org.eclipse.jetty.server.handler.RequestLogHandler Java Examples

The following examples show how to use org.eclipse.jetty.server.handler.RequestLogHandler. 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: WebContainerAccessLogAutoConfiguration.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer accessWebServerFactoryCustomizer() {
    return factory -> {
        if (factory instanceof JettyServletWebServerFactory) {
            ((JettyServletWebServerFactory) factory).addServerCustomizers((JettyServerCustomizer) server -> {
                HandlerCollection handlers = new HandlerCollection();
                for (Handler handler : server.getHandlers()) {
                    handlers.addHandler(handler);
                }
                RequestLogHandler reqLogs = new RequestLogHandler();
                Slf4jRequestLog requestLog = new Slf4jRequestLog();
                requestLog.setLoggerName("access-log");
                requestLog.setLogLatency(false);

                reqLogs.setRequestLog(requestLog);
                handlers.addHandler(reqLogs);
                server.setHandler(handlers);
            });
        }
    };
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	final Server server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example #11
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	context.addEventListener(new SessionListener());

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example #12
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 #13
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 #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: 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 #16
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 #17
Source File: ProxyServerFactory.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static Server of(String proxyTo, int port, File keystoreFile, String keystorePassword) {
  Server proxy = new Server();
  logger.info("Setting up HTTPS connector for web server");

  final SslContextFactory sslContextFactory = new SslContextFactory.Client();

  sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
  sslContextFactory.setKeyStorePassword(keystorePassword);

  // SSL Connector
  final ServerConnector sslConnector = new ServerConnector(proxy,
      new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
      new HttpConnectionFactory(new HttpConfiguration()));
  // regular http connector if one needs to inspect the wire. Requires tweaking the ElasticsearchPlugin to use http
  // final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
  //   new HttpConnectionFactory(new HttpConfiguration()));
  sslConnector.setPort(port);
  proxy.addConnector(sslConnector);

  // root handler with request logging
  final RequestLogHandler rootHandler = new RequestLogHandler();
  proxy.setHandler(rootHandler);

  final ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  servletContextHandler.setContextPath("/");
  rootHandler.setHandler(servletContextHandler);

  // error handler
  ProxyServlet.Transparent proxyServlet = new ProxyServlet.Transparent() {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
      try {
        HttpServletRequest hr = (HttpServletRequest) req;
        logger.debug("incoming {} {}://{}:{} {}",
            hr.getMethod(),
            req.getScheme(),
            req.getServerName(),
            req.getServerPort(),
            hr.getRequestURL());
        super.service(req, res);
      } catch (Exception e) {
        logger.error("can't proxy " + req, e);
        throw new RuntimeException(e);
      }
    }

    @Override
    protected String rewriteTarget(HttpServletRequest clientRequest) {
      final String serverName = clientRequest.getServerName();
      final int serverPort = clientRequest.getServerPort();
      final String query = clientRequest.getQueryString();

      String result = super.rewriteTarget(clientRequest);

      logger.debug("Proxying {}://{}:{}{} to {}\n",
          clientRequest.getScheme(),
          serverName,
          serverPort,
          query != null ? '?' + query : "",
          result);

      return result;
    }
  };
  // Rest API
  final ServletHolder proxyHolder = new ServletHolder(proxyServlet);
  proxyHolder.setInitParameter("proxyTo", proxyTo);
  proxyHolder.setInitOrder(1);

  servletContextHandler.addServlet(proxyHolder, "/*");

  return proxy;
}
 
Example #18
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 #19
Source File: ParaServer.java    From para with Apache License 2.0 4 votes vote down vote up
/**
 * @return Jetty config bean
 */
@Bean
public ServletWebServerFactory jettyConfigBean() {
	JettyServletWebServerFactory jef = new JettyServletWebServerFactory();
	jef.addServerCustomizers((JettyServerCustomizer) (Server server) -> {
		if (Config.getConfigBoolean("access_log_enabled", true)) {
			// enable access log via Logback
			HandlerCollection handlers = new HandlerCollection();
			for (Handler handler : server.getHandlers()) {
				handlers.addHandler(handler);
			}
			RequestLogHandler reqLogs = new RequestLogHandler();
			reqLogs.setServer(server);
			RequestLogImpl rli = new RequestLogImpl();
			rli.setResource("/logback-access.xml");
			rli.setQuiet(true);
			rli.start();
			reqLogs.setRequestLog(rli);
			handlers.addHandler(reqLogs);
			server.setHandler(handlers);
		}

		for (Connector y : server.getConnectors()) {
			for (ConnectionFactory cf : y.getConnectionFactories()) {
				if (cf instanceof HttpConnectionFactory) {
					HttpConnectionFactory dcf = (HttpConnectionFactory) cf;
					// support for X-Forwarded-Proto
					// redirect back to https if original request uses it
					if (Config.IN_PRODUCTION) {
						ForwardedRequestCustomizer frc = new ForwardedRequestCustomizer() {
							public void customize(Connector connector, HttpConfiguration config, Request request) {
								super.customize(connector, config, request);
								String cfProto = request.getHeader("CloudFront-Forwarded-Proto");
								if (StringUtils.equalsIgnoreCase(cfProto, config.getSecureScheme())) {
									request.setScheme(cfProto);
									request.setSecure(true);
								}
							}
						};
						HttpConfiguration httpConfiguration = dcf.getHttpConfiguration();
						httpConfiguration.addCustomizer(frc);
					}
					// Disable Jetty version header
					dcf.getHttpConfiguration().setSendServerVersion(false);
					// Increase idle timeout
					dcf.getHttpConfiguration().setIdleTimeout(TimeUnit.MINUTES.toMillis(5));
				}
			}
		}
	});
	String contextPath = Config.getConfigParam("context_path", "");
	if (StringUtils.length(contextPath) > 1 && contextPath.charAt(0) == '/') {
		jef.setContextPath(contextPath);
	}
	jef.setPort(getServerPort());
	logger.info("Listening on port {}...", jef.getPort());
	return jef;
}
 
Example #20
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 #21
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 #22
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());
}
 
Example #23
Source File: JettyHttpServer.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler handler = new RequestLogHandler();

    if (context == null) {
        context = new ServletContextHandler(handler, "/", ServletContextHandler.SESSIONS);
    }

    context.setEventListeners(new EventListener[]{new EverrestInitializedListener()});
    ServletHolder servletHolder = new ServletHolder(new EverrestServlet());

    context.addServlet(servletHolder, UNSECURE_PATH_SPEC);
    context.addServlet(servletHolder, SECURE_PATH_SPEC);

    //set up security
    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[]{"cloud-admin", "users", "user", "temp_user"});
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec(SECURE_PATH_SPEC);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.addConstraintMapping(constraintMapping);

    HashLoginService loginService = new HashLoginService();

    UserStore userStore = new UserStore();

    userStore.addUser(ADMIN_USER_NAME, new Password(ADMIN_USER_PASSWORD),
                         new String[]{"cloud-admin",
                                      "users",
                                      "user",
                                      "temp_user",
                                      "developer",
                                      "admin",
                                      "workspace/developer",
                                      "workspace/admin",
                                      "account/owner",
                                      "account/member",
                                      "system/admin",
                                      "system/manager"
                         });
    userStore.addUser(MANAGER_USER_NAME, new Password(MANAGER_USER_PASSWORD), new String[]{"cloud-admin",
                                                                                              "user",
                                                                                              "temp_user",
                                                                                              "users"});
    loginService.setUserStore(userStore);

    securityHandler.setLoginService(loginService);
    securityHandler.setAuthenticator(new BasicAuthenticator());

    context.setSecurityHandler(securityHandler);

    server.setHandler(handler);

    server.start();
    ResourceBinder binder =
            (ResourceBinder)context.getServletContext().getAttribute(ResourceBinder.class.getName());
    DependencySupplier dependencies =
            (DependencySupplier)context.getServletContext().getAttribute(DependencySupplier.class.getName());
    GroovyResourcePublisher groovyPublisher = new GroovyResourcePublisher(binder, dependencies);
    context.getServletContext().setAttribute(GroovyResourcePublisher.class.getName(), groovyPublisher);

}