Java Code Examples for org.eclipse.jetty.server.Server#setConnectors()

The following examples show how to use org.eclipse.jetty.server.Server#setConnectors() . 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: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
private static Server startServer(ContextHandlerCollection contexts, int port) throws Exception {
    System.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, "http://localhost:" + port);
    setBounceProxyUrl();
    setDirectoriesUrl();
    logger.info("HOST PATH: {}", System.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH));

    final Server jettyServer = new Server();
    ServerConnector connector = new ServerConnector(jettyServer,
                                                    new HttpConnectionFactory(new HttpConfiguration()));
    connector.setPort(port);
    connector.setAcceptQueueSize(1);
    jettyServer.setConnectors(new Connector[]{ connector });

    jettyServer.setHandler(contexts);
    jettyServer.start();

    logger.trace("Started jetty server: {}", jettyServer.dump());

    return jettyServer;
}
 
Example 2
Source File: ApiIT.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    // Check if executed inside target directory or module directory
    String pathPrefix =new File(".").getCanonicalFile().getName().equals("target") ? "../" : "./";

    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(18080);
    connector.setHost("localhost");
    server.setConnectors(new Connector[]{connector});

    WebAppContext context = new WebAppContext();
    context.setDescriptor(pathPrefix + "src/main/webapp/WEB-INF/web.xml");
    context.setResourceBase(pathPrefix + "src/main/webapp");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);

    server.setHandler(context);

    server.start();

    client = ClientBuilder.newClient();
    root = client.target("http://" + connector.getHost() + ':' + connector.getPort() + '/');
}
 
Example 3
Source File: RestHelper.java    From kafka-connect-http with Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
    //flushCapturedRequests();
    server = new Server(0);
    ServerConnector connector = new ServerConnector(server);
    ServletContextHandler handler = new ServletContextHandler();
    ServletHolder testServ = new ServletHolder("test", RestHelper.class);
    testServ.setInitParameter("resourceBase",System.getProperty("user.dir"));
    testServ.setInitParameter("dirAllowed","true");
    handler.addServlet(testServ,"/test");
    handler.addServlet(testServ,"/someTopic");
    handler.addServlet(testServ,"/someKey");



    server.setHandler(handler);
    server.setConnectors(new Connector[]{connector});

    server.start();

    port = server.getURI().getPort();

}
 
Example 4
Source File: TestServer.java    From chipster with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Server jettyInstance = new Server();
	ServerConnector connector = new ServerConnector(jettyInstance);
	connector.setPort(9080);
	SslContextFactory sslContext = new SslContextFactory("keystore.ks");
	sslContext.setKeyStorePassword("microarray");
	ServerConnector sslConnector = new ServerConnector(jettyInstance);
	sslConnector.setPort(9443);
	jettyInstance.setConnectors(new Connector[]{ connector, sslConnector });

	ServletContextHandler root = new ServletContextHandler(jettyInstance, "/", false, false);
	root.setResourceBase("/tmp/test-root");
	root.addServlet(new ServletHolder(new UploadServlet()), "/*");
	jettyInstance.start();
}
 
Example 5
Source File: StartSolrJetty.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static void main( String[] args )
  {
    //System.setProperty("solr.solr.home", "../../../example/solr");

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
    // Set some timeout options to make debugging easier.
    connector.setIdleTimeout(1000 * 60 * 60);
    connector.setPort(8983);
    server.setConnectors(new Connector[] { connector });

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/solr");
    bb.setWar("webapp/web");

//    // START JMX SERVER
//    if( true ) {
//      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
//      MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
//      server.getContainer().addEventListener(mBeanContainer);
//      mBeanContainer.start();
//    }

    server.setHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      while (System.in.available() == 0) {
        Thread.sleep(5000);
      }
      server.stop();
      server.join();
    }
    catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
 
Example 6
Source File: Main.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Flags flags = new Flags();
  JCommander.newBuilder().addObject(flags).build().parse(args);

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(flags.port);
  server.setConnectors(new Connector[] {connector });

  HandlerList handlers = new HandlerList();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/tests");
  ResourceHandler testHandler = new ResourceHandler();
  testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
  testHandler.setDirectoriesListed(true);
  context.setHandler(testHandler);
  handlers.addHandler(context);

  ContextHandler coreContext = new ContextHandler();
  coreContext.setContextPath("/core");
  ResourceHandler coreHandler = new ResourceHandler();
  coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
  coreContext.setHandler(coreHandler);
  handlers.addHandler(coreContext);

  ServletContextHandler driverContext = new ServletContextHandler();
  driverContext.setContextPath("/");
  driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
  handlers.addHandler(driverContext);

  server.setHandler(handlers);
  server.start();
}
 
Example 7
Source File: InfluxDBWarp10Plugin.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Server server = new Server(new QueuedThreadPool(maxThreads, 8, idleTimeout, queue));
  ServerConnector connector = new ServerConnector(server, acceptors, selectors);
  connector.setIdleTimeout(idleTimeout);
  connector.setPort(port);
  connector.setHost(host);
  connector.setName("Continuum Ingress");
  
  server.setConnectors(new Connector[] { connector });

  HandlerList handlers = new HandlerList();
  
  Handler cors = new CORSHandler();
  handlers.addHandler(cors);

  handlers.addHandler(new InfluxDBHandler(url, token));
  
  server.setHandler(handlers);
  
  JettyUtil.setSendServerVersion(server, false);

  try {
    server.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 8
Source File: JettyBootStrap.java    From demo-springmvc-shiro with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
private static Server createServer(){
	Server server = new Server();
	server.setStopAtShutdown(true);
	SelectChannelConnector connector = new SelectChannelConnector();
	connector.setPort(port);
	connector.setReuseAddress(false);
	server.setConnectors(new Connector[]{connector});
	String webAppPath = JettyBootStrap.class.getClassLoader().getResource(".").getFile();
	webAppPath = webAppPath.substring(0, webAppPath.indexOf("target")) + "src/main/webapp";
	WebAppContext context = new WebAppContext(webAppPath, contextPath);
	server.setHandler(context);
	return server;
}
 
Example 9
Source File: RESTInterface.java    From nadia with Apache License 2.0 5 votes vote down vote up
@Override
public void start(){
	try{
		NadiaProcessorConfig config = NadiaProcessorConfig.getInstance();
		
		//Jetty:
		server = new Server();
		
		//main config
        WebAppContext context = new WebAppContext();
        context.setDescriptor(config.getProperty(NadiaProcessorConfig.JETTYWEBXMLPATH));
        context.setResourceBase(config.getProperty(NadiaProcessorConfig.JETTYRESOURCEBASE));
        context.setContextPath(config.getProperty(NadiaProcessorConfig.JETTYCONTEXTPATH));
        context.setParentLoaderPriority(true);
        server.setHandler(context);
        
        //ssl (https)
        SslContextFactory sslContextFactory = new SslContextFactory(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPATH));
        sslContextFactory.setKeyStorePassword(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPASS));

        ServerConnector serverconn = new ServerConnector(server, sslContextFactory);
        serverconn.setPort(8080); //443 (or 80) not allowed on Linux unless run as root
        server.setConnectors(new Connector[] {serverconn});
        
        //start	        
        server.start();
        logger.info("REST interface started on "+server.getURI());
        server.join();
		
	}
	catch(Exception ex){
		ex.printStackTrace();
		logger.severe("Nadia: failed to start Jetty: "+ex.getMessage());
		server.destroy();
	}
}
 
Example 10
Source File: EmbeddedJettyServer.java    From Alpine with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final CliArgs cliArgs = new CliArgs(args);
    final String contextPath = cliArgs.switchValue("-context", "/");
    final String host = cliArgs.switchValue("-host", "0.0.0.0");
    final int port = cliArgs.switchIntegerValue("-port", 8080);

    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    final Server server = new Server();
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer( new org.eclipse.jetty.server.ForwardedRequestCustomizer() ); // Add support for X-Forwarded headers

    final HttpConnectionFactory connectionFactory = new HttpConnectionFactory( httpConfig );
    final ServerConnector connector = new ServerConnector(server, connectionFactory);
    connector.setHost(host);
    connector.setPort(port);
    disableServerVersionHeader(connector);
    server.setConnectors(new Connector[]{connector});

    final WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath(contextPath);
    context.setErrorHandler(new ErrorHandler());
    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*taglibs.*\\.jar$");
    context.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
    context.addBean(new ServletContainerInitializersStarter(context), true);

    // Prevent loading of logging classes
    context.getSystemClasspathPattern().add("org.apache.log4j.");
    context.getSystemClasspathPattern().add("org.slf4j.");
    context.getSystemClasspathPattern().add("org.apache.commons.logging.");

    final ProtectionDomain protectionDomain = EmbeddedJettyServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    context.setWar(location.toExternalForm());

    server.setHandler(context);
    server.addBean(new ErrorHandler());
    try {
        server.start();
        addJettyShutdownHook(server);
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
 
Example 11
Source File: HttpServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static void start() {
   try {
      DefaultContext main = new DefaultContext();
      String base = StorageService.getFile("agent:///www").getPath();
      
      org.eclipse.jetty.servlet.DefaultServlet defServlet = new org.eclipse.jetty.servlet.DefaultServlet();
      main.addServlet("/", defServlet, ImmutableMap.<String,String>of(
         "dirAllowed", "false",
         "welcomeServlets", "true",
         "resourceBase", base
      ));

      main.context.setWelcomeFiles(new String[] { "index.html" });
      main.addServlet("/index.html", new DefaultServlet());
      if (SpyService.INSTANCE.isActive()) {
      	main.addServlet("/spy/api", new SpyApiServlet());
      	main.addServlet("/spy", new SpyServlet());
      }

      main.context.setErrorHandler(new ErrorPage());

      ContextHandlerCollection ctxs = new ContextHandlerCollection();
      ctxs.addHandler(main.context);

      ThreadFactory tf = new HttpThreadFactory();
      BlockingQueue<Runnable> queue = new SynchronousQueue<>();
      ThreadPoolExecutor exec = new ThreadPoolExecutor(4,16,60,TimeUnit.SECONDS,queue,tf);

      Server srv = new Server(new ExecutorThreadPool(exec));
      srv.setHandler(ctxs);
      srv.setStopAtShutdown(false);
      srv.setStopTimeout(500);

      Map<String,Map<Integer,Connector>> conns = new LinkedHashMap<>();
      Map<Integer,Connector> dconns = new LinkedHashMap<>();
      conns.put("", dconns);

      DefaultConnector conn = new DefaultConnector(srv,PORT);
      srv.setConnectors(new ServerConnector[] { conn.connector });
      dconns.put(PORT, conn);

      mainConnector = conn;
      connectors = conns;

      mainContext = main;
      contexts = ctxs;

      server = srv;
      srv.start();
   } catch (Exception ex) {
      log.warn("failed to start http server:", ex);
   }
}
 
Example 12
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors, sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(), new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException("HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}
 
Example 13
Source File: SSLUtilsTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
private static JettyServer createHttpsJettyServer(boolean clientAuth) throws IOException {
    Server server = new Server();
    HttpConfiguration https_config = new HttpConfiguration();
    https_config.setSecureScheme("https");
    int port;
    try (ServerSocket socket = new ServerSocket(0)) {
        port = socket.getLocalPort();
    }
    https_config.setSecurePort(port);
    https_config.setOutputBufferSize(32768);

    SslContextFactory sslContextFactory = new SslContextFactory();
    File keystoreFile = new File(DEFAULT_SERVER_KEY_STORE);
    if (!keystoreFile.exists()) {
        throw new FileNotFoundException();
    }

    String trustStorePath = DEFAULT_CA_TRUST_STORE;
    File trustStoreFile = new File(trustStorePath);
    if (!trustStoreFile.exists()) {
        throw new FileNotFoundException();
    }

    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setTrustStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
    sslContextFactory.setKeyStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setKeyStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setProtocol(DEFAULT_SSL_PROTOCOL);
    sslContextFactory.setNeedClientAuth(clientAuth);

    ServerConnector https = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
    https.setPort(port);
    https.setIdleTimeout(500000);
    server.setConnectors(new Connector[] { https });
    HandlerList handlers = new HandlerList();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource("."));
    handlers.setHandlers(new Handler[]
            { resourceHandler, new DefaultHandler() });
    server.setHandler(handlers);
    return new JettyServer(server, port);
}
 
Example 14
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
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: RESTApp.java    From account-provisioning-for-google-apps with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the Jetty server.
 */
private void initJettyServer() {
  logger.log(Level.INFO, "Initialzing Jetty server...");
  int port;
  if (customPort == null) {
    logger.log(Level.INFO, "Initialzing server in default port: " + PORT_DEFAULT_VALUE);
    port = PORT_DEFAULT_VALUE;
  } else {
    logger.log(Level.INFO, "Initialzing server in custom port: " + customPort.toString());
    port = customPort;
  }
  jettyServer = new Server(port);

  ConfigData config = ProvisioningApp.getInstance().getContext().getConfig();
  if (config.getUseSSL()) {
    HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getKeyStorePath());
    sslContextFactory.setKeyStorePassword(config.getKeyStorePassword());
    sslContextFactory.setKeyManagerPassword(config.getKeyManagerPassword());

    ServerConnector sslConnector =
        new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HTTP_VERSION), new HttpConnectionFactory(
                https));
    sslConnector.setPort(port);

    jettyServer.setConnectors(new Connector[] {sslConnector});
  }

  jettyServer.setHandler(servletContext);

  try {
    jettyServer.start();
    jettyServer.join();
  } catch (Throwable e) {
    logger.log(Level.SEVERE, "Exception during server initialization", e);
    jettyServer.destroy();
  }
}
 
Example 17
Source File: Main.java    From dexter with Apache License 2.0 4 votes vote down vote up
private void start() {
	// Start a Jetty server with some sensible(?) defaults
	try {
		Server srv = new Server();
		srv.setStopAtShutdown(true);

		// Allow 5 seconds to complete.
		// Adjust this to fit with your own webapp needs.
		// Remove this if you wish to shut down immediately (i.e. kill <pid>
		// or Ctrl+C).
		srv.setGracefulShutdown(5000);

		// Increase thread pool
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMaxThreads(100);
		srv.setThreadPool(threadPool);

		// Ensure using the non-blocking connector (NIO)
		Connector connector = new SelectChannelConnector();
		connector.setPort(port);
		connector.setMaxIdleTime(30000);
		srv.setConnectors(new Connector[] { connector });

		// Get the war-file
		ProtectionDomain protectionDomain = Main.class
				.getProtectionDomain();
		String warFile = protectionDomain.getCodeSource().getLocation()
				.toExternalForm();
		String currentDir = new File(protectionDomain.getCodeSource()
				.getLocation().getPath()).getParent();

		// Handle signout/signin in BigIP-cluster

		// Add the warFile (this jar)
		WebAppContext context = new WebAppContext(warFile, contextPath);
		context.setServer(srv);
		resetTempDirectory(context, currentDir);

		// Add the handlers
		HandlerList handlers = new HandlerList();
		handlers.addHandler(context);
		handlers.addHandler(new ShutdownHandler(srv, context, secret));
		handlers.addHandler(new BigIPNodeHandler(secret));
		srv.setHandler(handlers);

		srv.start();
		srv.join();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 18
Source File: JettyServer.java    From tutorials with MIT License 4 votes vote down vote up
void start() throws Exception {

        int maxThreads = 100;
        int minThreads = 10;
        int idleTimeout = 120;

        QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);

        server = new Server(threadPool);
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8090);
        server.setConnectors(new Connector[] { connector });

        ServletHandler servletHandler = new ServletHandler();
        server.setHandler(servletHandler);

        servletHandler.addServletWithMapping(BlockingServlet.class, "/status");
        servletHandler.addServletWithMapping(AsyncServlet.class, "/heavy/async");

        server.start();

    }
 
Example 19
Source File: TestSdcIpcTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void testHttps(boolean hostVerification) throws Exception {
  String hostname = (hostVerification) ? TLSTestUtils.getHostname() : "localhost";

  File testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
  Assert.assertTrue(testDir.mkdirs());
  KeyPair keyPair = TLSTestUtils.generateKeyPair();
  Certificate cert = TLSTestUtils.generateCertificate("CN=" + hostname, keyPair, 30);
  File keyStore = new File(testDir, "keystore.jks");
  TLSTestUtils.createKeyStore(keyStore.toString(), "keystore", "web", keyPair.getPrivate(), cert);
  File trustStore = new File(testDir, "truststore.jks");
  TLSTestUtils.createTrustStore(trustStore.toString(), "truststore", "web", cert);

  Server server = new Server(0);
  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new ReceiverServlet()), Constants.IPC_PATH);
  context.setContextPath("/");
  server.setHandler(context);

  //Create a connector for HTTPS
  HttpConfiguration httpsConf = new HttpConfiguration();
  httpsConf.addCustomizer(new SecureRequestCustomizer());
  SslContextFactory sslContextFactory = new SslContextFactory();
  sslContextFactory.setKeyStorePath(keyStore.getPath());
  sslContextFactory.setKeyStorePassword("keystore");
  sslContextFactory.setKeyManagerPassword("keystore");
  ServerConnector httpsConnector = new ServerConnector(server,
                                                       new SslConnectionFactory(sslContextFactory, "http/1.1"),
                                                       new HttpConnectionFactory(httpsConf));
  httpsConnector.setPort(0);
  server.setConnectors(new Connector[]{httpsConnector});

  try {
    server.start();

    Configs config = new Configs();
    config.appId = () -> "appId";
    config.connectionTimeOutMs = 1000;
    config.readTimeOutMs = 2000;
    config.hostPorts = ImmutableList.of(hostname + ":" + server.getURI().getPort());
    config.retriesPerBatch = 2;
    config.tlsConfigBean.tlsEnabled = true;
    config.tlsConfigBean.trustStoreFilePath = trustStore.getName();
    config.tlsConfigBean.trustStorePassword = () -> "truststore";
    config.hostVerification = hostVerification;

    SdcIpcTarget target = new SdcIpcTarget(config);

    TargetRunner runner = new TargetRunner.Builder(SdcIpcDTarget.class, target)
        .setOnRecordError(OnRecordError.TO_ERROR).setResourcesDir(testDir.toString()).build();
    try {
      runner.runInit();
      List<Record> records = ImmutableList.of(RecordCreator.create(), RecordCreator.create());
      runner.runWrite(records);
      Assert.assertTrue(runner.getErrorRecords().isEmpty());
      Assert.assertTrue(runner.getErrors().isEmpty());
    } finally {
      runner.runDestroy();
    }

  } finally {
    server.stop();
  }
}
 
Example 20
Source File: Launcher.java    From EchoQuery with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Configures and sets up a Jetty server.
 * @param args
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {
  // Configure logging to output to the console with default level of
  // INFO.
  BasicConfigurator.configure();

  Server server = new Server();

  // Configure SSL from system properties.
  SslConnectionFactory sslConnectionFactory = new SslConnectionFactory();
  SslContextFactory sslContextFactory =
      sslConnectionFactory.getSslContextFactory();
  sslContextFactory.setKeyStorePath(
      System.getProperty("javax.net.ssl.keyStore"));
  sslContextFactory.setKeyStorePassword(
      System.getProperty("javax.net.ssl.keyStorePassword"));
  sslContextFactory.setIncludeCipherSuites(Sdk.SUPPORTED_CIPHER_SUITES);

  // Configure HTTPS server.
  HttpConfiguration httpConf = new HttpConfiguration();
  httpConf.setSecurePort(PORT);
  httpConf.setSecureScheme(HTTPS_SCHEME);
  httpConf.addCustomizer(new SecureRequestCustomizer());
  HttpConnectionFactory httpConnectionFactory =
      new HttpConnectionFactory(httpConf);

  // Set up the servlets.
  ServerConnector serverConnector = new ServerConnector(
      server, sslConnectionFactory, httpConnectionFactory);
  serverConnector.setPort(PORT);

  Connector[] connectors = new Connector[1];
  connectors[0] = serverConnector;
  server.setConnectors(connectors);

  ServletContextHandler context =
      new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  server.setHandler(context);
  context.addServlet(new ServletHolder(
      createServlet(new EchoQuerySpeechlet())), "/echoquery");
  server.start();
  server.join();
}