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;
130 String srvHost = host;
131 String ctxtPath = contextPath;
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 if (srvHost == null || srvHost.isEmpty()) {
142 srvHost = "localhost";
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 aFilterPath, String aFilterClass) {
183 if (aFilterClass == null || aFilterClass.isEmpty()) {
184 throw new IllegalArgumentException("No filter class provided");
187 String filterPath = aFilterPath;
188 if (aFilterPath == null || aFilterPath.isEmpty()) {
192 context.addFilter(aFilterClass, filterPath,
193 EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
196 public ServerConnector httpsConnector() {
197 SslContextFactory sslContextFactory = new SslContextFactory();
199 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
200 if (keyStore != null) {
201 sslContextFactory.setKeyStorePath(keyStore);
203 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
204 if (ksPassword != null) {
205 sslContextFactory.setKeyStorePassword(ksPassword);
209 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
210 if (trustStore != null) {
211 sslContextFactory.setTrustStorePath(trustStore);
213 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
214 if (tsPassword != null) {
215 sslContextFactory.setTrustStorePassword(tsPassword);
219 HttpConfiguration https = new HttpConfiguration();
220 https.addCustomizer(new SecureRequestCustomizer());
222 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
225 public ServerConnector httpConnector() {
226 return new ServerConnector(this.jettyServer);
230 public void setBasicAuthentication(String user, String password, String servletPath) {
231 String srvltPath = servletPath;
233 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
234 throw new IllegalArgumentException("Missing user and/or password");
237 if (srvltPath == null || srvltPath.isEmpty()) {
241 HashLoginService hashLoginService = new HashLoginService();
242 hashLoginService.putUser(user, Credential.getCredential(password), new String[] {"user"});
243 hashLoginService.setName(this.connector.getName() + "-login-service");
245 Constraint constraint = new Constraint();
246 constraint.setName(Constraint.__BASIC_AUTH);
247 constraint.setRoles(new String[] {"user"});
248 constraint.setAuthenticate(true);
250 ConstraintMapping constraintMapping = new ConstraintMapping();
251 constraintMapping.setConstraint(constraint);
252 constraintMapping.setPathSpec(srvltPath);
254 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
255 securityHandler.setAuthenticator(new BasicAuthenticator());
256 securityHandler.setRealmName(this.connector.getName() + "-realm");
257 securityHandler.addConstraintMapping(constraintMapping);
258 securityHandler.setLoginService(hashLoginService);
260 this.context.setSecurityHandler(securityHandler);
263 this.password = password;
267 * jetty server execution.
272 logger.info("{}: STARTING", this);
274 this.jettyServer.start();
276 if (logger.isInfoEnabled()) {
277 logger.info("{}: STARTED: {}", this, this.jettyServer.dump());
280 synchronized (this.startCondition) {
281 this.startCondition.notifyAll();
284 this.jettyServer.join();
285 } catch (Exception e) {
286 logger.error("{}: error found while bringing up server", this, e);
291 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
292 logger.info("{}: WAITED-START", this);
294 if (maxWaitTime < 0) {
295 throw new IllegalArgumentException("max-wait-time cannot be negative");
298 long pendingWaitTime = maxWaitTime;
304 synchronized (this.startCondition) {
306 while (!this.jettyServer.isRunning()) {
308 long startTs = System.currentTimeMillis();
310 this.startCondition.wait(pendingWaitTime);
312 if (maxWaitTime == 0) {
313 /* spurious notification */
317 long endTs = System.currentTimeMillis();
318 pendingWaitTime = pendingWaitTime - (endTs - startTs);
320 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
322 if (pendingWaitTime <= 0) {
326 } catch (InterruptedException e) {
327 logger.warn("{}: waited-start has been interrupted", this);
332 return this.jettyServer.isRunning();
337 public boolean start() {
338 logger.info("{}: STARTING", this);
340 synchronized (this) {
341 if (jettyThread == null || !this.jettyThread.isAlive()) {
343 this.jettyThread = new Thread(this);
344 this.jettyThread.setName(this.name + "-" + this.port);
345 this.jettyThread.start();
353 public boolean stop() {
354 logger.info("{}: STOPPING", this);
356 synchronized (this) {
357 if (jettyThread == null) {
361 if (!jettyThread.isAlive()) {
362 this.jettyThread = null;
366 this.connector.stop();
367 } catch (Exception e) {
368 logger.error("{}: error while stopping management server", this, e);
372 this.jettyServer.stop();
373 } catch (Exception e) {
374 logger.error("{}: error while stopping management server", this, e);
385 public void shutdown() {
386 logger.info("{}: SHUTTING DOWN", this);
390 if (this.jettyThread == null) {
394 Thread jettyThreadCopy = this.jettyThread;
396 if (jettyThreadCopy.isAlive()) {
398 jettyThreadCopy.join(2000L);
399 } catch (InterruptedException e) {
400 logger.warn("{}: error while shutting down management server", this);
401 Thread.currentThread().interrupt();
403 if (!jettyThreadCopy.isInterrupted()) {
405 jettyThreadCopy.interrupt();
406 } catch (Exception e) {
408 logger.warn("{}: exception while shutting down (OK)", this, e);
413 this.jettyServer.destroy();
417 public boolean isAlive() {
418 if (this.jettyThread != null) {
419 return this.jettyThread.isAlive();
426 public int getPort() {
435 public String getName() {
444 public String getHost() {
453 public String getUser() {
460 * @return the password
463 public String getPassword() {
468 public String toString() {
469 StringBuilder builder = new StringBuilder();
470 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
471 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
472 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
473 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
474 .append(jettyThread).append("]");
475 return builder.toString();