2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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.FilterHolder;
41 import org.eclipse.jetty.servlet.ServletContextHandler;
42 import org.eclipse.jetty.util.security.Constraint;
43 import org.eclipse.jetty.util.security.Credential;
44 import org.eclipse.jetty.util.ssl.SslContextFactory;
45 import org.onap.aaf.cadi.filter.CadiFilter;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Http Server implementation using Embedded Jetty.
54 public abstract class JettyServletServer implements HttpServletServer, Runnable {
57 * Keystore/Truststore system property names.
59 public static final String SYSTEM_KEYSTORE_PROPERTY_NAME = "javax.net.ssl.keyStore";
60 public static final String SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.keyStorePassword";
61 public static final String SYSTEM_TRUSTSTORE_PROPERTY_NAME = "javax.net.ssl.trustStore";
62 public static final String SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME = "javax.net.ssl.trustStorePassword";
67 private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class);
72 protected final String name;
75 * Server host address.
77 protected final String host;
80 * Server port to bind.
82 protected final int port;
85 * Server auth user name.
87 protected String user;
90 * Server auth password name.
92 protected String password;
95 * Server base context path.
97 protected final String contextPath;
100 * Embedded jetty server.
102 protected final Server jettyServer;
107 protected final ServletContextHandler context;
112 protected final ServerConnector connector;
117 protected volatile Thread jettyThread;
122 protected Object startCondition = new Object();
127 * @param name server name
128 * @param host server host
129 * @param port server port
130 * @param contextPath context path
132 * @throws IllegalArgumentException if invalid parameters are passed in
134 public JettyServletServer(String name, boolean https, String host, int port, String contextPath) {
135 String srvName = name;
137 if (srvName == null || srvName.isEmpty()) {
138 srvName = "http-" + port;
141 if (port <= 0 || port >= 65535) {
142 throw new IllegalArgumentException("Invalid Port provided: " + port);
145 String srvHost = host;
146 if (srvHost == null || srvHost.isEmpty()) {
147 srvHost = "localhost";
150 String ctxtPath = contextPath;
151 if (ctxtPath == null || ctxtPath.isEmpty()) {
160 this.contextPath = ctxtPath;
162 this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
163 this.context.setContextPath(ctxtPath);
165 this.jettyServer = new Server();
166 this.jettyServer.setRequestLog(new Slf4jRequestLog());
169 this.connector = httpsConnector();
171 this.connector = httpConnector();
174 this.connector.setName(srvName);
175 this.connector.setReuseAddress(true);
176 this.connector.setPort(port);
177 this.connector.setHost(srvHost);
179 this.jettyServer.addConnector(this.connector);
180 this.jettyServer.setHandler(context);
183 public JettyServletServer(String name, String host, int port, String contextPath) {
184 this(name, false, host, port, contextPath);
188 public void addFilterClass(String filterPath, String filterClass) {
189 if (filterClass == null || filterClass.isEmpty()) {
190 throw new IllegalArgumentException("No filter class provided");
193 String tempFilterPath = filterPath;
194 if (filterPath == null || filterPath.isEmpty()) {
195 tempFilterPath = "/*";
198 context.addFilter(filterClass, tempFilterPath, EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
202 * Returns the https connector.
204 * @return the server connector
206 public ServerConnector httpsConnector() {
207 SslContextFactory sslContextFactory = new SslContextFactory();
209 String keyStore = System.getProperty(SYSTEM_KEYSTORE_PROPERTY_NAME);
210 if (keyStore != null) {
211 sslContextFactory.setKeyStorePath(keyStore);
213 String ksPassword = System.getProperty(SYSTEM_KEYSTORE_PASSWORD_PROPERTY_NAME);
214 if (ksPassword != null) {
215 sslContextFactory.setKeyStorePassword(ksPassword);
219 String trustStore = System.getProperty(SYSTEM_TRUSTSTORE_PROPERTY_NAME);
220 if (trustStore != null) {
221 sslContextFactory.setTrustStorePath(trustStore);
223 String tsPassword = System.getProperty(SYSTEM_TRUSTSTORE_PASSWORD_PROPERTY_NAME);
224 if (tsPassword != null) {
225 sslContextFactory.setTrustStorePassword(tsPassword);
229 HttpConfiguration https = new HttpConfiguration();
230 https.addCustomizer(new SecureRequestCustomizer());
232 return new ServerConnector(jettyServer, sslContextFactory, new HttpConnectionFactory(https));
235 public ServerConnector httpConnector() {
236 return new ServerConnector(this.jettyServer);
240 public void setAafAuthentication(String filterPath) {
241 this.addFilterClass(filterPath, CadiFilter.class.getCanonicalName());
245 public boolean isAaf() {
246 for (FilterHolder filter : context.getServletHandler().getFilters()) {
247 if (CadiFilter.class.getCanonicalName().equals(filter.getClassName())) {
255 public void setBasicAuthentication(String user, String password, String servletPath) {
256 String srvltPath = servletPath;
258 if (user == null || user.isEmpty() || password == null || password.isEmpty()) {
259 throw new IllegalArgumentException("Missing user and/or password");
262 if (srvltPath == null || srvltPath.isEmpty()) {
266 final HashLoginService hashLoginService = new HashLoginService();
267 final UserStore userStore = new UserStore();
268 userStore.addUser(user, Credential.getCredential(password), new String[] {"user"});
269 hashLoginService.setUserStore(userStore);
270 hashLoginService.setName(this.connector.getName() + "-login-service");
272 Constraint constraint = new Constraint();
273 constraint.setName(Constraint.__BASIC_AUTH);
274 constraint.setRoles(new String[] {"user"});
275 constraint.setAuthenticate(true);
277 ConstraintMapping constraintMapping = new ConstraintMapping();
278 constraintMapping.setConstraint(constraint);
279 constraintMapping.setPathSpec(srvltPath);
281 ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
282 securityHandler.setAuthenticator(new BasicAuthenticator());
283 securityHandler.setRealmName(this.connector.getName() + "-realm");
284 securityHandler.addConstraintMapping(constraintMapping);
285 securityHandler.setLoginService(hashLoginService);
287 this.context.setSecurityHandler(securityHandler);
290 this.password = password;
294 * jetty server execution.
299 logger.info("{}: STARTING", this);
301 this.jettyServer.start();
303 if (logger.isTraceEnabled()) {
304 logger.trace("{}: STARTED: {}", this, this.jettyServer.dump());
307 synchronized (this.startCondition) {
308 this.startCondition.notifyAll();
311 this.jettyServer.join();
312 } catch (Exception e) {
313 logger.error("{}: error found while bringing up server", this, e);
318 public boolean waitedStart(long maxWaitTime) throws InterruptedException {
319 logger.info("{}: WAITED-START", this);
321 if (maxWaitTime < 0) {
322 throw new IllegalArgumentException("max-wait-time cannot be negative");
325 long pendingWaitTime = maxWaitTime;
331 synchronized (this.startCondition) {
333 while (!this.jettyServer.isRunning()) {
335 long startTs = System.currentTimeMillis();
337 this.startCondition.wait(pendingWaitTime);
339 if (maxWaitTime == 0) {
340 /* spurious notification */
344 long endTs = System.currentTimeMillis();
345 pendingWaitTime = pendingWaitTime - (endTs - startTs);
347 logger.info("{}: pending time is {} ms.", this, pendingWaitTime);
349 if (pendingWaitTime <= 0) {
353 } catch (InterruptedException e) {
354 logger.warn("{}: waited-start has been interrupted", this);
359 return this.jettyServer.isRunning();
364 public boolean start() {
365 logger.info("{}: STARTING", this);
367 synchronized (this) {
368 if (jettyThread == null || !this.jettyThread.isAlive()) {
370 this.jettyThread = new Thread(this);
371 this.jettyThread.setName(this.name + "-" + this.port);
372 this.jettyThread.start();
380 public boolean stop() {
381 logger.info("{}: STOPPING", this);
383 synchronized (this) {
384 if (jettyThread == null) {
388 if (!jettyThread.isAlive()) {
389 this.jettyThread = null;
393 this.connector.stop();
394 } catch (Exception e) {
395 logger.error("{}: error while stopping management server", this, e);
399 this.jettyServer.stop();
400 } catch (Exception e) {
401 logger.error("{}: error while stopping management server", this, e);
412 public void shutdown() {
413 logger.info("{}: SHUTTING DOWN", this);
417 if (this.jettyThread == null) {
421 Thread jettyThreadCopy = this.jettyThread;
423 if (jettyThreadCopy.isAlive()) {
425 jettyThreadCopy.join(2000L);
426 } catch (InterruptedException e) {
427 logger.warn("{}: error while shutting down management server", this);
428 Thread.currentThread().interrupt();
430 if (!jettyThreadCopy.isInterrupted()) {
432 jettyThreadCopy.interrupt();
433 } catch (Exception e) {
435 logger.warn("{}: exception while shutting down (OK)", this, e);
440 this.jettyServer.destroy();
444 public boolean isAlive() {
445 if (this.jettyThread != null) {
446 return this.jettyThread.isAlive();
453 public int getPort() {
462 public String getName() {
471 public String getHost() {
480 public String getUser() {
487 * @return the password
491 public String getPassword() {
496 public String toString() {
497 StringBuilder builder = new StringBuilder();
498 builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port)
499 .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=")
500 .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=")
501 .append(this.context).append(", connector=").append(connector).append(", jettyThread=")
502 .append(jettyThread).append("]");
503 return builder.toString();