2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.common.endpoints.http.server.internal;
23 import com.fasterxml.jackson.annotation.JsonIgnore;
25 import java.util.EnumSet;
26 import javax.servlet.DispatcherType;
27 import org.eclipse.jetty.security.ConstraintMapping;
28 import org.eclipse.jetty.security.ConstraintSecurityHandler;
29 import org.eclipse.jetty.security.HashLoginService;
30 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
31 import org.eclipse.jetty.server.HttpConfiguration;
32 import org.eclipse.jetty.server.HttpConnectionFactory;
33 import org.eclipse.jetty.server.SecureRequestCustomizer;
34 import org.eclipse.jetty.server.Server;
35 import org.eclipse.jetty.server.ServerConnector;
36 import org.eclipse.jetty.server.Slf4jRequestLog;
37 import org.eclipse.jetty.servlet.ServletContextHandler;
38 import org.eclipse.jetty.util.security.Constraint;
39 import org.eclipse.jetty.util.security.Credential;
40 import org.eclipse.jetty.util.ssl.SslContextFactory;
41 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Http Server implementation using Embedded Jetty.
48 public abstract class JettyServletServer implements HttpServletServer, Runnable {
51 * Keystore/Truststore system property names.
53 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
54 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword";
55 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
56 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword";
61 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
66 protected final String name;
69 * Server host address.
71 protected final String host;
74 * Server port to bind.
76 protected final int port;
79 * Server auth user name.
81 protected String user;
84 * Server auth password name.
86 protected String password;
89 * Server base context path.
91 protected final String contextPath;
94 * Embedded jetty server.
96 protected final Server jettyServer;
101 protected final ServletContextHandler context;
106 protected final ServerConnector connector;
111 protected volatile Thread jettyThread;
116 protected Object startCondition = new Object();
121 * @param name server name
122 * @param host server host
123 * @param port server port
124 * @param contextPath context path
126 * @throws IllegalArgumentException if invalid parameters are passed in
128 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
129 String srvName = name;
131 if (srvName == null || srvName.isEmpty()) {
132 srvName = "http-" + port;
135 if (port <= 0 || port >= 65535) {
136 throw new IllegalArgumentException("Invalid Port provided: " + port);
139 String srvHost = host;
140 if (srvHost == null || srvHost.isEmpty()) {
141 srvHost = "localhost";
144 String ctxtPath = contextPath;
145 if (ctxtPath == null || ctxtPath.isEmpty()) {
154 this.contextPath = ctxtPath;
156 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
157 this.context.setContextPath(ctxtPath);
159 this.jettyServer = new Server();
160 this.jettyServer.setRequestLog(new Slf4jRequestLog());
163 this.connector = httpsConnector();
165 this.connector = httpConnector();
168 this.connector.setName(srvName);
169 this.connector.setReuseAddress(true);
170 this.connector.setPort(port);
171 this.connector.setHost(srvHost);
173 this.jettyServer.addConnector(this.connector);
174 this.jettyServer.setHandler(context);
177 public JettyServletServer(String name, String host, int port, String contextPath) {
178 this(name, false, host, port, contextPath);
182 public void addFilterClass(String filterPath, String filterClass) {
183 if (filterClass == null || filterClass.isEmpty()) {
184 throw new IllegalArgumentException("No filter class provided");
187 String tempFilterPath = filterPath;
188 if (filterPath == null || filterPath.isEmpty()) {
189 tempFilterPath = "/*";
192 context.addFilter(filterClass, tempFilterPath,
193 EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
197 * Returns the https connector.
201 public ServerConnector httpsConnector() {
202 SslContextFactory sslContextFactory = new SslContextFactory();
204 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
205 if (keyStore != null) {
206 sslContextFactory.setKeyStorePath(keyStore);
208 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
209 if (ksPassword != null) {
210 sslContextFactory.setKeyStorePassword(ksPassword);
214 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
215 if (trustStore != null) {
216 sslContextFactory.setTrustStorePath(trustStore);
218 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
219 if (tsPassword != null) {
220 sslContextFactory.setTrustStorePassword(tsPassword);
224 HttpConfiguration https = new HttpConfiguration();
225 https.addCustomizer(new SecureRequestCustomizer());
227 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
230 public ServerConnector httpConnector() {
231 return new ServerConnector(this.jettyServer);
235 public void setBasicAuthentication(String user, String password, String servletPath) {
236 String srvltPath = servletPath;
238 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
239 throw new IllegalArgumentException("Missing user and/or password");
242 if (srvltPath == null || srvltPath.isEmpty()) {
246 HashLoginService hashLoginService = new HashLoginService();
247 hashLoginService.putUser(user, Credential.getCredential(password), new String[] {"user"});
248 hashLoginService.setName(this.connector.getName() + "-login-service");
250 Constraint constraint = new Constraint();
251 constraint.setName(Constraint.__BASIC_AUTH);
252 constraint.setRoles(new String[] {"user"});
253 constraint.setAuthenticate(true);
255 ConstraintMapping constraintMapping = new ConstraintMapping();
256 constraintMapping.setConstraint(constraint);
257 constraintMapping.setPathSpec(srvltPath);
259 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
260 securityHandler.setAuthenticator(new BasicAuthenticator());
261 securityHandler.setRealmName(this.connector.getName() + "-realm");
262 securityHandler.addConstraintMapping(constraintMapping);
263 securityHandler.setLoginService(hashLoginService);
265 this.context.setSecurityHandler(securityHandler);
268 this.password = password;
272 * jetty server execution.
277 logger.info("{}: STARTING", this);
279 this.jettyServer.start();
281 if (logger.isInfoEnabled()) {
282 logger.info("{}: STARTED: {}", this, this.jettyServer.dump());
285 synchronized (this.startCondition) {
286 this.startCondition.notifyAll();
289 this.jettyServer.join();
290 } catch (Exception e) {
291 logger.error("{}: error found while bringing up server", this, e);
296 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
297 logger.info("{}: WAITED-START", this);
299 if (maxWaitTime < 0) {
300 throw new IllegalArgumentException("max-wait-time cannot be negative");
303 long pendingWaitTime = maxWaitTime;
309 synchronized (this.startCondition) {
311 while (!this.jettyServer.isRunning()) {
313 long startTs = System.currentTimeMillis();
315 this.startCondition.wait(pendingWaitTime);
317 if (maxWaitTime == 0) {
318 /* spurious notification */
322 long endTs = System.currentTimeMillis();
323 pendingWaitTime = pendingWaitTime - (endTs - startTs);
325 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
327 if (pendingWaitTime <= 0) {
331 } catch (InterruptedException e) {
332 logger.warn("{}: waited-start has been interrupted", this);
337 return this.jettyServer.isRunning();
342 public boolean start() {
343 logger.info("{}: STARTING", this);
345 synchronized (this) {
346 if (jettyThread == null || !this.jettyThread.isAlive()) {
348 this.jettyThread = new Thread(this);
349 this.jettyThread.setName(this.name + "-" + this.port);
350 this.jettyThread.start();
358 public boolean stop() {
359 logger.info("{}: STOPPING", this);
361 synchronized (this) {
362 if (jettyThread == null) {
366 if (!jettyThread.isAlive()) {
367 this.jettyThread = null;
371 this.connector.stop();
372 } catch (Exception e) {
373 logger.error("{}: error while stopping management server", this, e);
377 this.jettyServer.stop();
378 } catch (Exception e) {
379 logger.error("{}: error while stopping management server", this, e);
390 public void shutdown() {
391 logger.info("{}: SHUTTING DOWN", this);
395 if (this.jettyThread == null) {
399 Thread jettyThreadCopy = this.jettyThread;
401 if (jettyThreadCopy.isAlive()) {
403 jettyThreadCopy.join(2000L);
404 } catch (InterruptedException e) {
405 logger.warn("{}: error while shutting down management server", this);
406 Thread.currentThread().interrupt();
408 if (!jettyThreadCopy.isInterrupted()) {
410 jettyThreadCopy.interrupt();
411 } catch (Exception e) {
413 logger.warn("{}: exception while shutting down (OK)", this, e);
418 this.jettyServer.destroy();
422 public boolean isAlive() {
423 if (this.jettyThread != null) {
424 return this.jettyThread.isAlive();
431 public int getPort() {
440 public String getName() {
449 public String getHost() {
458 public String getUser() {
465 * @return the password
468 public String getPassword() {
473 public String toString() {
474 StringBuilder builder = new StringBuilder();
475 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
476 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
477 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
478 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
479 .append(jettyThread).append("]");
480 return builder.toString();