rsanchez
2014-11-14 8076f3e62e24f23cc8eb866fe18cc6f00ceb02b8
securis/src/main/java/net/curisit/securis/SeCurisServer.java
....@@ -1,243 +1,219 @@
11 package net.curisit.securis;
22
3
-import java.io.File;
4
-import java.io.IOException;
5
-import java.lang.management.ManagementFactory;
6
-import java.net.URI;
7
-import java.net.URISyntaxException;
8
-import java.util.Properties;
9
-
10
-import javax.inject.Inject;
11
-import javax.inject.Named;
12
-
13
-import net.curisit.securis.ioc.RequestsModule;
14
-import net.curisit.securis.ioc.SecurisModule;
15
-import net.curisit.securis.utils.Config;
16
-
17
-import org.apache.commons.io.FileUtils;
183 import org.apache.logging.log4j.LogManager;
194 import org.apache.logging.log4j.Logger;
20
-import org.eclipse.jetty.http.HttpVersion;
21
-import org.eclipse.jetty.server.Handler;
22
-import org.eclipse.jetty.server.HttpConfiguration;
23
-import org.eclipse.jetty.server.HttpConnectionFactory;
24
-import org.eclipse.jetty.server.SecureRequestCustomizer;
25
-import org.eclipse.jetty.server.Server;
26
-import org.eclipse.jetty.server.ServerConnector;
27
-import org.eclipse.jetty.server.SslConnectionFactory;
28
-import org.eclipse.jetty.server.handler.ContextHandlerCollection;
29
-import org.eclipse.jetty.server.handler.ResourceHandler;
30
-import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
31
-import org.eclipse.jetty.servlet.FilterHolder;
32
-import org.eclipse.jetty.servlet.ServletContextHandler;
33
-import org.eclipse.jetty.servlet.ServletHolder;
34
-import org.eclipse.jetty.util.component.AbstractLifeCycle.AbstractLifeCycleListener;
35
-import org.eclipse.jetty.util.component.LifeCycle;
36
-import org.eclipse.jetty.util.resource.Resource;
37
-import org.eclipse.jetty.util.ssl.SslContextFactory;
38
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
39
-import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener;
40
-import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
41
-
42
-import com.google.inject.Guice;
43
-import com.google.inject.Injector;
44
-import com.google.inject.Key;
45
-import com.google.inject.name.Names;
46
-import com.google.inject.persist.PersistFilter;
47
-import com.google.inject.persist.jpa.JpaPersistModule;
485
496 public class SeCurisServer {
507
518 private static final Logger LOG = LogManager.getLogger(SeCurisServer.class);
529 private static final Logger CONSOLE = LogManager.getLogger("console");
53
-
54
- private static final String PID_FILE = System.getProperty("user.home") + "/.SeCuris/securis-server.pid";
55
-
56
- private static Server server;
57
- private static Injector injector = null;
58
-
59
- @Inject
60
- @Named("base-uri")
61
- private URI uri;
62
-
63
- private static void showHelp() {
64
- CONSOLE.info("Execute SeCuris server using:");
65
- CONSOLE.info(" $ ./securis-server.sh {start|stop}");
66
- }
67
-
68
- public static void main(String[] args) throws Exception {
69
- String command;
70
- if (args.length > 0) {
71
- command = args[0].toLowerCase();
72
- } else {
73
- command = "start";
74
- }
75
-
76
- switch (command) {
77
- case "start":
78
- startServer();
79
- break;
80
- case "stop":
81
- stopServer();
82
- break;
83
-
84
- default:
85
- showHelp();
86
- System.exit(-1);
87
- }
88
- }
89
-
90
- private static void stopServer() {
91
- if (!new File(PID_FILE).exists()) {
92
- CONSOLE.error("SeCuris server is NOT running or PID file is missing");
93
- System.exit(-3);
94
- }
95
- try {
96
- int pid = Integer.parseInt(FileUtils.readFileToString(new File(PID_FILE)));
97
- Runtime.getRuntime().exec("kill -SIGINT " + pid);
98
- new File(PID_FILE).delete();
99
- CONSOLE.info("SeCuris server process stopped sucessfully (PID: {})", pid);
100
- } catch (NumberFormatException | IOException e) {
101
- LOG.error("Error getting SeCuris server process PID from file: {}", PID_FILE);
102
- }
103
- }
104
-
105
- private static void startServer() {
106
-
107
- if (new File(PID_FILE).exists()) {
108
- try {
109
- CONSOLE.error("SeCuris server is already running with PID: {}", FileUtils.readFileToString(new File(PID_FILE)));
110
- } catch (IOException e) {
111
- LOG.error("Unexpected error", e);
112
- }
113
- System.exit(-2);
114
- }
115
-
116
- SecurisModule securisModule = new SecurisModule();
117
- JpaPersistModule jpaPersistModule = new JpaPersistModule("localdb");
118
- Properties props = new Properties();
119
- props.put("javax.persistence.jdbc.password", securisModule.getPassword());
120
- props.put("javax.persistence.jdbc.url", securisModule.getUrl(securisModule.getAppDir()));
121
- // LOG.info("BD Url: {} {}",
122
- // securisModule.getUrl(securisModule.getAppDir()),
123
- // securisModule.getPassword());
124
- jpaPersistModule.properties(props);
125
-
126
- injector = Guice.createInjector(securisModule, new RequestsModule(), jpaPersistModule);
127
-
128
- try {
129
- startServer(injector.getInstance(Key.get(URI.class, Names.named("base-uri"))));
130
-
131
- } catch (SeCurisException e) {
132
- CONSOLE.error("Error launching the SeCuris server, {}", e);
133
- }
134
- }
135
-
136
- private static void savePID() throws SeCurisException {
137
- String runtimeName = ManagementFactory.getRuntimeMXBean().getName();
138
- // runtimeName contains something like: "12345@localhost"
139
- String pid = runtimeName.substring(0, runtimeName.indexOf('@'));
140
- try {
141
- FileUtils.writeStringToFile(new File(PID_FILE), pid);
142
- CONSOLE.info("SeCuris server process started sucessfully (PID: {})", pid);
143
- } catch (IOException e) {
144
- LOG.error("Error saving pid file", e);
145
- throw new SeCurisException("Error saving pid file");
146
- }
147
- }
148
-
149
- private static void startServer(URI uri) throws SeCurisException {
150
- System.out.println("Starting jetty...");
151
-
152
- QueuedThreadPool threadPool = new QueuedThreadPool();
153
- threadPool.setMaxThreads(50);
154
-
155
- server = new Server();
156
-
157
- ServerConnector httpConnector = new ServerConnector(server);
158
- httpConnector.setPort(Config.getInt(Config.KEYS.SERVER_PORT, 9080));
159
- httpConnector.setHost(Config.get(Config.KEYS.SERVER_HOSTNAME, "0.0.0.0"));
160
- server.addConnector(httpConnector);
161
-
162
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
163
- context.setContextPath("/");
164
- context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
165
-
166
- context.setInitParameter("resteasy.role.based.security", "true");
167
- context.setInitParameter("resteasy.providers", DefaultExceptionHandler.class.getName());
168
- context.addFilter(new FilterHolder(injector.getInstance(PersistFilter.class)), "/*", null);
169
- ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
170
- sh.setName("resteasy");
171
- context.addServlet(sh, "/*");
172
-
173
- ResourceHandler staticResources = new ResourceHandler();
174
- try {
175
- staticResources.setBaseResource(Resource.newResource(SeCurisServer.class.getResource("/static").toURI()));
176
- } catch (IOException | URISyntaxException e) {
177
- LOG.error("Error configuring static resources", e);
178
- throw new SeCurisException("Error configuring static resources");
179
- }
180
- staticResources.setWelcomeFiles(new String[] {
181
- "/main.html"
182
- });
183
- context.setHandler(staticResources);
184
-
185
- ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
186
- context.setErrorHandler(errorHandler);
187
- ContextHandlerCollection contexts = new ContextHandlerCollection();
188
-
189
- contexts.setHandlers(new Handler[] {
190
- staticResources, context
191
- });
192
-
193
- HttpConfiguration http_config = new HttpConfiguration();
194
- http_config.setSecureScheme("https");
195
- http_config.setSecurePort(Config.getInt(Config.KEYS.SERVER_SSL_PORT, 9443));
196
- http_config.setOutputBufferSize(32768);
197
- http_config.setSendServerVersion(true);
198
- http_config.setSendDateHeader(false);
199
-
200
- HttpConfiguration https_config = new HttpConfiguration(http_config);
201
- https_config.addCustomizer(new SecureRequestCustomizer());
202
-
203
- SslContextFactory sslContextFactory = new SslContextFactory();
204
- sslContextFactory.setKeyStorePath(Config.get(Config.KEYS.KEYSTORE_PATH));
205
- sslContextFactory.setKeyStoreType(Config.get(Config.KEYS.KEYSTORE_TYPE, "JKS"));
206
- sslContextFactory.setKeyStorePassword(Config.get(Config.KEYS.KEYSTORE_PASSWORD, ""));
207
- // sslContextFactory.setCertAlias("1");
208
- // sslContextFactory.setKeyManagerPassword("curist3c");
209
- // sslContextFactory.setTrustStorePath("/Users/rob/.ssh/keys/keystore");
210
- // sslContextFactory.setTrustStorePassword("curist3c");
211
- sslContextFactory.checkKeyStore();
212
- sslContextFactory.setNeedClientAuth(false);
213
-
214
- ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
215
- new HttpConnectionFactory(https_config));
216
- sslConnector.setPort(Config.getInt(Config.KEYS.SERVER_SSL_PORT, 9443));
217
- sslConnector.setHost(Config.get(Config.KEYS.SERVER_HOSTNAME, "0.0.0.0"));
218
- server.addConnector(sslConnector);
219
-
220
- server.setHandler(context);
221
- server.setStopAtShutdown(true);
222
- server.addLifeCycleListener(new ServerStoppedListener());
223
- try {
224
- server.start();
225
- savePID();
226
- CONSOLE.info("Server running in: {}", String.format("http://%s:%d", httpConnector.getHost(), httpConnector.getPort()));
227
- server.join();
228
- } catch (Exception e) {
229
- LOG.error("Error starting SeCurisServer", e);
230
- throw new SeCurisException("Error starting SeCurisServer");
231
- }
232
-
233
- }
234
-
235
- static class ServerStoppedListener extends AbstractLifeCycleListener {
236
- @Override
237
- public void lifeCycleStopped(LifeCycle event) {
238
- if (new File(PID_FILE).exists())
239
- new File(PID_FILE).delete();
240
- }
241
- }
10
+ //
11
+ // private static final String PID_FILE = System.getProperty("user.home") +
12
+ // "/.SeCuris/securis-server.pid";
13
+ //
14
+ // private static Server server;
15
+ // private static Injector injector = null;
16
+ //
17
+ // @Inject
18
+ // @Named("base-uri")
19
+ // private URI uri;
20
+ //
21
+ // private static void showHelp() {
22
+ // CONSOLE.info("Execute SeCuris server using:");
23
+ // CONSOLE.info(" $ ./securis-server.sh {start|stop}");
24
+ // }
25
+ //
26
+ // public static void main(String[] args) throws Exception {
27
+ // String command;
28
+ // if (args.length > 0) {
29
+ // command = args[0].toLowerCase();
30
+ // } else {
31
+ // command = "start";
32
+ // }
33
+ //
34
+ // switch (command) {
35
+ // case "start":
36
+ // startServer();
37
+ // break;
38
+ // case "stop":
39
+ // stopServer();
40
+ // break;
41
+ //
42
+ // default:
43
+ // showHelp();
44
+ // System.exit(-1);
45
+ // }
46
+ // }
47
+ //
48
+ // private static void stopServer() {
49
+ // if (!new File(PID_FILE).exists()) {
50
+ // CONSOLE.error("SeCuris server is NOT running or PID file is missing");
51
+ // System.exit(-3);
52
+ // }
53
+ // try {
54
+ // int pid = Integer.parseInt(FileUtils.readFileToString(new
55
+ // File(PID_FILE)));
56
+ // Runtime.getRuntime().exec("kill -SIGINT " + pid);
57
+ // new File(PID_FILE).delete();
58
+ // CONSOLE.info("SeCuris server process stopped sucessfully (PID: {})",
59
+ // pid);
60
+ // } catch (NumberFormatException | IOException e) {
61
+ // LOG.error("Error getting SeCuris server process PID from file: {}",
62
+ // PID_FILE);
63
+ // }
64
+ // }
65
+ //
66
+ // private static void startServer() {
67
+ //
68
+ // if (new File(PID_FILE).exists()) {
69
+ // try {
70
+ // CONSOLE.error("SeCuris server is already running with PID: {}",
71
+ // FileUtils.readFileToString(new File(PID_FILE)));
72
+ // } catch (IOException e) {
73
+ // LOG.error("Unexpected error", e);
74
+ // }
75
+ // System.exit(-2);
76
+ // }
77
+ //
78
+ // SecurisModule securisModule = new SecurisModule();
79
+ // JpaPersistModule jpaPersistModule = new JpaPersistModule("localdb");
80
+ // Properties props = new Properties();
81
+ // props.put("javax.persistence.jdbc.password",
82
+ // securisModule.getPassword());
83
+ // props.put("javax.persistence.jdbc.url",
84
+ // securisModule.getUrl(securisModule.getAppDir()));
85
+ // // LOG.info("BD Url: {} {}",
86
+ // // securisModule.getUrl(securisModule.getAppDir()),
87
+ // // securisModule.getPassword());
88
+ // jpaPersistModule.properties(props);
89
+ //
90
+ // injector = Guice.createInjector(securisModule, new RequestsModule(),
91
+ // jpaPersistModule);
92
+ //
93
+ // try {
94
+ // startServer(injector.getInstance(Key.get(URI.class,
95
+ // Names.named("base-uri"))));
96
+ //
97
+ // } catch (SeCurisException e) {
98
+ // CONSOLE.error("Error launching the SeCuris server, {}", e);
99
+ // }
100
+ // }
101
+ //
102
+ // private static void savePID() throws SeCurisException {
103
+ // String runtimeName = ManagementFactory.getRuntimeMXBean().getName();
104
+ // // runtimeName contains something like: "12345@localhost"
105
+ // String pid = runtimeName.substring(0, runtimeName.indexOf('@'));
106
+ // try {
107
+ // FileUtils.writeStringToFile(new File(PID_FILE), pid);
108
+ // CONSOLE.info("SeCuris server process started sucessfully (PID: {})",
109
+ // pid);
110
+ // } catch (IOException e) {
111
+ // LOG.error("Error saving pid file", e);
112
+ // throw new SeCurisException("Error saving pid file");
113
+ // }
114
+ // }
115
+ //
116
+ // private static void startServer(URI uri) throws SeCurisException {
117
+ // System.out.println("Starting jetty...");
118
+ //
119
+ // QueuedThreadPool threadPool = new QueuedThreadPool();
120
+ // threadPool.setMaxThreads(50);
121
+ //
122
+ // server = new Server();
123
+ //
124
+ // ServerConnector httpConnector = new ServerConnector(server);
125
+ // httpConnector.setPort(Config.getInt(Config.KEYS.SERVER_PORT, 9080));
126
+ // httpConnector.setHost(Config.get(Config.KEYS.SERVER_HOSTNAME,
127
+ // "0.0.0.0"));
128
+ // server.addConnector(httpConnector);
129
+ //
130
+ // ServletContextHandler context = new
131
+ // ServletContextHandler(ServletContextHandler.SESSIONS);
132
+ // context.setContextPath("/");
133
+ // context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
134
+ //
135
+ // context.setInitParameter("resteasy.role.based.security", "true");
136
+ // context.setInitParameter("resteasy.providers",
137
+ // DefaultExceptionHandler.class.getName());
138
+ // context.addFilter(new
139
+ // FilterHolder(injector.getInstance(PersistFilter.class)), "/*", null);
140
+ // ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
141
+ // sh.setName("resteasy");
142
+ // context.addServlet(sh, "/*");
143
+ //
144
+ // ResourceHandler staticResources = new ResourceHandler();
145
+ // try {
146
+ // staticResources.setBaseResource(Resource.newResource(SeCurisServer.class.getResource("/static").toURI()));
147
+ // } catch (IOException | URISyntaxException e) {
148
+ // LOG.error("Error configuring static resources", e);
149
+ // throw new SeCurisException("Error configuring static resources");
150
+ // }
151
+ // staticResources.setWelcomeFiles(new String[] {
152
+ // "/main.html"
153
+ // });
154
+ // context.setHandler(staticResources);
155
+ //
156
+ // ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
157
+ // context.setErrorHandler(errorHandler);
158
+ // ContextHandlerCollection contexts = new ContextHandlerCollection();
159
+ //
160
+ // contexts.setHandlers(new Handler[] {
161
+ // staticResources, context
162
+ // });
163
+ //
164
+ // HttpConfiguration http_config = new HttpConfiguration();
165
+ // http_config.setSecureScheme("https");
166
+ // http_config.setSecurePort(Config.getInt(Config.KEYS.SERVER_SSL_PORT,
167
+ // 9443));
168
+ // http_config.setOutputBufferSize(32768);
169
+ // http_config.setSendServerVersion(true);
170
+ // http_config.setSendDateHeader(false);
171
+ //
172
+ // HttpConfiguration https_config = new HttpConfiguration(http_config);
173
+ // https_config.addCustomizer(new SecureRequestCustomizer());
174
+ //
175
+ // SslContextFactory sslContextFactory = new SslContextFactory();
176
+ // sslContextFactory.setKeyStorePath(Config.get(Config.KEYS.KEYSTORE_PATH));
177
+ // sslContextFactory.setKeyStoreType(Config.get(Config.KEYS.KEYSTORE_TYPE,
178
+ // "JKS"));
179
+ // sslContextFactory.setKeyStorePassword(Config.get(Config.KEYS.KEYSTORE_PASSWORD,
180
+ // ""));
181
+ // // sslContextFactory.setCertAlias("1");
182
+ // // sslContextFactory.setKeyManagerPassword("curist3c");
183
+ // // sslContextFactory.setTrustStorePath("/Users/rob/.ssh/keys/keystore");
184
+ // // sslContextFactory.setTrustStorePassword("curist3c");
185
+ // sslContextFactory.checkKeyStore();
186
+ // sslContextFactory.setNeedClientAuth(false);
187
+ //
188
+ // ServerConnector sslConnector = new ServerConnector(server, new
189
+ // SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
190
+ // new HttpConnectionFactory(https_config));
191
+ // sslConnector.setPort(Config.getInt(Config.KEYS.SERVER_SSL_PORT, 9443));
192
+ // sslConnector.setHost(Config.get(Config.KEYS.SERVER_HOSTNAME, "0.0.0.0"));
193
+ // server.addConnector(sslConnector);
194
+ //
195
+ // server.setHandler(context);
196
+ // server.setStopAtShutdown(true);
197
+ // server.addLifeCycleListener(new ServerStoppedListener());
198
+ // try {
199
+ // server.start();
200
+ // savePID();
201
+ // CONSOLE.info("Server running in: {}", String.format("http://%s:%d",
202
+ // httpConnector.getHost(), httpConnector.getPort()));
203
+ // server.join();
204
+ // } catch (Exception e) {
205
+ // LOG.error("Error starting SeCurisServer", e);
206
+ // throw new SeCurisException("Error starting SeCurisServer");
207
+ // }
208
+ //
209
+ // }
210
+ //
211
+ // static class ServerStoppedListener extends AbstractLifeCycleListener {
212
+ // @Override
213
+ // public void lifeCycleStopped(LifeCycle event) {
214
+ // if (new File(PID_FILE).exists())
215
+ // new File(PID_FILE).delete();
216
+ // }
217
+ // }
242218
243219 }