Java Code Examples for org.eclipse.jetty.server.handler.RequestLogHandler#setRequestLog()

The following examples show how to use org.eclipse.jetty.server.handler.RequestLogHandler#setRequestLog() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DremioServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected void addHandlers() {
  // root handler with request logging
  final RequestLogHandler rootHandler = new RequestLogHandler();
  embeddedJetty.insertHandler(rootHandler);
  RequestLogImpl_Jetty_Fix requestLogger = new RequestLogImpl_Jetty_Fix();
  requestLogger.setResource("/logback-access.xml");
  rootHandler.setRequestLog(requestLogger);

  // gzip handler.
  final GzipHandler gzipHandler = new GzipHandler();
  // gzip handler interferes with ChunkedOutput, so exclude the job download path
  gzipHandler.addExcludedPaths("/apiv2/job/*");
  rootHandler.setHandler(gzipHandler);

  // servlet handler for everything (to manage path mapping)
  servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  servletContextHandler.setContextPath("/");
  gzipHandler.setHandler(servletContextHandler);

  // error handler
  final ErrorHandler errorHandler = new ErrorHandler();
  errorHandler.setShowStacks(true);
  errorHandler.setShowMessageInTitle(true);
  embeddedJetty.setErrorHandler(errorHandler);
}
 
Example 2
Source File: ServerManager.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    server.start();

    log.info("Server started at end point {}", getServiceUri());
}
 
Example 3
Source File: ProxyServer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public void start() throws PulsarServerException {
    log.info("Starting web socket proxy at port {}", conf.getWebServicePort().get());
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    try {
        server.start();
    } catch (Exception e) {
        throw new PulsarServerException(e);
    }
}
 
Example 4
Source File: WebServer.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
public WebServer(@NotNull SharedContext context, @NotNull Server server, @Nullable URL baseUrl, @NotNull EncryptionFactory tokenFactory) throws URISyntaxException {
  this.context = context;
  this.server = server;
  this.baseUrl = baseUrl == null ? null : baseUrl.toURI();
  this.tokenFactory = tokenFactory;
  final ServletContextHandler contextHandler = new ServletContextHandler();
  contextHandler.setContextPath("/");
  handler = contextHandler.getServletHandler();

  final RequestLogHandler logHandler = new RequestLogHandler();
  logHandler.setRequestLog((request, response) -> {
    final User user = (User) request.getAttribute(User.class.getName());
    final String username = (user == null || user.isAnonymous()) ? "" : user.getUsername();
    log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), username, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason());
  });

  final HandlerCollection handlers = new HandlerCollection();
  handlers.addHandler(contextHandler);
  handlers.addHandler(logHandler);
  server.setHandler(handlers);
}
 
Example 5
Source File: GatewayServer.java    From hadoop-mini-clusters with Apache License 2.0 6 votes vote down vote up
private static HandlerCollection createHandlers(
        final GatewayConfig config,
        final GatewayServices services,
        final ContextHandlerCollection contexts) {
    HandlerCollection handlers = new HandlerCollection();
    RequestLogHandler logHandler = new RequestLogHandler();
    logHandler.setRequestLog(new AccessHandler());

    TraceHandler traceHandler = new TraceHandler();
    traceHandler.setHandler(contexts);
    traceHandler.setTracedBodyFilter(System.getProperty("org.apache.knox.gateway.trace.body.status.filter"));

    CorrelationHandler correlationHandler = new CorrelationHandler();
    correlationHandler.setHandler(traceHandler);

    DefaultTopologyHandler defaultTopoHandler = new DefaultTopologyHandler(config, services, contexts);

    handlers.setHandlers(new Handler[]{correlationHandler, defaultTopoHandler, logHandler});
    return handlers;
}
 
Example 6
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Pair<SessionHandler,HandlerCollection> createHandlers() {
    final WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(contextPath);
    webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    // GZIP handler
    final GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.addIncludedMimeTypes("text/html", "text/xml", "text/css", "text/plain", "text/javascript", "application/javascript", "application/json", "application/xml");
    gzipHandler.setIncludedMethods("GET", "POST");
    gzipHandler.setCompressionLevel(9);
    gzipHandler.setHandler(webApp);

    if (Strings.isNullOrEmpty(webAppLocation)) {
        webApp.setWar(getShadedWarUrl());
    } else {
        webApp.setWar(webAppLocation);
    }

    // Request log handler
    final RequestLogHandler log = new RequestLogHandler();
    log.setRequestLog(createRequestLog());

    // Redirect root context handler_war
    MovedContextHandler rootRedirect = new MovedContextHandler();
    rootRedirect.setContextPath("/");
    rootRedirect.setNewContextURL(contextPath);
    rootRedirect.setPermanent(true);

    // Put rootRedirect at the end!
    return new Pair<>(webApp.getSessionHandler(), new HandlerCollection(log, gzipHandler, rootRedirect));
}
 
Example 7
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example 8
Source File: Poseidon.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private Handler getRequestLogHandler(Handler handler) {
    RequestLog requestLog = new Log4JAccessLog(configuration.getAccessLogConfigFilePath(),
            () -> configuration.isAccessLogEnabled());
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);
    requestLogHandler.setHandler(handler);

    return requestLogHandler;
}
 
Example 9
Source File: JettyLogbackAccessInstaller.java    From logback-access-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps the Jetty handler.
 *
 * @param server the Jetty server.
 */
private void wrapJettyHandler(Server server) {
    LogbackAccessJettyRequestLog requestLog = new LogbackAccessJettyRequestLog(
            logbackAccessProperties, environment, applicationEventPublisher);
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setHandler(server.getHandler());
    requestLogHandler.setRequestLog(requestLog);
    server.setHandler(requestLogHandler);
}
 
Example 10
Source File: MinimalServletsWithLogging.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
       // Create a basic jetty server object that will listen on port 8080.  Note that if you set this to port 0
       // then a randomly available port will be assigned that you can either look in the logs for the port,
       // or programmatically obtain it for use in test cases.
       Server server = new Server(8080);
	HandlerCollection handlers = new HandlerCollection();
	server.setHandler(handlers);

       ServletHandler servlet = new ServletHandler();
	servlet.addServletWithMapping(HelloServlet.class, "/*");
	handlers.addHandler(servlet);

	handlers.addHandler(new DefaultHandler()); // must be after servlet it seems

	// log using NCSA (common log format)
	// http://en.wikipedia.org/wiki/Common_Log_Format
	NCSARequestLog requestLog = new NCSARequestLog();
	requestLog.setFilename("/tmp/yyyy_mm_dd.request.log");
	requestLog.setFilenameDateFormat("yyyy_MM_dd");
	requestLog.setRetainDays(90);
	requestLog.setAppend(true);
	requestLog.setExtended(true);
	requestLog.setLogCookies(false);
	requestLog.setLogTimeZone("GMT");
	RequestLogHandler requestLogHandler = new RequestLogHandler();
	requestLogHandler.setRequestLog(requestLog);
	handlers.addHandler(requestLogHandler);

	// Start things up! By using the server.join() the server thread will join with the current thread.
	// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
	server.start();
	server.join();
}
 
Example 11
Source File: JettyStarter.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
public List<String> deployWebApplications(String rmUrl, String schedulerUrl) {
    initializeRestProperties();

    setSystemPropertyIfNotDefined("rm.url", rmUrl);
    setSystemPropertyIfNotDefined("scheduler.url", schedulerUrl);

    if (WebProperties.WEB_DEPLOY.getValueAsBoolean()) {
        logger.info("Starting the web applications...");

        int httpPort = getJettyHttpPort();
        int httpsPort = 443;
        if (WebProperties.WEB_HTTPS_PORT.isSet()) {
            httpsPort = WebProperties.WEB_HTTPS_PORT.getValueAsInt();
        }

        boolean httpsEnabled = WebProperties.WEB_HTTPS.getValueAsBoolean();
        boolean redirectHttpToHttps = WebProperties.WEB_REDIRECT_HTTP_TO_HTTPS.getValueAsBoolean();

        int restPort = httpPort;

        String httpProtocol;
        String[] defaultVirtualHost;
        String[] httpVirtualHost = new String[] { "@" + HTTP_CONNECTOR_NAME };

        if (httpsEnabled) {
            httpProtocol = "https";
            defaultVirtualHost = new String[] { "@" + HTTPS_CONNECTOR_NAME };
            restPort = httpsPort;
        } else {
            defaultVirtualHost = httpVirtualHost;
            httpProtocol = "http";
        }

        Server server = createHttpServer(httpPort, httpsPort, httpsEnabled, redirectHttpToHttps);

        server.setStopAtShutdown(true);

        HandlerList handlerList = new HandlerList();

        if (WebProperties.JETTY_LOG_FILE.isSet()) {
            String pathToJettyLogFile = FileStorageSupportFactory.relativeToHomeIfNotAbsolute(WebProperties.JETTY_LOG_FILE.getValueAsString());
            File jettyLogFile = new File(pathToJettyLogFile);
            if (!jettyLogFile.getParentFile().exists() && !jettyLogFile.getParentFile().mkdirs()) {
                logger.error("Could not create jetty log file in: " +
                             WebProperties.JETTY_LOG_FILE.getValueAsString());
            } else {
                NCSARequestLog requestLog = new NCSARequestLog(pathToJettyLogFile);
                requestLog.setAppend(true);
                requestLog.setExtended(false);
                requestLog.setLogTimeZone("GMT");
                requestLog.setLogLatency(true);
                requestLog.setRetainDays(WebProperties.JETTY_LOG_RETAIN_DAYS.getValueAsInt());

                RequestLogHandler requestLogHandler = new RequestLogHandler();
                requestLogHandler.setRequestLog(requestLog);
                handlerList.addHandler(requestLogHandler);
            }
        }

        if (httpsEnabled && redirectHttpToHttps) {
            ContextHandler redirectHandler = new ContextHandler();
            redirectHandler.setContextPath("/");
            redirectHandler.setHandler(new SecuredRedirectHandler());
            redirectHandler.setVirtualHosts(httpVirtualHost);
            handlerList.addHandler(redirectHandler);
        }

        addWarsToHandlerList(handlerList, defaultVirtualHost);
        server.setHandler(handlerList);

        String schedulerHost = ProActiveInet.getInstance().getHostname();
        return startServer(server, schedulerHost, restPort, httpProtocol);
    }
    return new ArrayList<>();
}
 
Example 12
Source File: Application.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
final Handler configureHandler() {
  ResourceConfig resourceConfig = new ResourceConfig();
  configureBaseApplication(resourceConfig, getMetricsTags());
  configureResourceExtensions(resourceConfig);
  setupResources(resourceConfig, getConfiguration());

  // Configure the servlet container
  ServletContainer servletContainer = new ServletContainer(resourceConfig);
  final FilterHolder servletHolder = new FilterHolder(servletContainer);

  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath(path);

  ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
  defaultHolder.setInitParameter("dirAllowed", "false");

  ResourceCollection staticResources = getStaticResources();
  if (staticResources != null) {
    context.setBaseResource(staticResources);
  }

  configureSecurityHandler(context);

  if (isCorsEnabled()) {
    String allowedOrigins = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
    filterHolder.setName("cross-origin");
    filterHolder.setInitParameter(
            CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins

    );
    String allowedMethods = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_METHODS);
    String allowedHeaders = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_HEADERS);
    if (allowedMethods != null && !allowedMethods.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
    }
    if (allowedHeaders != null && !allowedHeaders.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, allowedHeaders);
    }
    // handle preflight cors requests at the filter level, do not forward down the filter chain
    filterHolder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false");
    context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
  }

  if (config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG) != null
          && !config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG).isEmpty()) {
    configureHttpResponsHeaderFilter(context);
  }

  configurePreResourceHandling(context);
  context.addFilter(servletHolder, "/*", null);
  configurePostResourceHandling(context);
  context.addServlet(defaultHolder, "/*");

  applyCustomConfiguration(context, REST_SERVLET_INITIALIZERS_CLASSES_CONFIG);

  RequestLogHandler requestLogHandler = new RequestLogHandler();
  requestLogHandler.setRequestLog(requestLog);

  HandlerCollection handlers = new HandlerCollection();
  handlers.setHandlers(new Handler[]{context, requestLogHandler});

  return handlers;
}
 
Example 13
Source File: GatewayServer.java    From knox with Apache License 2.0 4 votes vote down vote up
private static HandlerCollection createHandlers(
    final GatewayConfig config,
    final GatewayServices services,
    final ContextHandlerCollection contexts,
    final Map<String, Integer> topologyPortMap) {

  final Map<String, Handler> contextToHandlerMap = new HashMap<>();
  if(contexts.getHandlers() != null) {
    Arrays.asList(contexts.getHandlers()).stream()
        .filter(h -> h instanceof WebAppContext)
        .forEach(h -> contextToHandlerMap
            .put(((WebAppContext) h).getContextPath(), h));
  }

  HandlerCollection handlers = new HandlerCollection();
  RequestLogHandler logHandler = new RequestLogHandler();

  logHandler.setRequestLog( new AccessHandler() );

  TraceHandler traceHandler = new TraceHandler();
  traceHandler.setHandler( contexts );
  traceHandler.setTracedBodyFilter( System.getProperty( "org.apache.knox.gateway.trace.body.status.filter" ) );

  CorrelationHandler correlationHandler = new CorrelationHandler();
  correlationHandler.setHandler( traceHandler );

  // Used to correct the {target} part of request with Topology Port Mapping feature
  final PortMappingHelperHandler portMappingHandler = new PortMappingHelperHandler(config);
  portMappingHandler.setHandler(correlationHandler);

   // If topology to port mapping feature is enabled then we add new Handler {RequestForwardHandler}
   // to the chain, this handler listens on the configured port (in gateway-site.xml)
   // and simply forwards requests to the correct context path.

   //  The reason for adding ContextHandler is so that we can add a connector
   // to it on which the handler listens (exclusively).


  if (config.isGatewayPortMappingEnabled()) {

    /* Do the virtual host bindings for all the defined topology port mapped
    *  contexts except for the one that has gateway port to prevent issues
    *  with context deployment */
    topologyPortMap
        .entrySet()
        .stream()
        .filter(e -> !e.getValue().equals(config.getGatewayPort()))
        .forEach( entry ->  {
          log.createJettyHandler(entry.getKey());
          final Handler context = contextToHandlerMap
              .get("/" + config.getGatewayPath() + "/" + entry.getKey());

          if(context !=  null) {
            ((WebAppContext) context).setVirtualHosts(
                new String[] { "@" + entry.getKey().toLowerCase(Locale.ROOT) });
          } else {
            // no topology found for mapping entry.getKey()
            log.noMappedTopologyFound(entry.getKey());
          }
        });
  }

  handlers.addHandler(logHandler);

  if (config.isWebsocketEnabled()) {
    final GatewayWebsocketHandler websocketHandler = new GatewayWebsocketHandler(
        config, services);
    websocketHandler.setHandler(portMappingHandler);

    handlers.addHandler(websocketHandler);

  } else {
    handlers.addHandler(portMappingHandler);
  }

  return handlers;
}
 
Example 14
Source File: HttpServer2.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
private void initializeWebServer(String name, String hostName,
    ConfigurationSource conf, String[] pathSpecs,
    String authFilterConfigPrefix,
    boolean securityEnabled) throws IOException {

  Preconditions.checkNotNull(webAppContext);

  int maxThreads = conf.getInt(HTTP_MAX_THREADS_KEY, -1);
  // If HTTP_MAX_THREADS is not configured, QueueThreadPool() will use the
  // default value (currently 250).

  QueuedThreadPool threadPool = (QueuedThreadPool) webServer.getThreadPool();
  threadPool.setDaemon(true);
  if (maxThreads != -1) {
    threadPool.setMaxThreads(maxThreads);
  }

  SessionHandler handler = webAppContext.getSessionHandler();
  handler.setHttpOnly(true);
  handler.getSessionCookieConfig().setSecure(true);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  RequestLog requestLog = HttpRequestLog.getRequestLog(name);

  handlers.addHandler(contexts);
  if (requestLog != null) {
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);
    handlers.addHandler(requestLogHandler);
  }
  handlers.addHandler(webAppContext);
  final String appDir = getWebAppsPath(name);
  addDefaultApps(contexts, appDir, conf);
  webServer.setHandler(handlers);

  Map<String, String> xFrameParams = setHeaders(conf);
  addGlobalFilter("safety", QuotingInputFilter.class.getName(), xFrameParams);
  final FilterInitializer[] initializers = getFilterInitializers(conf);
  if (initializers != null) {
    conf.set(BIND_ADDRESS, hostName);
    org.apache.hadoop.conf.Configuration hadoopConf =
        LegacyHadoopConfigurationSource.asHadoopConfiguration(conf);
    Map<String, String> filterConfig = getFilterConfigMap(hadoopConf,
        authFilterConfigPrefix);
    for (FilterInitializer c : initializers) {
      if ((c instanceof AuthenticationFilterInitializer) && securityEnabled) {
        addFilter("authentication",
            AuthenticationFilter.class.getName(), filterConfig);
      } else {
        c.initFilter(this, hadoopConf);
      }
    }
  }

  addDefaultServlets();

  if (pathSpecs != null) {
    for (String path : pathSpecs) {
      LOG.info("adding path spec: {}", path);
      addFilterPathMapping(path, webAppContext);
    }
  }
}
 
Example 15
Source File: WorkerServer.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private void init() {
    server = new Server(webServerExecutor);

    List<ServerConnector> connectors = new ArrayList<>();
    httpConnector = new ServerConnector(server, 1, 1);
    httpConnector.setPort(this.workerConfig.getWorkerPort());
    connectors.add(httpConnector);

    List<Handler> handlers = new ArrayList<>(4);
    handlers.add(
            newServletContextHandler("/admin", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v2", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v3", new ResourceConfig(Resources.getApiV3Resources()), workerService));
    // don't require auth for metrics or config routes
    handlers.add(newServletContextHandler("/", new ResourceConfig(Resources.getRootResources()), workerService, workerConfig.isAuthenticateMetricsEndpoint()));

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    if (this.workerConfig.getWorkerPortTls() != null) {
        try {
            SslContextFactory sslCtxFactory = SecurityUtility.createSslContextFactory(
                    this.workerConfig.isTlsAllowInsecureConnection(), this.workerConfig.getTlsTrustCertsFilePath(),
                    this.workerConfig.getTlsCertificateFilePath(), this.workerConfig.getTlsKeyFilePath(),
                    this.workerConfig.isTlsRequireTrustedClientCertOnConnect(),
                    true,
                    this.workerConfig.getTlsCertRefreshCheckDurationSec());
            httpsConnector = new ServerConnector(server, 1, 1, sslCtxFactory);
            httpsConnector.setPort(this.workerConfig.getWorkerPortTls());
            connectors.add(httpsConnector);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Limit number of concurrent HTTP connections to avoid getting out of file descriptors
    connectors.forEach(c -> c.setAcceptQueueSize(MAX_CONCURRENT_REQUESTS / connectors.size()));
    server.setConnectors(connectors.toArray(new ServerConnector[connectors.size()]));
}
 
Example 16
Source File: RestServer.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public void start() {
        log.info("Starting REST server");
        ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.register(DataxResource.class);

        ServletContainer servletContainer = new ServletContainer(resourceConfig);
        ServletHolder servletHolder = new ServletHolder(servletContainer);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.addServlet(servletHolder, "/*");

        String allowedOrigins = System.getProperty(ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
        if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
            FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
            filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = System.getProperty(ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
            context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);


    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler});

    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new RuntimeException("Unable to start REST server", e);
    }

    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
 
Example 17
Source File: RestServer.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public void start(Keeper keeper) {
    log.info("Starting REST server");

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages("com.ucar.datalink.worker.core.runtime.rest.resources");
    resourceConfig.register(new FastJsonProvider());
    resourceConfig.register(RootResource.class);
    resourceConfig.register(new TasksResource(keeper));
    resourceConfig.register(RestExceptionMapper.class);
    resourceConfig.register(FlushResource.class);
    resourceConfig.register(HBaseMetaResource.class);
    resourceConfig.register(WorkerResource.class);

    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");

    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler});

    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new DatalinkException("Unable to start REST server", e);
    }

    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}