Java Code Examples for org.eclipse.jetty.server.HttpConfiguration#setRequestHeaderSize()

The following examples show how to use org.eclipse.jetty.server.HttpConfiguration#setRequestHeaderSize() . 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: JettyServerWrapper.java    From cougar with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the request and header buffer sizex if they are not zero
 */
private void setBufferSizes(HttpConfiguration buffers) {
    if (requestHeaderSize > 0) {
        LOGGER.info("Request header size set to {} for {}", requestHeaderSize, buffers.getClass().getCanonicalName());
        buffers.setRequestHeaderSize(requestHeaderSize);
    }

    if (responseBufferSize > 0) {
        LOGGER.info("Response buffer size set to {} for {}", responseBufferSize, buffers.getClass().getCanonicalName());
        buffers.setOutputBufferSize(responseBufferSize);
    }
    if (responseHeaderSize > 0) {
        LOGGER.info("Response header size set to {} for {}", responseHeaderSize, buffers.getClass().getCanonicalName());
        buffers.setResponseHeaderSize(responseHeaderSize);
    }
}
 
Example 2
Source File: JettyServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void configureConnectors(final Server server) throws ServerConfigurationException {
    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    final int headerSize = DataUnit.parseDataSize(props.getWebMaxHeaderSize(), DataUnit.B).intValue();
    httpConfiguration.setRequestHeaderSize(headerSize);
    httpConfiguration.setResponseHeaderSize(headerSize);
    httpConfiguration.setSendServerVersion(props.shouldSendServerVersion());

    // Check if both HTTP and HTTPS connectors are configured and fail if both are configured
    if (bothHttpAndHttpsConnectorsConfigured(props)) {
        logger.error("NiFi only supports one mode of HTTP or HTTPS operation, not both simultaneously. " +
                "Check the nifi.properties file and ensure that either the HTTP hostname and port or the HTTPS hostname and port are empty");
        startUpFailure(new IllegalStateException("Only one of the HTTP and HTTPS connectors can be configured at one time"));
    }

    if (props.getSslPort() != null) {
        configureHttpsConnector(server, httpConfiguration);
    } else if (props.getPort() != null) {
        configureHttpConnector(server, httpConfiguration);
    } else {
        logger.error("Neither the HTTP nor HTTPS connector was configured in nifi.properties");
        startUpFailure(new IllegalStateException("Must configure HTTP or HTTPS connector"));
    }
}
 
Example 3
Source File: JettySeverTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addHttpsConnector(Server server, Integer port) throws Exception {
	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(Config.sslKeyStore().getAbsolutePath());
	sslContextFactory.setKeyStorePassword(Config.token().getSslKeyStorePassword());
	sslContextFactory.setKeyManagerPassword(Config.token().getSslKeyManagerPassword());
	sslContextFactory.setTrustAll(true);
	HttpConfiguration config = new HttpConfiguration();
	config.setSecureScheme("https");
	config.setOutputBufferSize(32768);
	config.setRequestHeaderSize(8192 * 2);
	config.setResponseHeaderSize(8192 * 2);
	config.setSendServerVersion(true);
	config.setSendDateHeader(false);
	ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
			new HttpConnectionFactory(config));
	sslConnector.setPort(port);
	server.addConnector(sslConnector);
}
 
Example 4
Source File: AthenzJettyContainer.java    From athenz with Apache License 2.0 6 votes vote down vote up
public HttpConfiguration newHttpConfiguration() {

        // HTTP Configuration
        
        boolean sendServerVersion = Boolean.parseBoolean(
                System.getProperty(AthenzConsts.ATHENZ_PROP_SEND_SERVER_VERSION, "false"));
        boolean sendDateHeader = Boolean.parseBoolean(
                System.getProperty(AthenzConsts.ATHENZ_PROP_SEND_DATE_HEADER, "false"));
        int outputBufferSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_OUTPUT_BUFFER_SIZE, "32768"));
        int requestHeaderSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_REQUEST_HEADER_SIZE, "8192"));
        int responseHeaderSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_RESPONSE_HEADER_SIZE, "8192"));
        
        HttpConfiguration httpConfig = new HttpConfiguration();
        
        httpConfig.setOutputBufferSize(outputBufferSize);
        httpConfig.setRequestHeaderSize(requestHeaderSize);
        httpConfig.setResponseHeaderSize(responseHeaderSize);
        httpConfig.setSendServerVersion(sendServerVersion);
        httpConfig.setSendDateHeader(sendDateHeader);

        return httpConfig;
    }
 
Example 5
Source File: EmbeddedServer.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
protected Connector getConnector(int port) throws IOException {
    HttpConfiguration http_config = new HttpConfiguration();
    // this is to enable large header sizes when Kerberos is enabled with AD
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();;
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setRequestHeaderSize(bufferSize);

    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(http_config));
    connector.setPort(port);
    connector.setHost("0.0.0.0");
    return connector;
}
 
Example 6
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void configureProxiedConnector(HttpConfiguration httpConfig) {
     // Check to see if we are deployed behind a proxy
     // Refer to http://eclipse.org/jetty/documentation/current/configuring-connectors.html
     if (isXFFEnabled()) {
         ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer();
         // default: "X-Forwarded-For"
         String forwardedForHeader = getXFFHeader();
         if (forwardedForHeader != null) {
             customizer.setForwardedForHeader(forwardedForHeader);
         }
         // default: "X-Forwarded-Server"
         String forwardedServerHeader = getXFFServerHeader();
         if (forwardedServerHeader != null) {
             customizer.setForwardedServerHeader(forwardedServerHeader);
         }
         // default: "X-Forwarded-Host"
         String forwardedHostHeader = getXFFHostHeader();
         if (forwardedHostHeader != null) {
             customizer.setForwardedHostHeader(forwardedHostHeader);
         }
         // default: none
         String hostName = getXFFHostName();
         if (hostName != null) {
             customizer.setHostHeader(hostName);
         }

         httpConfig.addCustomizer(customizer);
     }
     httpConfig.setRequestHeaderSize(JiveGlobals.getIntProperty(HTTP_BIND_REQUEST_HEADER_SIZE, HTTP_BIND_REQUEST_HEADER_SIZE_DEFAULT));
}
 
Example 7
Source File: JettyConfigurationHelper.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
static void configureHttp( HttpConfiguration httpConfig, JettyConfiguration config )
{
    // Date header
    Boolean sendDateHeader = config.sendDateHeader().get();
    if( sendDateHeader != null )
    {
        httpConfig.setSendDateHeader( sendDateHeader );
    }

    // Server version
    Boolean sendServerVersion = config.sendServerVersion().get();
    if( sendServerVersion != null )
    {
        httpConfig.setSendServerVersion( sendServerVersion );
    }

    // Header sizes
    Integer requestHeaderSize = config.requestHeaderSize().get();
    if( requestHeaderSize != null )
    {
        httpConfig.setRequestHeaderSize( requestHeaderSize );
    }
    Integer responseHeaderSize = config.responseHeaderSize().get();
    if( responseHeaderSize != null )
    {
        httpConfig.setResponseHeaderSize( responseHeaderSize );
    }

    // Buffer sizes
    Integer responseBufferSize = config.responseBufferSize().get();
    if( responseBufferSize != null )
    {
        httpConfig.setOutputBufferSize( responseBufferSize );
    }

}
 
Example 8
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> {
        Thread t = new Thread(r);
        t.setName("Jetty Thread Pool");
        return t;
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(ADDRESS);
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOG.info("Running on {}", getURL());

    return context.getServletContext();
}
 
Example 9
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example 10
Source File: ConnectorFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
private HttpConnectionFactory newHttpConnectionFactory() {
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSendDateHeader(true);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendXPoweredBy(false);
    httpConfig.setHeaderCacheSize(connectorConfig.headerCacheSize());
    httpConfig.setOutputBufferSize(connectorConfig.outputBufferSize());
    httpConfig.setRequestHeaderSize(connectorConfig.requestHeaderSize());
    httpConfig.setResponseHeaderSize(connectorConfig.responseHeaderSize());
    if (connectorConfig.ssl().enabled() || TransportSecurityUtils.isTransportSecurityEnabled()) { // TODO Cleanup once mixed mode is gone
        httpConfig.addCustomizer(new SecureRequestCustomizer());
    }
    return new HttpConnectionFactory(httpConfig);
}
 
Example 11
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(HOST);
    if (System.getProperty("port")!=null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example 12
Source File: JettySeverTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static void addHttpConnector(Server server, Integer port) throws Exception {
	HttpConfiguration config = new HttpConfiguration();
	config.setOutputBufferSize(32768);
	config.setRequestHeaderSize(8192 * 2);
	config.setResponseHeaderSize(8192 * 2);
	config.setSendServerVersion(true);
	config.setSendDateHeader(false);
	ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config));
	http.setIdleTimeout(30000);
	http.setPort(port);
	server.addConnector(http);
}
 
Example 13
Source File: EmbeddedServer.java    From atlas with Apache License 2.0 5 votes vote down vote up
protected Connector getConnector(String host, int port) throws IOException {
    HttpConfiguration http_config = new HttpConfiguration();
    // this is to enable large header sizes when Kerberos is enabled with AD
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();;
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setRequestHeaderSize(bufferSize);

    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(http_config));
    connector.setPort(port);
    connector.setHost(host);
    return connector;
}
 
Example 14
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath              the context path at which to put Jenkins
 * @param portSetter               the port on which the server runs will be set using this function
 * @param classLoader              the class loader for the {@link WebAppContext}
 * @param localPort                port on which the server runs
 * @param loginServiceSupplier     configures the {@link LoginService} for the instance
 * @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier,
                                                                     @CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
        throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JenkinsRule)");
    Server server = new Server(qtp);

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(classLoader);
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");
    if (System.getProperty("port") != null) {
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else if (localPort != 0) {
        connector.setPort(localPort);
    }

    server.addConnector(connector);
    if (contextAndServerConsumer != null) {
        contextAndServerConsumer.accept(context, server);
    }
    server.start();

    portSetter.accept(connector.getLocalPort());

    ServletContext servletContext =  context.getServletContext();
    return new ImmutablePair<>(server, servletContext);
}
 
Example 15
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public void run() {
    log.info("Starting jdbc-bridge");

    JdbcDriverLoader.load(config.getDriverPath());

    BridgeConnectionManager manager = new BridgeConnectionManager();
    if (null != config.getConnectionFile()) {
        manager.load(config.getConnectionFile());
    }

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new QueryHandlerServlet(manager)), "/");
    handler.addServletWithMapping(new ServletHolder(new ColumnsInfoServlet(manager, new ClickHouseConverter())), "/columns_info");
    handler.addServletWithMapping(new ServletHolder(new IdentifierQuoteServlet(manager)), "/identifier_quote");
    handler.addServletWithMapping(new ServletHolder(new PingHandlerServlet()), "/ping");
    handler.addFilterWithMapping(RequestLogger.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    InetSocketAddress address = new InetSocketAddress(config.getListenHost(), config.getHttpPort());
    log.info("Will bind to {}", address);

    // this tricks are don in order to get good thread name in logs :(
    QueuedThreadPool pool = new QueuedThreadPool(1024, 10); // @todo make configurable?
    pool.setName("HTTP Handler");
    Server jettyServer = new Server(pool);
    ServerConnector connector = new ServerConnector(jettyServer);

    // @todo a temporary solution for dealing with too long URI for some endpoints
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(24 * 1024);
    HttpConnectionFactory factory = new HttpConnectionFactory(httpConfiguration);
    connector.setConnectionFactories(Collections.singleton(factory));

    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    jettyServer.setHandler(handler);
    jettyServer.setErrorHandler(new ErrorHandler() {
        @Override
        protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write(message);
        }
    });

    try {
        log.info("Starting server");
        jettyServer.start();
        log.info("Server is ready to accept connections");
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}
 
Example 16
Source File: SecureEmbeddedServer.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
protected Connector getConnector(int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
            System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
    sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
    sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
    sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
            System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
    sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
    sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));

    List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
    sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
    sslContextFactory.setRenegotiationAllowed(false);

    String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
            config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
    if (excludedProtocols != null && excludedProtocols.length > 0) {
        sslContextFactory.addExcludeProtocols(excludedProtocols);
    }

    // SSL HTTP Configuration
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
    http_config.setSecurePort(port);
    http_config.setRequestHeaderSize(bufferSize);
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);

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

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    return sslConnector;
}
 
Example 17
Source File: Start.java    From etcd-viewer with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int timeout = (int) Duration.ONE_HOUR.getMilliseconds();

    System.setProperty(WICKET_CFG, CfgType.development.toString());

    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);

    // Set some timeout options to make debugging easier.
    connector.setIdleTimeout(timeout);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.addConnector(connector);

    Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
        // if a keystore for a SSL certificate is available, start a SSL
        // connector on port 8443.
        // By default, the quickstart comes with a Apache Wicket Quickstart
        // Certificate that expires about half way september 2021. Do not
        // use this certificate anywhere important as the passwords are
        // available in the source.

        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStoreResource(keystore);
        sslContextFactory.setKeyStorePassword("wicket");
        sslContextFactory.setTrustStoreResource(keystore);
        sslContextFactory.setKeyManagerPassword("wicket");

        // HTTP Configuration
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(8443);
        httpConfig.setOutputBufferSize(32768);
        httpConfig.setRequestHeaderSize(8192);
        httpConfig.setResponseHeaderSize(8192);
        httpConfig.setSendServerVersion(true);
        httpConfig.setSendDateHeader(false);

        // SSL HTTP Configuration
        HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
        httpsConfig.addCustomizer(new SecureRequestCustomizer());

        // SSL Connector
        ServerConnector sslConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(8443);

        server.addConnector(sslConnector);

        System.out.println("SSL access to the quickstart has been enabled on port 8443");
        System.out.println("You can access the application using SSL on https://localhost:8443");
        System.out.println();
    }

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // START JMX SERVER
    // 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();
        System.in.read();
        System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
        server.stop();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 18
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    System.err.println("Listening on host address: " + HOST);
    connector.setHost(HOST);

    if (System.getProperty("port")!=null) {
        LOGGER.info("Overriding port using system property: " + System.getProperty("port"));
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else {
        if (port != null) {
            connector.setPort(port);
        }
    }

    server.addConnector(connector);
    try {
        server.start();
    } catch (BindException e) {
        throw new BindException(String.format("Error binding to %s:%d %s", connector.getHost(), connector.getPort(),
                e.getMessage()));
    }

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example 19
Source File: SecureEmbeddedServer.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
protected Connector getConnector(String host, int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    SSLContext sslContext = getSSLContext();
    if (sslContext != null) {
        SSLContext.setDefault(sslContext);
    }

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
            System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
    sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
    sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
    sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
            System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
    sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
    sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));

    List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
    sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
    sslContextFactory.setRenegotiationAllowed(false);

    String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
            config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
    if (excludedProtocols != null && excludedProtocols.length > 0) {
        sslContextFactory.addExcludeProtocols(excludedProtocols);
    }

    // SSL HTTP Configuration
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
    http_config.setSecurePort(port);
    http_config.setRequestHeaderSize(bufferSize);
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);

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

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    return sslConnector;
}
 
Example 20
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();
}