Java Code Examples for org.eclipse.jetty.server.handler.HandlerCollection#setHandlers()

The following examples show how to use org.eclipse.jetty.server.handler.HandlerCollection#setHandlers() . 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: 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 2
Source File: EmbeddedServer.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example 3
Source File: JAXRSClientServerWebSocketSpringWebAppTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static void startServers(String port) throws Exception {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(port));

    WebAppContext webappcontext = new WebAppContext();
    String contextPath = null;
    try {
        contextPath = JAXRSClientServerWebSocketSpringWebAppTest.class
            .getResource("/jaxrs_websocket").toURI().getPath();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    webappcontext.setContextPath("/webapp");

    webappcontext.setWar(contextPath);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
}
 
Example 4
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    System.out.println("Starting Server");

    /**
     * Important: This code simply starts up a servlet container and adds
     * the web application in src/webapp to it. Normally you would be using
     * Jetty or Tomcat and have the webapp packaged as a WAR. This is simply
     * as a convenience so you do not need to configure your servlet
     * container to see CXF in action!
     */
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9002);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    webappcontext.setWar("target/GroovySpringSupport.war");

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

    server.setHandler(handlers);
    server.start();
    System.out.println("Server ready...");
    server.join();
}
 
Example 5
Source File: Jetty9Server.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    server.addEventListener(mbeans());
    server.addConnector(plainConnector());

    ContextHandlerCollection handlers = new ContextHandlerCollection();
    deploymentManager.setContexts(handlers);

    createWebAppContext();

    JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler();
    webAppContext.setErrorHandler(errorHandler);
    webAppContext.setGzipHandler(gzipHandler());
    server.addBean(errorHandler);
    server.addBean(deploymentManager);

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

    performCustomConfiguration();
    server.setStopAtShutdown(true);
}
 
Example 6
Source File: EmbeddedServer.java    From jaxrs with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	URI baseUri = UriBuilder.fromUri("http://localhost").port(SERVER_PORT)
			.build();
	ResourceConfig config = new ResourceConfig(Calculator.class);
	Server server = JettyHttpContainerFactory.createServer(baseUri, config,
			false);

	ContextHandler contextHandler = new ContextHandler("/rest");
	contextHandler.setHandler(server.getHandler());
	
	ProtectionDomain protectionDomain = EmbeddedServer.class
			.getProtectionDomain();
	URL location = protectionDomain.getCodeSource().getLocation();
	
	ResourceHandler resourceHandler = new ResourceHandler();
	resourceHandler.setWelcomeFiles(new String[] { "index.html" });
	resourceHandler.setResourceBase(location.toExternalForm());
	System.out.println(location.toExternalForm());
	HandlerCollection handlerCollection = new HandlerCollection();
	handlerCollection.setHandlers(new Handler[] { resourceHandler,
			contextHandler, new DefaultHandler() });
	server.setHandler(handlerCollection);
	server.start();
	server.join();
}
 
Example 7
Source File: JAXRSClientServerWebSocketSpringWebAppNoAtmosphereTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected static void startServers(String port) throws Exception {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(port));

    WebAppContext webappcontext = new WebAppContext();
    String contextPath = null;
    try {
        contextPath = JAXRSClientServerWebSocketSpringWebAppTest.class
            .getResource("/jaxrs_websocket").toURI().getPath();
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }
    webappcontext.setContextPath("/webapp");

    webappcontext.setWar(contextPath);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
}
 
Example 8
Source File: Application.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");

    Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
    String clientSecret = properties.getProperty("client.secret");

    HandlerCollection handlers = new HandlerCollection();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());

    VkApiClient vk = new VkApiClient(new HttpTransportClient());
    handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example 9
Source File: Application.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");

    Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
    String clientSecret = properties.getProperty("client.secret");

    HandlerCollection handlers = new HandlerCollection();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());

    VkApiClient vk = new VkApiClient(new HttpTransportClient());
    handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example 10
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    System.out.println("Starting Server");

    /**
     * Important: This code simply starts up a servlet container and adds
     * the web application in src/webapp to it. Normally you would be using
     * Jetty or Tomcat and have the webapp packaged as a WAR. This is simply
     * as a convenience so you do not need to configure your servlet
     * container to see CXF in action!
     */
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9002);

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    webappcontext.setWar("target/JavaFirstSpringSupport.war");

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

    server.setHandler(handlers);
    server.start();
    System.out.println("Server ready...");
    server.join();
}
 
Example 11
Source File: StandaloneAdminWeb.java    From chipster with MIT License 5 votes vote down vote up
public static void main(String args[]) throws Exception {
	org.eclipse.jetty.server.Server adminServer = new org.eclipse.jetty.server.Server();
	ServerConnector connector = new ServerConnector(adminServer);
	connector.setPort(8083);
	adminServer.setConnectors(new Connector[]{ connector });
	
	Constraint constraint = new Constraint();
	constraint.setName(Constraint.__BASIC_AUTH);
	constraint.setRoles(new String[] {"admin_role"});
	constraint.setAuthenticate(true);
	
	ConstraintMapping cm = new ConstraintMapping();
	cm.setConstraint(constraint);
	cm.setPathSpec("/*");
	
	HashLoginService loginService = new HashLoginService("Please enter Chipster Admin username and password");
	loginService.update("chipster", 
			new Password("chipster"), 
			new String[] {"admin_role"});
	
	ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
	sh.setLoginService(loginService);
	sh.addConstraintMapping(cm);
	
	WebAppContext context = new WebAppContext();
	File war = new File("../chipster/dist/admin-web.war");
	//File war = new File("webapps/admin-web.war");
	context.setWar(war.getAbsolutePath());
	System.out.println(war.getAbsolutePath());
       context.setContextPath("/");
			
       context.setHandler(sh);
	HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] {context, new DefaultHandler()});
			
	adminServer.setHandler(handlers);
       adminServer.start();
}
 
Example 12
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception {
    Server server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("json", "application/json");
    resourceHandler.setMimeTypes(mimeTypes);
    URL url = this.getClass().getResource(".");
    resourceHandler.setBaseResource(new FileResource(url));
    resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"});

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.addServlet(loginServletClass, "/login/");

    ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth"));
    basicAuthContextHandler.setContextPath("/a");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {
        servletContextHandler,
        resourceHandler,
        basicAuthContextHandler
    });
    server.setHandler(handlers);

    server.start();

    Connector connector = server.getConnectors()[0];
    String host = "localhost";
    int port = connector.getLocalPort();
    return String.format("http://%s:%s", host, port);
}
 
Example 13
Source File: Application.java    From vk-java-sdk with MIT License 5 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");
    HandlerCollection handlers = new HandlerCollection();

    ConfirmationCodeRequestHandler confirmationCodeRequestHandler = null;

    GetCallbackServersResponse getCallbackServersResponse = vk.groups().getCallbackServers(actor, actor.getGroupId()).execute();
    CallbackServer callbackServer = isServerExist(getCallbackServersResponse.getItems(), host);

    if (callbackServer == null) {
        GetCallbackConfirmationCodeResponse getCallbackConfirmationCodeResponse = vk().groups().getCallbackConfirmationCode(actor, actor.getGroupId()).execute();
        String confirmationCode = getCallbackConfirmationCodeResponse.getCode();
        confirmationCodeRequestHandler = new ConfirmationCodeRequestHandler(confirmationCode);
    }

    CallbackRequestHandler callbackRequestHandler = new CallbackRequestHandler();

    if (callbackServer == null) {
        handlers.setHandlers(new Handler[]{confirmationCodeRequestHandler, callbackRequestHandler});
    } else {
        handlers.setHandlers(new Handler[]{callbackRequestHandler}); //temp solution
    }

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();

    if (callbackServer == null) {
        AddCallbackServerResponse addServerResponse = vk.groups().addCallbackServer(actor, actor.getGroupId(), host, "YouTrack Bot").execute();
        Integer serverId = addServerResponse.getServerId();
        vk.groups().setCallbackSettings(actor, serverId).messageNew(true).execute();
    }

    server.join();
}
 
Example 14
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 15
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 16
Source File: WebstartJettyServer.java    From chipster with MIT License 4 votes vote down vote up
public void start() {

	try {
		// initialise config and logging
		DirectoryLayout.initialiseServerLayout(Arrays.asList(new String[] {"webstart"}));
		Configuration configuration = DirectoryLayout.getInstance().getConfiguration();
		logger = Logger.getLogger(WebstartJettyServer.class);
		if (logger.isDebugEnabled()) {
			System.setProperty("DEBUG", "true");
		}

		// initialise jetty
		jettyInstance = new Server();
		ServerConnector connector = new ServerConnector(jettyInstance);
		connector.setPort(configuration.getInt("webstart", "port"));
		jettyInstance.setConnectors(new Connector[]{ connector });

		// webstart front page
		ServletContextHandler wsRoot = new ServletContextHandler(jettyInstance, "/", false, false);
		wsRoot.setResourceBase(DirectoryLayout.WEB_ROOT + "/");
		wsRoot.addServlet(new ServletHolder(new DefaultServlet()), "/*");
		
		// dynamic jnlp servlet
		wsRoot.addServlet(new ServletHolder(new JnlpServlet()), "/servlet.jnlp");

		// tooleditor web app
		WebAppContext context = new WebAppContext();
		context.setWar(new File(DirectoryLayout.getInstance().getWebappsDir(), "tool-editor.war").getAbsolutePath());
        context.setContextPath("/tool-editor");
		
        // seems to work like this, no idea if this is correct way to do it
		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] {context, wsRoot});
		jettyInstance.setHandler(handlers);
		
		jettyInstance.start();

		// create keep-alive thread and register shutdown hook
		KeepAliveShutdownHandler.init(this);
		
		logger.info("webstart is up and running [" + ApplicationConstants.VERSION + "]");
		logger.info("[mem: " + SystemMonitorUtil.getMemInfo() + "]");

	} catch (Exception e) {
		e.printStackTrace();
		logger.error(e, e);
	}
}
 
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());
}
 
Example 18
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 19
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 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());
}