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.UserStore;
33 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
34 import org.eclipse.jetty.server.HttpConfiguration;
35 import org.eclipse.jetty.server.HttpConnectionFactory;
36 import org.eclipse.jetty.server.SecureRequestCustomizer;
37 import org.eclipse.jetty.server.Server;
38 import org.eclipse.jetty.server.ServerConnector;
39 import org.eclipse.jetty.server.Slf4jRequestLog;
40 import org.eclipse.jetty.servlet.ServletContextHandler;
41 import org.eclipse.jetty.util.security.Constraint;
42 import org.eclipse.jetty.util.security.Credential;
43 import org.eclipse.jetty.util.ssl.SslContextFactory;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Http Server implementation using Embedded Jetty.
51 public abstract class JettyServletServer implements HttpServletServer, Runnable {
54 * Keystore/Truststore system property names.
56 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
57 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword";
58 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
59 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword";
64 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
69 protected final String name;
72 * Server host address.
74 protected final String host;
77 * Server port to bind.
79 protected final int port;
82 * Server auth user name.
84 protected String user;
87 * Server auth password name.
89 protected String password;
92 * Server base context path.
94 protected final String contextPath;
97 * Embedded jetty server.
99 protected final Server jettyServer;
104 protected final ServletContextHandler context;
109 protected final ServerConnector connector;
114 protected volatile Thread jettyThread;
119 protected Object startCondition = new Object();
124 * @param name server name
125 * @param host server host
126 * @param port server port
127 * @param contextPath context path
129 * @throws IllegalArgumentException if invalid parameters are passed in
131 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
132 String srvName = name;
134 if (srvName == null || srvName.isEmpty()) {
135 srvName = "http-" + port;
138 if (port <= 0 || port >= 65535) {
139 throw new IllegalArgumentException("Invalid Port provided: " + port);
142 String srvHost = host;
143 if (srvHost == null || srvHost.isEmpty()) {
144 srvHost = "localhost";
147 String ctxtPath = contextPath;
148 if (ctxtPath == null || ctxtPath.isEmpty()) {
157 this.contextPath = ctxtPath;
159 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
160 this.context.setContextPath(ctxtPath);
162 this.jettyServer = new Server();
163 this.jettyServer.setRequestLog(new Slf4jRequestLog());
166 this.connector = httpsConnector();
168 this.connector = httpConnector();
171 this.connector.setName(srvName);
172 this.connector.setReuseAddress(true);
173 this.connector.setPort(port);
174 this.connector.setHost(srvHost);
176 this.jettyServer.addConnector(this.connector);
177 this.jettyServer.setHandler(context);
180 public JettyServletServer(String name, String host, int port, String contextPath) {
181 this(name, false, host, port, contextPath);
185 public void addFilterClass(String filterPath, String filterClass) {
186 if (filterClass == null || filterClass.isEmpty()) {
187 throw new IllegalArgumentException("No filter class provided");
190 String tempFilterPath = filterPath;
191 if (filterPath == null || filterPath.isEmpty()) {
192 tempFilterPath = "/*";
195 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
199 * Returns the https connector.
201 * @return the server connector
203 public ServerConnector httpsConnector() {
204 SslContextFactory sslContextFactory = new SslContextFactory();
206 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
207 if (keyStore != null) {
208 sslContextFactory.setKeyStorePath(keyStore);
210 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
211 if (ksPassword != null) {
212 sslContextFactory.setKeyStorePassword(ksPassword);
216 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
217 if (trustStore != null) {
218 sslContextFactory.setTrustStorePath(trustStore);
220 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
221 if (tsPassword != null) {
222 sslContextFactory.setTrustStorePassword(tsPassword);
226 HttpConfiguration https = new HttpConfiguration();
227 https.addCustomizer(new SecureRequestCustomizer());
229 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
232 public ServerConnector httpConnector() {
233 return new ServerConnector(this.jettyServer);
237 public void setBasicAuthentication(String user, String password, String servletPath) {
238 String srvltPath = servletPath;
240 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
241 throw new IllegalArgumentException("Missing user and/or password");
244 if (srvltPath == null || srvltPath.isEmpty()) {
248 final HashLoginService hashLoginService = new HashLoginService();
249 final UserStore userStore = new UserStore();
250 userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
251 hashLoginService.setUserStore(userStore);
252 hashLoginService.setName(this.connector.getName() + "-login-service");
254 Constraint constraint = new Constraint();
255 constraint.setName(Constraint.__BASIC_AUTH);
256 constraint.setRoles(new String[] {"user"});
257 constraint.setAuthenticate(true);
259 ConstraintMapping constraintMapping = new ConstraintMapping();
260 constraintMapping.setConstraint(constraint);
261 constraintMapping.setPathSpec(srvltPath);
263 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
264 securityHandler.setAuthenticator(new BasicAuthenticator());
265 securityHandler.setRealmName(this.connector.getName() + "-realm");
266 securityHandler.addConstraintMapping(constraintMapping);
267 securityHandler.setLoginService(hashLoginService);
269 this.context.setSecurityHandler(securityHandler);
272 this.password = password;
276 * jetty server execution.
281 logger.info("{}: STARTING", this);
283 this.jettyServer.start();
285 if (logger.isInfoEnabled()) {
286 logger.info("{}: STARTED: {}", this, this.jettyServer.dump());
289 synchronized (this.startCondition) {
290 this.startCondition.notifyAll();
293 this.jettyServer.join();
294 } catch (Exception e) {
295 logger.error("{}: error found while bringing up server", this, e);
300 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
301 logger.info("{}: WAITED-START", this);
303 if (maxWaitTime < 0) {
304 throw new IllegalArgumentException("max-wait-time cannot be negative");
307 long pendingWaitTime = maxWaitTime;
313 synchronized (this.startCondition) {
315 while (!this.jettyServer.isRunning()) {
317 long startTs = System.currentTimeMillis();
319 this.startCondition.wait(pendingWaitTime);
321 if (maxWaitTime == 0) {
322 /* spurious notification */
326 long endTs = System.currentTimeMillis();
327 pendingWaitTime = pendingWaitTime - (endTs - startTs);
329 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
331 if (pendingWaitTime <= 0) {
335 } catch (InterruptedException e) {
336 logger.warn("{}: waited-start has been interrupted", this);
341 return this.jettyServer.isRunning();
346 public boolean start() {
347 logger.info("{}: STARTING", this);
349 synchronized (this) {
350 if (jettyThread == null || !this.jettyThread.isAlive()) {
352 this.jettyThread = new Thread(this);
353 this.jettyThread.setName(this.name + "-" + this.port);
354 this.jettyThread.start();
362 public boolean stop() {
363 logger.info("{}: STOPPING", this);
365 synchronized (this) {
366 if (jettyThread == null) {
370 if (!jettyThread.isAlive()) {
371 this.jettyThread = null;
375 this.connector.stop();
376 } catch (Exception e) {
377 logger.error("{}: error while stopping management server", this, e);
381 this.jettyServer.stop();
382 } catch (Exception e) {
383 logger.error("{}: error while stopping management server", this, e);
394 public void shutdown() {
395 logger.info("{}: SHUTTING DOWN", this);
399 if (this.jettyThread == null) {
403 Thread jettyThreadCopy = this.jettyThread;
405 if (jettyThreadCopy.isAlive()) {
407 jettyThreadCopy.join(2000L);
408 } catch (InterruptedException e) {
409 logger.warn("{}: error while shutting down management server", this);
410 Thread.currentThread().interrupt();
412 if (!jettyThreadCopy.isInterrupted()) {
414 jettyThreadCopy.interrupt();
415 } catch (Exception e) {
417 logger.warn("{}: exception while shutting down (OK)", this, e);
422 this.jettyServer.destroy();
426 public boolean isAlive() {
427 if (this.jettyThread != null) {
428 return this.jettyThread.isAlive();
435 public int getPort() {
444 public String getName() {
453 public String getHost() {
462 public String getUser() {
469 * @return the password
472 public String getPassword() {
477 public String toString() {
478 StringBuilder builder = new StringBuilder();
479 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
480 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
481 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
482 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
483 .append(jettyThread).append("]");
484 return builder.toString();