File: HttpServerManager.java

package info (click to toggle)
eclipse 3.8.1-10
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 338,840 kB
  • ctags: 472,808
  • sloc: java: 2,762,042; ansic: 136,783; xml: 105,676; cpp: 35,759; jsp: 4,420; sh: 3,288; perl: 1,687; makefile: 232; python: 67; php: 24
file content (385 lines) | stat: -rw-r--r-- 13,812 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*******************************************************************************
 * Copyright (c) 2007, 2012 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

package org.eclipse.equinox.http.jetty.internal;

import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.*;
import org.eclipse.equinox.http.jetty.JettyConstants;
import org.eclipse.equinox.http.jetty.JettyCustomizer;
import org.eclipse.equinox.http.servlet.HttpServiceServlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.session.HashSessionManager;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedServiceFactory;

public class HttpServerManager implements ManagedServiceFactory {

	private static final String CONTEXT_TEMPDIR = "javax.servlet.context.tempdir"; //$NON-NLS-1$
	private static final String DIR_PREFIX = "pid_"; //$NON-NLS-1$
	private static final String INTERNAL_CONTEXT_CLASSLOADER = "org.eclipse.equinox.http.jetty.internal.ContextClassLoader"; //$NON-NLS-1$

	private Map<String, Server> servers = new HashMap<String, Server>();
	private File workDir;

	public HttpServerManager(File workDir) {
		this.workDir = workDir;
	}

	public synchronized void deleted(String pid) {
		Server server = servers.remove(pid);
		if (server != null) {
			try {
				server.stop();
			} catch (Exception e) {
				// TODO: consider logging this, but we should still continue cleaning up 
				e.printStackTrace();
			}
			File contextWorkDir = new File(workDir, DIR_PREFIX + pid.hashCode());
			deleteDirectory(contextWorkDir);
		}
	}

	public String getName() {
		return this.getClass().getName();
	}

	@SuppressWarnings("unchecked")
	public synchronized void updated(String pid, @SuppressWarnings("rawtypes") Dictionary dictionary) throws ConfigurationException {
		deleted(pid);
		Server server = new Server();

		JettyCustomizer customizer = createJettyCustomizer(dictionary);

		HttpConfiguration http_config = new HttpConfiguration();

		ServerConnector httpConnector = createHttpConnector(dictionary, server, http_config);
		if (null != customizer)
			httpConnector = (ServerConnector) customizer.customizeHttpConnector(httpConnector, dictionary);

		if (httpConnector != null)
			server.addConnector(httpConnector);

		ServerConnector httpsConnector = createHttpsConnector(dictionary, server, http_config);
		if (null != customizer)
			httpsConnector = (ServerConnector) customizer.customizeHttpsConnector(httpsConnector, dictionary);
		if (httpsConnector != null)
			server.addConnector(httpsConnector);

		ServletHolder holder = new ServletHolder(new InternalHttpServiceServlet());
		holder.setInitOrder(0);
		holder.setInitParameter(Constants.SERVICE_VENDOR, "Eclipse.org"); //$NON-NLS-1$
		holder.setInitParameter(Constants.SERVICE_DESCRIPTION, "Equinox Jetty-based Http Service"); //$NON-NLS-1$
		if (httpConnector != null) {
			int port = httpConnector.getLocalPort();
			if (port == -1)
				port = httpConnector.getPort();
			holder.setInitParameter(JettyConstants.HTTP_PORT, Integer.toString(port));
		}
		if (httpsConnector != null) {
			int port = httpsConnector.getLocalPort();
			if (port == -1)
				port = httpsConnector.getPort();
			holder.setInitParameter(JettyConstants.HTTPS_PORT, Integer.toString(port));
		}
		String otherInfo = (String) dictionary.get(JettyConstants.OTHER_INFO);
		if (otherInfo != null)
			holder.setInitParameter(JettyConstants.OTHER_INFO, otherInfo);

		ServletContextHandler httpContext = createHttpContext(dictionary);
		if (null != customizer)
			httpContext = (ServletContextHandler) customizer.customizeContext(httpContext, dictionary);

		httpContext.addServlet(holder, "/*"); //$NON-NLS-1$
		server.setHandler(httpContext);

		try {
			server.start();
		} catch (Exception e) {
			throw new ConfigurationException(pid, e.getMessage(), e);
		}
		servers.put(pid, server);
	}

	public synchronized void shutdown() throws Exception {
		for (Iterator<Server> it = servers.values().iterator(); it.hasNext();) {
			Server server = it.next();
			server.stop();
		}
		servers.clear();
	}

	private ServerConnector createHttpConnector(@SuppressWarnings("rawtypes") Dictionary dictionary, Server server, HttpConfiguration http_config) {
		Boolean httpEnabled = null;
		Object httpEnabledObj = dictionary.get(JettyConstants.HTTP_ENABLED);
		if (httpEnabledObj instanceof Boolean)
		{
			httpEnabled = (Boolean) httpEnabledObj;			
		}
		else
			if (httpEnabledObj instanceof String)
			{
				httpEnabled = Boolean.parseBoolean(httpEnabledObj.toString());
			}	
		if (httpEnabled != null && !httpEnabled.booleanValue())
			return null;

		
		Integer httpPort = getIntProperty(dictionary, JettyConstants.HTTP_PORT);
		if (httpPort == null)
			return null;

		if (isHttpsEnabled(dictionary)) {
			http_config.setSecureScheme("https");
			http_config.setSecurePort(getIntProperty(dictionary, JettyConstants.HTTPS_PORT));
		}

		ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(http_config));
		connector.setPort(httpPort.intValue());

		String httpHost = (String) dictionary.get(JettyConstants.HTTP_HOST);
		if (httpHost != null) {
			connector.setHost(httpHost);
		}

		if (connector.getPort() == 0) {
			try {
				connector.open();
			} catch (IOException e) {
				// this would be unexpected since we're opening the next available port 
				e.printStackTrace();
			}
		}
		return connector;
	}

	@SuppressWarnings("deprecation")
	private ServerConnector createHttpsConnector(@SuppressWarnings("rawtypes") Dictionary dictionary, Server server, HttpConfiguration http_config) {
		boolean httpsEnabled = isHttpsEnabled(dictionary);
		if (!httpsEnabled)
			return null;

		Integer httpsPort = getIntProperty(dictionary, JettyConstants.HTTPS_PORT);
		if (httpsPort == null)
			return null;

		SslContextFactory sslContextFactory = new SslContextFactory();

		String keyStore = (String) dictionary.get(JettyConstants.SSL_KEYSTORE);
		if (keyStore != null)
			sslContextFactory.setKeyStorePath(keyStore);

		String password = (String) dictionary.get(JettyConstants.SSL_PASSWORD);
		if (password != null)
			sslContextFactory.setKeyStorePassword(password);

		String keyPassword = (String) dictionary.get(JettyConstants.SSL_KEYPASSWORD);
		if (keyPassword != null)
			sslContextFactory.setKeyManagerPassword(keyPassword);

		Object needClientAuth = dictionary.get(JettyConstants.SSL_NEEDCLIENTAUTH);
		if (needClientAuth != null) {
			if (needClientAuth instanceof String)
				needClientAuth = Boolean.valueOf((String) needClientAuth);

			sslContextFactory.setNeedClientAuth(((Boolean) needClientAuth).booleanValue());
		}

		Object wantClientAuth = dictionary.get(JettyConstants.SSL_WANTCLIENTAUTH);
		if (wantClientAuth != null) {
			if (wantClientAuth instanceof String)
				wantClientAuth = Boolean.valueOf((String) wantClientAuth);

			sslContextFactory.setWantClientAuth(((Boolean) wantClientAuth).booleanValue());
		}

		String protocol = (String) dictionary.get(JettyConstants.SSL_PROTOCOL);
		if (protocol != null)
			sslContextFactory.setProtocol(protocol);

		String keystoreType = (String) dictionary.get(JettyConstants.SSL_KEYSTORETYPE);
		if (keystoreType != null)
			sslContextFactory.setKeyStoreType(keystoreType);

		HttpConfiguration https_config = new HttpConfiguration(http_config);
		https_config.addCustomizer(new SecureRequestCustomizer());

		ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
		sslConnector.setPort(httpsPort.intValue());

		String httpsHost = (String) dictionary.get(JettyConstants.HTTPS_HOST);
		if (httpsHost != null) {
			sslConnector.setHost(httpsHost);
		}

		if (sslConnector.getPort() == 0) {
			try {
				sslConnector.open();
			} catch (IOException e) {
				// this would be unexpected since we're opening the next available port 
				e.printStackTrace();
			}
		}
		return sslConnector;
	}

	private Integer getIntProperty(@SuppressWarnings("rawtypes") Dictionary dictionary, String property) {
		Integer httpPort = null;
		Object httpPortObj = dictionary.get(property);
		if (httpPortObj instanceof Integer) {
			httpPort = (Integer) httpPortObj;
		} else if (httpPortObj instanceof String) {
			httpPort = Integer.valueOf(httpPortObj.toString());
		}
		if (httpPort == null) {
			throw new IllegalArgumentException("Expected " + property + "property, but it is not set."); //$NON-NLS-1$//$NON-NLS-2$
		}
		return httpPort;
	}

	private boolean isHttpsEnabled(@SuppressWarnings("rawtypes") Dictionary dictionary) {
		Boolean httpsEnabled = false;
		Object httpsEnabledObj = dictionary.get(JettyConstants.HTTPS_ENABLED);
		if (httpsEnabledObj instanceof Boolean) {
			httpsEnabled = (Boolean) httpsEnabledObj;
		} else if (httpsEnabledObj instanceof String) {
			httpsEnabled = Boolean.parseBoolean(httpsEnabledObj.toString());
		}
		return httpsEnabled;
	}

	private ServletContextHandler createHttpContext(@SuppressWarnings("rawtypes") Dictionary dictionary) {
		ServletContextHandler httpContext = new ServletContextHandler();
		httpContext.setAttribute(INTERNAL_CONTEXT_CLASSLOADER, Thread.currentThread().getContextClassLoader());
		httpContext.setClassLoader(this.getClass().getClassLoader());

		String contextPathProperty = (String) dictionary.get(JettyConstants.CONTEXT_PATH);
		if (contextPathProperty == null)
			contextPathProperty = "/"; //$NON-NLS-1$
		httpContext.setContextPath(contextPathProperty);

		File contextWorkDir = new File(workDir, DIR_PREFIX + dictionary.get(Constants.SERVICE_PID).hashCode());
		contextWorkDir.mkdir();
		httpContext.setAttribute(CONTEXT_TEMPDIR, contextWorkDir);

		HashSessionManager sessionManager = new HashSessionManager();
		Integer sessionInactiveInterval = null;
		Object sessionInactiveIntervalObj = dictionary.get(JettyConstants.CONTEXT_SESSIONINACTIVEINTERVAL);
		if (sessionInactiveIntervalObj instanceof Integer)
		{
			sessionInactiveInterval = (Integer) sessionInactiveIntervalObj;
		}
		else
			if (sessionInactiveIntervalObj instanceof String)
			{
				sessionInactiveInterval = Integer.valueOf(sessionInactiveIntervalObj.toString());
			}
		if (sessionInactiveInterval != null)
			sessionManager.setMaxInactiveInterval(sessionInactiveInterval.intValue());

		httpContext.setSessionHandler(new SessionHandler(sessionManager));

		return httpContext;
	}

	private JettyCustomizer createJettyCustomizer(@SuppressWarnings("rawtypes") Dictionary dictionary) {
		String customizerClass = (String) dictionary.get(JettyConstants.CUSTOMIZER_CLASS);
		if (null == customizerClass)
			return null;

		try {
			return (JettyCustomizer) Class.forName(customizerClass).newInstance();
		} catch (Exception e) {
			// TODO: consider logging this, but we should still continue 
			e.printStackTrace();
			return null;
		}
	}

	public static class InternalHttpServiceServlet implements Servlet {
		//		private static final long serialVersionUID = 7477982882399972088L;
		private Servlet httpServiceServlet = new HttpServiceServlet();
		private ClassLoader contextLoader;

		public void init(ServletConfig config) throws ServletException {
			ServletContext context = config.getServletContext();
			contextLoader = (ClassLoader) context.getAttribute(INTERNAL_CONTEXT_CLASSLOADER);

			Thread thread = Thread.currentThread();
			ClassLoader current = thread.getContextClassLoader();
			thread.setContextClassLoader(contextLoader);
			try {
				httpServiceServlet.init(config);
			} finally {
				thread.setContextClassLoader(current);
			}
		}

		public void destroy() {
			Thread thread = Thread.currentThread();
			ClassLoader current = thread.getContextClassLoader();
			thread.setContextClassLoader(contextLoader);
			try {
				httpServiceServlet.destroy();
			} finally {
				thread.setContextClassLoader(current);
			}
			contextLoader = null;
		}

		public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
			Thread thread = Thread.currentThread();
			ClassLoader current = thread.getContextClassLoader();
			thread.setContextClassLoader(contextLoader);
			try {
				httpServiceServlet.service(req, res);
			} finally {
				thread.setContextClassLoader(current);
			}
		}

		public ServletConfig getServletConfig() {
			return httpServiceServlet.getServletConfig();
		}

		public String getServletInfo() {
			return httpServiceServlet.getServletInfo();
		}
	}

	// deleteDirectory is a convenience method to recursively delete a directory
	private static boolean deleteDirectory(File directory) {
		if (directory.exists() && directory.isDirectory()) {
			File[] files = directory.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return directory.delete();
	}
}