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;
27 import javax.servlet.DispatcherType;
29 import org.eclipse.jetty.security.ConstraintMapping;
30 import org.eclipse.jetty.security.ConstraintSecurityHandler;
31 import org.eclipse.jetty.security.HashLoginService;
32 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
33 import org.eclipse.jetty.server.HttpConfiguration;
34 import org.eclipse.jetty.server.HttpConnectionFactory;
35 import org.eclipse.jetty.server.SecureRequestCustomizer;
36 import org.eclipse.jetty.server.Server;
37 import org.eclipse.jetty.server.ServerConnector;
38 import org.eclipse.jetty.server.Slf4jRequestLog;
39 import org.eclipse.jetty.servlet.ServletContextHandler;
40 import org.eclipse.jetty.util.security.Constraint;
41 import org.eclipse.jetty.util.security.Credential;
42 import org.eclipse.jetty.util.ssl.SslContextFactory;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Http Server implementation using Embedded Jetty.
50 public abstract class JettyServletServer implements HttpServletServer, Runnable {
53 * Keystore/Truststore system property names.
55 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
56 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword";
57 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
58 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword";
63 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
68 protected final String name;
71 * Server host address.
73 protected final String host;
76 * Server port to bind.
78 protected final int port;
81 * Server auth user name.
83 protected String user;
86 * Server auth password name.
88 protected String password;
91 * Server base context path.
93 protected final String contextPath;
96 * Embedded jetty server.
98 protected final Server jettyServer;
103 protected final ServletContextHandler context;
108 protected final ServerConnector connector;
113 protected volatile Thread jettyThread;
118 protected Object startCondition = new Object();
123 * @param name server name
124 * @param host server host
125 * @param port server port
126 * @param contextPath context path
128 * @throws IllegalArgumentException if invalid parameters are passed in
130 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
131 String srvName = name;
133 if (srvName == null || srvName.isEmpty()) {
134 srvName = "http-" + port;
137 if (port <= 0 || port >= 65535) {
138 throw new IllegalArgumentException("Invalid Port provided: " + port);
141 String srvHost = host;
142 if (srvHost == null || srvHost.isEmpty()) {
143 srvHost = "localhost";
146 String ctxtPath = contextPath;
147 if (ctxtPath == null || ctxtPath.isEmpty()) {
156 this.contextPath = ctxtPath;
158 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
159 this.context.setContextPath(ctxtPath);
161 this.jettyServer = new Server();
162 this.jettyServer.setRequestLog(new Slf4jRequestLog());
165 this.connector = httpsConnector();
167 this.connector = httpConnector();
170 this.connector.setName(srvName);
171 this.connector.setReuseAddress(true);
172 this.connector.setPort(port);
173 this.connector.setHost(srvHost);
175 this.jettyServer.addConnector(this.connector);
176 this.jettyServer.setHandler(context);
179 public JettyServletServer(String name, String host, int port, String contextPath) {
180 this(name, false, host, port, contextPath);
184 public void addFilterClass(String filterPath, String filterClass) {
185 if (filterClass == null || filterClass.isEmpty()) {
186 throw new IllegalArgumentException("No filter class provided");
189 String tempFilterPath = filterPath;
190 if (filterPath == null || filterPath.isEmpty()) {
191 tempFilterPath = "/*";
194 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
198 * Returns the https connector.
202 public ServerConnector httpsConnector() {
203 SslContextFactory sslContextFactory = new SslContextFactory();
205 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
206 if (keyStore != null) {
207 sslContextFactory.setKeyStorePath(keyStore);
209 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
210 if (ksPassword != null) {
211 sslContextFactory.setKeyStorePassword(ksPassword);
215 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
216 if (trustStore != null) {
217 sslContextFactory.setTrustStorePath(trustStore);
219 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
220 if (tsPassword != null) {
221 sslContextFactory.setTrustStorePassword(tsPassword);
225 HttpConfiguration https = new HttpConfiguration();
226 https.addCustomizer(new SecureRequestCustomizer());
228 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
231 public ServerConnector httpConnector() {
232 return new ServerConnector(this.jettyServer);
236 public void setBasicAuthentication(String user, String password, String servletPath) {
237 String srvltPath = servletPath;
239 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
240 throw new IllegalArgumentException("Missing user and/or password");
243 if (srvltPath == null || srvltPath.isEmpty()) {
247 HashLoginService hashLoginService = new HashLoginService();
248 hashLoginService.putUser(user, Credential.getCredential(password), new String[] {"user"});
249 hashLoginService.setName(this.connector.getName() + "-login-service");
251 Constraint constraint = new Constraint();
252 constraint.setName(Constraint.__BASIC_AUTH);
253 constraint.setRoles(new String[] {"user"});
254 constraint.setAuthenticate(true);
256 ConstraintMapping constraintMapping = new ConstraintMapping();
257 constraintMapping.setConstraint(constraint);
258 constraintMapping.setPathSpec(srvltPath);
260 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
261 securityHandler.setAuthenticator(new BasicAuthenticator());
262 securityHandler.setRealmName(this.connector.getName() + "-realm");
263 securityHandler.addConstraintMapping(constraintMapping);
264 securityHandler.setLoginService(hashLoginService);
266 this.context.setSecurityHandler(securityHandler);
269 this.password = password;
273 * jetty server execution.
278 logger.info("{}: STARTING", this);
280 this.jettyServer.start();
282 if (logger.isInfoEnabled()) {
283 logger.info("{}: STARTED: {}", this, this.jettyServer.dump());
286 synchronized (this.startCondition) {
287 this.startCondition.notifyAll();
290 this.jettyServer.join();
291 } catch (Exception e) {
292 logger.error("{}: error found while bringing up server", this, e);
297 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
298 logger.info("{}: WAITED-START", this);
300 if (maxWaitTime < 0) {
301 throw new IllegalArgumentException("max-wait-time cannot be negative");
304 long pendingWaitTime = maxWaitTime;
310 synchronized (this.startCondition) {
312 while (!this.jettyServer.isRunning()) {
314 long startTs = System.currentTimeMillis();
316 this.startCondition.wait(pendingWaitTime);
318 if (maxWaitTime == 0) {
319 /* spurious notification */
323 long endTs = System.currentTimeMillis();
324 pendingWaitTime = pendingWaitTime - (endTs - startTs);
326 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
328 if (pendingWaitTime <= 0) {
332 } catch (InterruptedException e) {
333 logger.warn("{}: waited-start has been interrupted", this);
338 return this.jettyServer.isRunning();
343 public boolean start() {
344 logger.info("{}: STARTING", this);
346 synchronized (this) {
347 if (jettyThread == null || !this.jettyThread.isAlive()) {
349 this.jettyThread = new Thread(this);
350 this.jettyThread.setName(this.name + "-" + this.port);
351 this.jettyThread.start();
359 public boolean stop() {
360 logger.info("{}: STOPPING", this);
362 synchronized (this) {
363 if (jettyThread == null) {
367 if (!jettyThread.isAlive()) {
368 this.jettyThread = null;
372 this.connector.stop();
373 } catch (Exception e) {
374 logger.error("{}: error while stopping management server", this, e);
378 this.jettyServer.stop();
379 } catch (Exception e) {
380 logger.error("{}: error while stopping management server", this, e);
391 public void shutdown() {
392 logger.info("{}: SHUTTING DOWN", this);
396 if (this.jettyThread == null) {
400 Thread jettyThreadCopy = this.jettyThread;
402 if (jettyThreadCopy.isAlive()) {
404 jettyThreadCopy.join(2000L);
405 } catch (InterruptedException e) {
406 logger.warn("{}: error while shutting down management server", this);
407 Thread.currentThread().interrupt();
409 if (!jettyThreadCopy.isInterrupted()) {
411 jettyThreadCopy.interrupt();
412 } catch (Exception e) {
414 logger.warn("{}: exception while shutting down (OK)", this, e);
419 this.jettyServer.destroy();
423 public boolean isAlive() {
424 if (this.jettyThread != null) {
425 return this.jettyThread.isAlive();
432 public int getPort() {
441 public String getName() {
450 public String getHost() {
459 public String getUser() {
466 * @return the password
469 public String getPassword() {
474 public String toString() {
475 StringBuilder builder = new StringBuilder();
476 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
477 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
478 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
479 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
480 .append(jettyThread).append("]");
481 return builder.toString();