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 org.eclipse.jetty.security.ConstraintMapping;
26 import org.eclipse.jetty.security.ConstraintSecurityHandler;
27 import org.eclipse.jetty.security.HashLoginService;
28 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
29 import org.eclipse.jetty.server.HttpConfiguration;
30 import org.eclipse.jetty.server.HttpConnectionFactory;
31 import org.eclipse.jetty.server.SecureRequestCustomizer;
32 import org.eclipse.jetty.server.Server;
33 import org.eclipse.jetty.server.ServerConnector;
34 import org.eclipse.jetty.server.Slf4jRequestLog;
35 import org.eclipse.jetty.servlet.ServletContextHandler;
36 import org.eclipse.jetty.util.security.Constraint;
37 import org.eclipse.jetty.util.security.Credential;
38 import org.eclipse.jetty.util.ssl.SslContextFactory;
39 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * Http Server implementation using Embedded Jetty
46 public abstract class JettyServletServer implements HttpServletServer, Runnable {
49 * Keystore/Truststore system property names
51 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
52 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword";
53 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
54 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword";
59 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
64 protected final String name;
69 protected final String host;
74 protected final int port;
77 * server auth user name
79 protected String user;
82 * server auth password name
84 protected String password;
87 * server base context path
89 protected final String contextPath;
92 * embedded jetty server
94 protected final Server jettyServer;
99 protected final ServletContextHandler context;
104 protected final ServerConnector connector;
109 protected volatile Thread jettyThread;
114 protected Object startCondition = new Object();
119 * @param name server name
120 * @param host server host
121 * @param port server port
122 * @param contextPath context path
124 * @throws IllegalArgumentException if invalid parameters are passed in
126 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
127 String srvName = name;
128 String srvHost = host;
129 String ctxtPath = contextPath;
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 if (srvHost == null || srvHost.isEmpty()) {
140 srvHost = "localhost";
143 if (ctxtPath == null || ctxtPath.isEmpty()) {
152 this.contextPath = ctxtPath;
154 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
155 this.context.setContextPath(ctxtPath);
157 this.jettyServer = new Server();
158 this.jettyServer.setRequestLog(new Slf4jRequestLog());
161 this.connector = httpsConnector();
163 this.connector = httpConnector();
165 this.connector.setName(srvName);
166 this.connector.setReuseAddress(true);
167 this.connector.setPort(port);
168 this.connector.setHost(srvHost);
170 this.jettyServer.addConnector(this.connector);
171 this.jettyServer.setHandler(context);
174 public JettyServletServer(String name, String host, int port, String contextPath) {
175 this(name, false, host, port, contextPath);
178 public ServerConnector httpsConnector() {
179 SslContextFactory sslContextFactory = new SslContextFactory();
181 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
182 if (keyStore != null) {
183 sslContextFactory.setKeyStorePath(keyStore);
185 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
186 if (ksPassword != null)
187 sslContextFactory.setKeyStorePassword(ksPassword);
190 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
191 if (trustStore != null) {
192 sslContextFactory.setTrustStorePath(trustStore);
194 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
195 if (tsPassword != null)
196 sslContextFactory.setTrustStorePassword(tsPassword);
199 HttpConfiguration https = new HttpConfiguration();
200 https.addCustomizer(new SecureRequestCustomizer());
202 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
205 public ServerConnector httpConnector() {
206 return new ServerConnector(this.jettyServer);
210 public void setBasicAuthentication(String user, String password, String servletPath) {
211 String srvltPath = servletPath;
213 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
214 throw new IllegalArgumentException("Missing user and/or password");
217 if (srvltPath == null || srvltPath.isEmpty()) {
221 HashLoginService hashLoginService = new HashLoginService();
222 hashLoginService.putUser(user, Credential.getCredential(password), new String[] {"user"});
223 hashLoginService.setName(this.connector.getName() + "-login-service");
225 Constraint constraint = new Constraint();
226 constraint.setName(Constraint.__BASIC_AUTH);
227 constraint.setRoles(new String[] {"user"});
228 constraint.setAuthenticate(true);
230 ConstraintMapping constraintMapping = new ConstraintMapping();
231 constraintMapping.setConstraint(constraint);
232 constraintMapping.setPathSpec(srvltPath);
234 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
235 securityHandler.setAuthenticator(new BasicAuthenticator());
236 securityHandler.setRealmName(this.connector.getName() + "-realm");
237 securityHandler.addConstraintMapping(constraintMapping);
238 securityHandler.setLoginService(hashLoginService);
240 this.context.setSecurityHandler(securityHandler);
243 this.password = password;
247 * jetty server execution
252 logger.info("{}: STARTING", this);
254 this.jettyServer.start();
256 if (logger.isInfoEnabled()) {
257 logger.info("{}: STARTED: {}", this, this.jettyServer.dump());
260 synchronized (this.startCondition) {
261 this.startCondition.notifyAll();
264 this.jettyServer.join();
265 } catch (Exception e) {
266 logger.error("{}: error found while bringing up server", this, e);
271 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
272 logger.info("{}: WAITED-START", this);
274 if (maxWaitTime < 0) {
275 throw new IllegalArgumentException("max-wait-time cannot be negative");
278 long pendingWaitTime = maxWaitTime;
284 synchronized (this.startCondition) {
286 while (!this.jettyServer.isRunning()) {
288 long startTs = System.currentTimeMillis();
290 this.startCondition.wait(pendingWaitTime);
292 if (maxWaitTime == 0) {
293 /* spurious notification */
297 long endTs = System.currentTimeMillis();
298 pendingWaitTime = pendingWaitTime - (endTs - startTs);
300 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
302 if (pendingWaitTime <= 0) {
306 } catch (InterruptedException e) {
307 logger.warn("{}: waited-start has been interrupted", this);
312 return this.jettyServer.isRunning();
317 public boolean start() {
318 logger.info("{}: STARTING", this);
320 synchronized (this) {
321 if (jettyThread == null || !this.jettyThread.isAlive()) {
323 this.jettyThread = new Thread(this);
324 this.jettyThread.setName(this.name + "-" + this.port);
325 this.jettyThread.start();
333 public boolean stop() {
334 logger.info("{}: STOPPING", this);
336 synchronized (this) {
337 if (jettyThread == null) {
341 if (!jettyThread.isAlive()) {
342 this.jettyThread = null;
346 this.connector.stop();
347 } catch (Exception e) {
348 logger.error("{}: error while stopping management server", this, e);
352 this.jettyServer.stop();
353 } catch (Exception e) {
354 logger.error("{}: error while stopping management server", this, e);
365 public void shutdown() {
366 logger.info("{}: SHUTTING DOWN", this);
370 if (this.jettyThread == null) {
374 Thread jettyThreadCopy = this.jettyThread;
376 if (jettyThreadCopy.isAlive()) {
378 jettyThreadCopy.join(2000L);
379 } catch (InterruptedException e) {
380 logger.warn("{}: error while shutting down management server", this);
381 Thread.currentThread().interrupt();
383 if (!jettyThreadCopy.isInterrupted()) {
385 jettyThreadCopy.interrupt();
386 } catch (Exception e) {
388 logger.warn("{}: exception while shutting down (OK)", this, e);
393 this.jettyServer.destroy();
397 public boolean isAlive() {
398 if (this.jettyThread != null) {
399 return this.jettyThread.isAlive();
406 public int getPort() {
413 public String getName() {
420 public String getHost() {
427 public String getUser() {
432 * @return the password
435 public String getPassword() {
440 public String toString() {
441 StringBuilder builder = new StringBuilder();
442 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
443 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
444 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
445 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
446 .append(jettyThread).append("]");
447 return builder.toString();