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

The following examples show how to use org.eclipse.jetty.server.Server#addBean() . 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: HttpProtocolServer.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private void addBasicAuth(Server server) {
    
    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    security.setAuthenticator(new BasicAuthenticator());

    Constraint constraint = new Constraint();
    constraint.setAuthenticate(true);
    constraint.setRoles(ROLES);
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    security.setConstraintMappings(Collections.singletonList(mapping));

    HashLoginService loginService = new HashLoginService();
    loginService.setUserStore(buildUserStore());
    server.addBean(loginService);
    security.setLoginService(loginService);

    security.setHandler(server.getHandler());
    server.setHandler(security);
}
 
Example 2
Source File: JettyServer.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Enabled JMX reporting:
 * https://docs.newrelic.com/docs/agents/java-agent/troubleshooting/application-server-jmx-setup
 * https://www.eclipse.org/jetty/documentation/current/jmx-chapter
 */
private void configureMBeanContainer(final Server server){
    final MBeanContainer mbContainer = new MBeanContainer(getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(getLog());
}
 
Example 3
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureDigestBasic(Configuration conf, Server server, String mode) {
  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);

  ConstraintSecurityHandler security = new ConstraintSecurityHandler();
  switch (mode) {
    case "digest":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new DigestAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    case "basic":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new BasicAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    default:
      // no action
      break;
  }
  security.setLoginService(loginService);
  return security;
}
 
Example 4
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureForm(Configuration conf, Server server, String mode) {
  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);
  securityHandler.setLoginService(loginService);

  FormAuthenticator authenticator = new FormAuthenticator("/login.html", "/login.html?error=true", true);
  securityHandler.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(authenticator, runtimeInfo, conf)));
  return securityHandler;
}
 
Example 5
Source File: BaleenWebApi.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void configureServer(Server server, WebAuthConfig authConfig, Handler servletHandler)
    throws BaleenException {
  Handler serverHandler;

  if (authConfig == null || authConfig.getType() == AuthType.NONE) {
    LOGGER.warn("No security applied to API");
    // No security
    serverHandler = servletHandler;
  } else if (authConfig.getType() == AuthType.BASIC) {
    // Basic authentication
    LOGGER.info("Using Basic HTTP authentication for API");

    HashLoginService loginService = new HashLoginService(authConfig.getName());

    UserStore userStore = new UserStore();
    for (WebUser user : authConfig.getUsers()) {
      Credential credential = Credential.getCredential(user.getPassword());
      userStore.addUser(user.getUsername(), credential, user.getRolesAsArray());
    }
    loginService.setUserStore(userStore);
    server.addBean(loginService);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

    securityHandler.setHandler(servletHandler);
    securityHandler.setConstraintMappings(constraintMappings);
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setLoginService(loginService);

    serverHandler = securityHandler;
  } else {
    throw new InvalidParameterException("Configuration of authentication failed");
  }

  server.setHandler(serverHandler);
}
 
Example 6
Source File: ClientJettyStreamITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        fail("Failed to start server: " + e);
    }
}
 
Example 7
Source File: JavaxServletSyncServerITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() throws Exception {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    server.start();
}
 
Example 8
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void setupJmx(Server server, ServerConfig serverConfig) {
    if (serverConfig.jmx().enabled()) {
        System.setProperty("java.rmi.server.hostname", "localhost");
        server.addBean(
                new MBeanContainer(ManagementFactory.getPlatformMBeanServer()));
        server.addBean(
                new ConnectorServer(
                        createJmxLoopbackOnlyServiceUrl(serverConfig.jmx().listenPort()),
                        "org.eclipse.jetty.jmx:name=rmiconnectorserver"));
    }
}
 
Example 9
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 5 votes vote down vote up
@Override
protected ConstraintSecurityHandler configureBasicAuthentication(Server server,
                                                                 AvaticaServerConfiguration config) {
    LOG.info("Configuring basic auth");
    final String[] allowedRoles = config.getAllowedRoles();
    final String realm = config.getHashLoginServiceRealm();

    JAASLoginService loginService = new JAASLoginService(realm);
    server.addBean(loginService);

    return configureCommonAuthentication(Constraint.__BASIC_AUTH,
        allowedRoles, new BasicAuthenticator(), null, loginService);
}
 
Example 10
Source File: HttpServer.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected ConstraintSecurityHandler configureDigestAuthentication(Server server,
    AvaticaServerConfiguration config) {
  final String[] allowedRoles = config.getAllowedRoles();
  final String realm = config.getHashLoginServiceRealm();
  final String loginServiceProperties = config.getHashLoginServiceProperties();

  HashLoginService loginService = new HashLoginService(realm, loginServiceProperties);
  server.addBean(loginService);

  return configureCommonAuthentication(Constraint.__DIGEST_AUTH,
      allowedRoles, new DigestAuthenticator(), null, loginService);
}
 
Example 11
Source File: HttpServer.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
protected ConstraintSecurityHandler configureBasicAuthentication(Server server,
    AvaticaServerConfiguration config) {
  final String[] allowedRoles = config.getAllowedRoles();
  final String realm = config.getHashLoginServiceRealm();
  final String loginServiceProperties = config.getHashLoginServiceProperties();

  HashLoginService loginService = new HashLoginService(realm, loginServiceProperties);
  server.addBean(loginService);

  return configureCommonAuthentication(Constraint.__BASIC_AUTH,
      allowedRoles, new BasicAuthenticator(), null, loginService);
}
 
Example 12
Source File: JettyComposer.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
public static void compose(Server server) {
    //Servlets + Guice
    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");

    //JMX stuff...
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
}
 
Example 13
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 14
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example 15
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 16
Source File: ConfirmedHttpApiService.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void start() {
    try {
        server = new Server(port);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        // same as Start
        context.addServlet(new ServletHolder(accountOnConfirmedServlet), "/walletconfirmed/getaccount");
        context.addServlet(new ServletHolder(listWitnessesOnConfirmedServlet),
                "/walletconfirmed/listwitnesses");
        context.addServlet(new ServletHolder(getAssetIssueListOnConfirmedServlet),
                "/walletconfirmed/getassetissuelist");
        context.addServlet(new ServletHolder(getPaginatedAssetIssueListOnConfirmedServlet),
                "/walletconfirmed/getpaginatedassetissuelist");
        context.addServlet(new ServletHolder(getAssetIssueByNameOnConfirmedServlet),
                "/walletconfirmed/getassetissuebyname");
        context.addServlet(new ServletHolder(getAssetIssueByIdOnConfirmedServlet),
                "/walletconfirmed/getassetissuebyid");
        context.addServlet(new ServletHolder(getAssetIssueListByNameOnConfirmedServlet),
                "/walletconfirmed/getassetissuelistbyname");
        context.addServlet(new ServletHolder(getNowBlockOnConfirmedServlet),
                "/walletconfirmed/getnowblock");
        context.addServlet(new ServletHolder(getBlockByNumOnConfirmedServlet),
                "/walletconfirmed/getblockbynum");
        context.addServlet(new ServletHolder(getDelegatedResourceOnConfirmedServlet),
                "/walletconfirmed/getdelegatedresource");
        context.addServlet(new ServletHolder(getDelegatedResourceAccountIndexOnConfirmedServlet),
                "/walletconfirmed/getdelegatedresourceaccountindex");
        context.addServlet(new ServletHolder(getExchangeByIdOnConfirmedServlet),
                "/walletconfirmed/getexchangebyid");
        context.addServlet(new ServletHolder(listExchangesOnConfirmedServlet),
                "/walletconfirmed/listexchanges");
        context.addServlet(new ServletHolder(getAccountByIdOnConfirmedServlet),
                "/walletconfirmed/getaccountbyid");
        context.addServlet(new ServletHolder(getBlockByIdOnConfirmedServlet),
                "/walletconfirmed/getblockbyid");
        context.addServlet(new ServletHolder(getBlockByLimitNextOnConfirmedServlet),
                "/walletconfirmed/getblockbylimitnext");
        context.addServlet(new ServletHolder(getBlockByLatestNumOnConfirmedServlet),
                "/walletconfirmed/getblockbylatestnum");
        // only for ConfirmedNode
        context.addServlet(new ServletHolder(getTransactionByIdOnConfirmedServlet),
                "/walletconfirmed/gettransactionbyid");
        context.addServlet(new ServletHolder(getTransactionInfoByIdOnConfirmedServlet),
                "/walletconfirmed/gettransactioninfobyid");

        context.addServlet(new ServletHolder(getTransactionCountByBlockNumOnConfirmedServlet),
                "/walletconfirmed/gettransactioncountbyblocknum");

        context.addServlet(new ServletHolder(getNodeInfoOnConfirmedServlet), "/wallet/getnodeinfo");
        int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber();
        if (maxHttpConnectNumber > 0) {
            server.addBean(new ConnectionLimit(maxHttpConnectNumber, server));
        }
        server.start();
    } catch (Exception e) {
        logger.debug("IOException: {}", e.getMessage());
    }
}
 
Example 17
Source File: CitizenIntelligenceAgencyServer.java    From cia with Apache License 2.0 4 votes vote down vote up
/**
 * Inits the.
 *
 * @throws Exception the exception
 */
public final void init() throws Exception {
	initialised = true;
	server = new Server();
	Security.addProvider(new BouncyCastleProvider());
	// Setup JMX
	final MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
	server.addBean(mbContainer);

	final org.eclipse.jetty.webapp.Configurations classlist = org.eclipse.jetty.webapp.Configurations.setServerDefault(server);
			
	final HttpConfiguration http_config = new HttpConfiguration();
	http_config.setSecureScheme("https");
	http_config.setSecurePort(28443);
	http_config.setSendServerVersion(false);

	final HttpConfiguration https_config = new HttpConfiguration(http_config);
	https_config.addCustomizer(new SecureRequestCustomizer());

	final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
	sslContextFactory.setKeyStoreType("PKCS12");
	sslContextFactory.setKeyStorePath("target/keystore.p12");
	sslContextFactory.setTrustStorePath("target/keystore.p12");
	sslContextFactory.setTrustStoreType("PKCS12");

	sslContextFactory.setKeyStorePassword("changeit");
	sslContextFactory.setTrustStorePassword("changeit");
	sslContextFactory.setKeyManagerPassword("changeit");
	sslContextFactory.setCertAlias("jetty");
	sslContextFactory.setIncludeCipherSuites("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
			"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
			"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
	sslContextFactory.setExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
	sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");

	final ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config),
			new HTTP2CServerConnectionFactory(https_config));
	sslConnector.setPort(PORT);

	server.setConnectors(new ServerConnector[] { sslConnector });
	final WebAppContext handler = new WebAppContext("src/main/webapp", "/");
	handler.setExtraClasspath("target/classes");
	handler.setParentLoaderPriority(true);
	handler.setConfigurationDiscovered(true);
	handler.setClassLoader(Thread.currentThread().getContextClassLoader());
	final HandlerList handlers = new HandlerList();

	handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });

	server.setHandler(handlers);
}
 
Example 18
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    // Thread pool
    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(10);
    threadPool.setMaxThreads(500);

    // Jetty Server
    server = new Server(threadPool);

    // Setup Scheduler
    server.addBean(new ScheduledExecutorScheduler());

    // Setup JMX
    final MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbeanContainer);

    // HTTP config
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer( new ForwardedRequestCustomizer() );
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(httpsPort);
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // HTTP Connector
    createHttpConnector(httpConfig);

    // Setup handlers
    Pair<SessionHandler,HandlerCollection> pair = createHandlers();
    server.setHandler(pair.second());

    // Extra config options
    server.setStopAtShutdown(true);

    // HTTPS Connector
    createHttpsConnector(httpConfig);

    server.start();
    // Must set the session timeout after the server has started
    pair.first().setMaxInactiveInterval(sessionTimeout * 60);
    server.join();
}
 
Example 19
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public void start() {

        if (!isHttpBindServiceEnabled()) {
            return;
        }

        // this is the number of threads allocated to each connector/port
        final int processingThreads = JiveGlobals.getIntProperty(HTTP_BIND_THREADS, HTTP_BIND_THREADS_DEFAULT);

        final QueuedThreadPool tp = new QueuedThreadPool(processingThreads);
        tp.setName("Jetty-QTP-BOSH");

        httpBindServer = new Server(tp);
        if (JMXManager.isEnabled()) {
            JMXManager jmx = JMXManager.getInstance();
            httpBindServer.addBean(jmx.getContainer());
        }

        final Connector httpConnector = createConnector( httpBindServer );
        final Connector httpsConnector = createSSLConnector( httpBindServer);

        if (httpConnector == null && httpsConnector == null) {
            httpBindServer = null;
            return;
        }
        if (httpConnector != null) {
            httpBindServer.addConnector(httpConnector);
        }
        if (httpsConnector != null) {
            httpBindServer.addConnector(httpsConnector);
        }

        httpBindServer.setHandler( handlerList );

        try {
            httpBindServer.start();
            handlerList.start();
            extensionHandlers.start();

            CertificateManager.addListener(this);

            Log.info("HTTP bind service started");
        }
        catch (Exception e) {
            Log.error("Error starting HTTP bind service", e);
        }

        if ( JiveGlobals.getBooleanProperty( "jetty.temp-file-toucher.enabled", true ) ) {
            tempFileToucherTask = new TempFileToucherTask( httpBindServer );
            final long period = JiveGlobals.getLongProperty( "jetty.temp-file-toucher.period", JiveConstants.DAY );
            TaskEngine.getInstance().schedule( tempFileToucherTask, period, period );
        }
    }
 
Example 20
Source File: BrooklynRestApiLauncher.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private static void initAuth(ManagementContext mgmt, Server server) {
    server.addBean(new BrooklynSecurityProviderFilterHelper());
}