2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7 * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.common.endpoints.http.server.internal;
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.UserStore;
31 import org.eclipse.jetty.security.authentication.BasicAuthenticator;
32 import org.eclipse.jetty.server.CustomRequestLog;
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.Slf4jRequestLogWriter;
39 import org.eclipse.jetty.servlet.FilterHolder;
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.aaf.cadi.filter.CadiFilter;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
46 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
51 * Http Server implementation using Embedded Jetty.
53 public abstract class JettyServletServer implements HttpServletServer, Runnable {
56 * Keystore/Truststore system property names.
58 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
59 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword"; //NOSONAR
60 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
61 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword"; //NOSONAR
66 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
68 private static final String NOT_SUPPORTED = " is not supported on this type of jetty server";
73 protected final String name;
76 * Server host address.
78 protected final String host;
81 * Server port to bind.
83 protected final int port;
86 * Server auth user name.
88 protected String user;
91 * Server auth password name.
93 protected String password;
96 * Server base context path.
98 protected final String contextPath;
101 * Embedded jetty server.
103 protected final Server jettyServer;
108 protected final ServletContextHandler context;
113 protected final ServerConnector connector;
118 protected Thread jettyThread;
123 protected Object startCondition = new Object();
128 * @param name server name
129 * @param host server host
130 * @param port server port
131 * @param contextPath context path
133 * @throws IllegalArgumentException if invalid parameters are passed in
135 protected JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
136 String srvName = name;
138 if (srvName == null || srvName.isEmpty()) {
139 srvName = "http-" + port;
142 if (port <= 0 || port >= 65535) {
143 throw new IllegalArgumentException("Invalid Port provided: " + port);
146 String srvHost = host;
147 if (srvHost == null || srvHost.isEmpty()) {
148 srvHost = "localhost";
151 String ctxtPath = contextPath;
152 if (ctxtPath == null || ctxtPath.isEmpty()) {
161 this.contextPath = ctxtPath;
163 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
164 this.context.setContextPath(ctxtPath);
166 this.jettyServer = new Server();
168 var requestLog = new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT);
169 this.jettyServer.setRequestLog(requestLog);
172 this.connector = httpsConnector();
174 this.connector = httpConnector();
177 this.connector.setName(srvName);
178 this.connector.setReuseAddress(true);
179 this.connector.setPort(port);
180 this.connector.setHost(srvHost);
182 this.jettyServer.addConnector(this.connector);
183 this.jettyServer.setHandler(context);
186 protected JettyServletServer(String name, String host, int port, String contextPath) {
187 this(name, false, host, port, contextPath);
191 public void addFilterClass(String filterPath, String filterClass) {
192 if (filterClass == null || filterClass.isEmpty()) {
193 throw new IllegalArgumentException("No filter class provided");
196 String tempFilterPath = filterPath;
197 if (filterPath == null || filterPath.isEmpty()) {
198 tempFilterPath = "/*";
201 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
205 * Returns the https connector.
207 * @return the server connector
209 public ServerConnector httpsConnector() {
210 SslContextFactory sslContextFactory = new SslContextFactory.Server();
212 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
213 if (keyStore != null) {
214 sslContextFactory.setKeyStorePath(keyStore);
216 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
217 if (ksPassword != null) {
218 sslContextFactory.setKeyStorePassword(ksPassword);
222 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
223 if (trustStore != null) {
224 sslContextFactory.setTrustStorePath(trustStore);
226 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
227 if (tsPassword != null) {
228 sslContextFactory.setTrustStorePassword(tsPassword);
232 var https = new HttpConfiguration();
233 https.addCustomizer(new SecureRequestCustomizer());
235 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
238 public ServerConnector httpConnector() {
239 return new ServerConnector(this.jettyServer);
243 public void setAafAuthentication(String filterPath) {
244 this.addFilterClass(filterPath, CadiFilter.class.getName());
248 public boolean isAaf() {
249 for (FilterHolder filter : context.getServletHandler().getFilters()) {
250 if (CadiFilter.class.getName().equals(filter.getClassName())) {
258 public void setBasicAuthentication(String user, String password, String servletPath) {
259 String srvltPath = servletPath;
261 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
262 throw new IllegalArgumentException("Missing user and/or password");
265 if (srvltPath == null || srvltPath.isEmpty()) {
269 final var hashLoginService = new HashLoginService();
270 final var userStore = new UserStore();
271 userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
272 hashLoginService.setUserStore(userStore);
273 hashLoginService.setName(this.connector.getName() + "-login-service");
275 var constraint = new Constraint();
276 constraint.setName(Constraint.__BASIC_AUTH);
277 constraint.setRoles(new String[] {"user"});
278 constraint.setAuthenticate(true);
280 var constraintMapping = new ConstraintMapping();
281 constraintMapping.setConstraint(constraint);
282 constraintMapping.setPathSpec(srvltPath);
284 var securityHandler = new ConstraintSecurityHandler();
285 securityHandler.setAuthenticator(new BasicAuthenticator());
286 securityHandler.setRealmName(this.connector.getName() + "-realm");
287 securityHandler.addConstraintMapping(constraintMapping);
288 securityHandler.setLoginService(hashLoginService);
290 this.context.setSecurityHandler(securityHandler);
293 this.password = password;
297 * jetty server execution.
302 logger.info("{}: STARTING", this);
304 this.jettyServer.start();
306 if (logger.isTraceEnabled()) {
307 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
310 synchronized (this.startCondition) {
311 this.startCondition.notifyAll();
314 this.jettyServer.join();
316 } catch (InterruptedException e) {
317 logger.error("{}: error found while bringing up server", this, e);
318 Thread.currentThread().interrupt();
320 } catch (Exception e) {
321 logger.error("{}: error found while bringing up server", this, e);
326 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
327 logger.info("{}: WAITED-START", this);
329 if (maxWaitTime < 0) {
330 throw new IllegalArgumentException("max-wait-time cannot be negative");
333 long pendingWaitTime = maxWaitTime;
339 synchronized (this.startCondition) {
341 while (!this.jettyServer.isRunning()) {
343 long startTs = System.currentTimeMillis();
345 this.startCondition.wait(pendingWaitTime);
347 if (maxWaitTime == 0) {
348 /* spurious notification */
352 long endTs = System.currentTimeMillis();
353 pendingWaitTime = pendingWaitTime - (endTs - startTs);
355 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
357 if (pendingWaitTime <= 0) {
361 } catch (InterruptedException e) {
362 logger.warn("{}: waited-start has been interrupted", this);
367 return this.jettyServer.isRunning();
372 public boolean start() {
373 logger.info("{}: STARTING", this);
375 synchronized (this) {
376 if (jettyThread == null || !this.jettyThread.isAlive()) {
378 this.jettyThread = new Thread(this);
379 this.jettyThread.setName(this.name + "-" + this.port);
380 this.jettyThread.start();
388 public boolean stop() {
389 logger.info("{}: STOPPING", this);
391 synchronized (this) {
392 if (jettyThread == null) {
396 if (!jettyThread.isAlive()) {
397 this.jettyThread = null;
401 this.connector.stop();
402 } catch (Exception e) {
403 logger.error("{}: error while stopping management server", this, e);
407 this.jettyServer.stop();
408 } catch (Exception e) {
409 logger.error("{}: error while stopping management server", this, e);
420 public void shutdown() {
421 logger.info("{}: SHUTTING DOWN", this);
425 Thread jettyThreadCopy;
426 synchronized (this) {
427 if ((jettyThreadCopy = this.jettyThread) == null) {
432 if (jettyThreadCopy.isAlive()) {
434 jettyThreadCopy.join(2000L);
435 } catch (InterruptedException e) {
436 logger.warn("{}: error while shutting down management server", this);
437 Thread.currentThread().interrupt();
439 if (!jettyThreadCopy.isInterrupted()) {
441 jettyThreadCopy.interrupt();
442 } catch (Exception e) {
444 logger.warn("{}: exception while shutting down (OK)", this, e);
449 this.jettyServer.destroy();
453 public boolean isAlive() {
454 if (this.jettyThread != null) {
455 return this.jettyThread.isAlive();
462 public int getPort() {
472 public String getName() {
481 public String getHost() {
490 public String getUser() {
497 * @return the password
500 public String getPassword() {
505 public void setSerializationProvider(String provider) {
506 throw new UnsupportedOperationException("setSerializationProvider()" + NOT_SUPPORTED);
510 public void addServletClass(String servletPath, String restClass) {
511 throw new UnsupportedOperationException("addServletClass()" + NOT_SUPPORTED);
515 public void addServletPackage(String servletPath, String restPackage) {
516 throw new UnsupportedOperationException("addServletPackage()" + NOT_SUPPORTED);
520 public void addServletResource(String servletPath, String resourceBase) {
521 throw new UnsupportedOperationException("addServletResource()" + NOT_SUPPORTED);
525 public String toString() {
526 var builder = new StringBuilder();
527 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
528 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
529 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
530 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
531 .append(jettyThread).append("]");
532 return builder.toString();