2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 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;
24 import java.util.EnumSet;
25 import javax.servlet.DispatcherType;
26 import org.eclipse.jetty.security.ConstraintMapping;
27 import org.eclipse.jetty.security.ConstraintSecurityHandler;
28 import org.eclipse.jetty.security.HashLoginService;
29 import org.eclipse.jetty.security.UserStore;
30 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
31 import org.eclipse.jetty.server.CustomRequestLog;
32 import org.eclipse.jetty.server.HttpConfiguration;
33 import org.eclipse.jetty.server.HttpConnectionFactory;
34 import org.eclipse.jetty.server.SecureRequestCustomizer;
35 import org.eclipse.jetty.server.Server;
36 import org.eclipse.jetty.server.ServerConnector;
37 import org.eclipse.jetty.server.Slf4jRequestLogWriter;
38 import org.eclipse.jetty.servlet.FilterHolder;
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.aaf.cadi.filter.CadiFilter;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
45 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Http Server implementation using Embedded Jetty.
52 public abstract class JettyServletServer implements HttpServletServer, Runnable {
55 * Keystore/Truststore system property names.
57 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
58 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; //NOSONAR
59 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
60 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; //NOSONAR
65 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
70 protected final String name;
73 * Server host address.
75 protected final String host;
78 * Server port to bind.
80 protected final int port;
83 * Server auth user name.
85 protected String user;
88 * Server auth password name.
90 protected String password;
93 * Server base context path.
95 protected final String contextPath;
98 * Embedded jetty server.
100 protected final Server jettyServer;
105 protected final ServletContextHandler context;
110 protected final ServerConnector connector;
115 protected volatile Thread jettyThread;
120 protected Object startCondition = new Object();
125 * @param name server name
126 * @param host server host
127 * @param port server port
128 * @param contextPath context path
130 * @throws IllegalArgumentException if invalid parameters are passed in
132 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
133 String srvName = name;
135 if (srvName == null || srvName.isEmpty()) {
136 srvName = "http-" + port;
139 if (port <= 0 || port >= 65535) {
140 throw new IllegalArgumentException("Invalid Port provided: " + port);
143 String srvHost = host;
144 if (srvHost == null || srvHost.isEmpty()) {
145 srvHost = "localhost";
148 String ctxtPath = contextPath;
149 if (ctxtPath == null || ctxtPath.isEmpty()) {
158 this.contextPath = ctxtPath;
160 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
161 this.context.setContextPath(ctxtPath);
163 this.jettyServer = new Server();
165 CustomRequestLog requestLog =
166 new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
167 this.jettyServer.setRequestLog(requestLog);
170 this.connector = httpsConnector();
172 this.connector = httpConnector();
175 this.connector.setName(srvName);
176 this.connector.setReuseAddress(true);
177 this.connector.setPort(port);
178 this.connector.setHost(srvHost);
180 this.jettyServer.addConnector(this.connector);
181 this.jettyServer.setHandler(context);
184 public JettyServletServer(String name, String host, int port, String contextPath) {
185 this(name, false, host, port, contextPath);
189 public void addFilterClass(String filterPath, String filterClass) {
190 if (filterClass == null || filterClass.isEmpty()) {
191 throw new IllegalArgumentException("No filter class provided");
194 String tempFilterPath = filterPath;
195 if (filterPath == null || filterPath.isEmpty()) {
196 tempFilterPath = "/*";
199 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
203 * Returns the https connector.
205 * @return the server connector
207 public ServerConnector httpsConnector() {
208 SslContextFactory sslContextFactory = new SslContextFactory.Server();
210 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
211 if (keyStore != null) {
212 sslContextFactory.setKeyStorePath(keyStore);
214 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
215 if (ksPassword != null) {
216 sslContextFactory.setKeyStorePassword(ksPassword);
220 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
221 if (trustStore != null) {
222 sslContextFactory.setTrustStorePath(trustStore);
224 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
225 if (tsPassword != null) {
226 sslContextFactory.setTrustStorePassword(tsPassword);
230 HttpConfiguration https = new HttpConfiguration();
231 https.addCustomizer(new SecureRequestCustomizer());
233 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
236 public ServerConnector httpConnector() {
237 return new ServerConnector(this.jettyServer);
241 public void setAafAuthentication(String filterPath) {
242 this.addFilterClass(filterPath, CadiFilter.class.getName());
246 public boolean isAaf() {
247 for (FilterHolder filter : context.getServletHandler().getFilters()) {
248 if (CadiFilter.class.getName().equals(filter.getClassName())) {
256 public void setBasicAuthentication(String user, String password, String servletPath) {
257 String srvltPath = servletPath;
259 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
260 throw new IllegalArgumentException("Missing user and/or password");
263 if (srvltPath == null || srvltPath.isEmpty()) {
267 final HashLoginService hashLoginService = new HashLoginService();
268 final UserStore userStore = new UserStore();
269 userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
270 hashLoginService.setUserStore(userStore);
271 hashLoginService.setName(this.connector.getName() + "-login-service");
273 Constraint constraint = new Constraint();
274 constraint.setName(Constraint.__BASIC_AUTH);
275 constraint.setRoles(new String[] {"user"});
276 constraint.setAuthenticate(true);
278 ConstraintMapping constraintMapping = new ConstraintMapping();
279 constraintMapping.setConstraint(constraint);
280 constraintMapping.setPathSpec(srvltPath);
282 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
283 securityHandler.setAuthenticator(new BasicAuthenticator());
284 securityHandler.setRealmName(this.connector.getName() + "-realm");
285 securityHandler.addConstraintMapping(constraintMapping);
286 securityHandler.setLoginService(hashLoginService);
288 this.context.setSecurityHandler(securityHandler);
291 this.password = password;
295 * jetty server execution.
300 logger.info("{}: STARTING", this);
302 this.jettyServer.start();
304 if (logger.isTraceEnabled()) {
305 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
308 synchronized (this.startCondition) {
309 this.startCondition.notifyAll();
312 this.jettyServer.join();
313 } catch (Exception e) {
314 logger.error("{}: error found while bringing up server", this, e);
319 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
320 logger.info("{}: WAITED-START", this);
322 if (maxWaitTime < 0) {
323 throw new IllegalArgumentException("max-wait-time cannot be negative");
326 long pendingWaitTime = maxWaitTime;
332 synchronized (this.startCondition) {
334 while (!this.jettyServer.isRunning()) {
336 long startTs = System.currentTimeMillis();
338 this.startCondition.wait(pendingWaitTime);
340 if (maxWaitTime == 0) {
341 /* spurious notification */
345 long endTs = System.currentTimeMillis();
346 pendingWaitTime = pendingWaitTime - (endTs - startTs);
348 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
350 if (pendingWaitTime <= 0) {
354 } catch (InterruptedException e) {
355 logger.warn("{}: waited-start has been interrupted", this);
360 return this.jettyServer.isRunning();
365 public boolean start() {
366 logger.info("{}: STARTING", this);
368 synchronized (this) {
369 if (jettyThread == null || !this.jettyThread.isAlive()) {
371 this.jettyThread = new Thread(this);
372 this.jettyThread.setName(this.name + "-" + this.port);
373 this.jettyThread.start();
381 public boolean stop() {
382 logger.info("{}: STOPPING", this);
384 synchronized (this) {
385 if (jettyThread == null) {
389 if (!jettyThread.isAlive()) {
390 this.jettyThread = null;
394 this.connector.stop();
395 } catch (Exception e) {
396 logger.error("{}: error while stopping management server", this, e);
400 this.jettyServer.stop();
401 } catch (Exception e) {
402 logger.error("{}: error while stopping management server", this, e);
413 public void shutdown() {
414 logger.info("{}: SHUTTING DOWN", this);
418 if (this.jettyThread == null) {
422 Thread jettyThreadCopy = this.jettyThread;
424 if (jettyThreadCopy.isAlive()) {
426 jettyThreadCopy.join(2000L);
427 } catch (InterruptedException e) {
428 logger.warn("{}: error while shutting down management server", this);
429 Thread.currentThread().interrupt();
431 if (!jettyThreadCopy.isInterrupted()) {
433 jettyThreadCopy.interrupt();
434 } catch (Exception e) {
436 logger.warn("{}: exception while shutting down (OK)", this, e);
441 this.jettyServer.destroy();
445 public boolean isAlive() {
446 if (this.jettyThread != null) {
447 return this.jettyThread.isAlive();
454 public int getPort() {
464 public String getName() {
473 public String getHost() {
482 public String getUser() {
489 * @return the password
493 public String getPassword() {
498 public String toString() {
499 StringBuilder builder = new StringBuilder();
500 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
501 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
502 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
503 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
504 .append(jettyThread).append("]");
505 return builder.toString();