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

The following examples show how to use org.eclipse.jetty.server.Server#addConnector() . 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: ChaosHttpProxy.java    From chaos-http-proxy with Apache License 2.0 6 votes vote down vote up
public ChaosHttpProxy(URI endpoint, ChaosConfig config)
        throws Exception {
    setChaosConfig(config);

    Supplier<Failure> supplier = new RandomFailureSupplier(
            config.getFailures());

    requireNonNull(endpoint);

    client = new HttpClient();

    server = new Server();
    HttpConnectionFactory httpConnectionFactory =
            new HttpConnectionFactory();
    // TODO: SSL
    ServerConnector connector = new ServerConnector(server,
            httpConnectionFactory);
    connector.setHost(endpoint.getHost());
    connector.setPort(endpoint.getPort());
    server.addConnector(connector);
    this.handler = new ChaosHttpProxyHandler(client, supplier);
    HandlerList handlers = new HandlerList();
    handlers.addHandler(new ChaosApiHandler(this, handler));
    handlers.addHandler(handler);
    server.setHandler(handlers);
}
 
Example 2
Source File: AbstractServletTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void initServerAndClient() throws Exception {

    // because we reuse the same classloader with different servlet context names
    // we need to explicitly reset the name cache to make service name detection work as expected
    ServletTransactionHelper.clearServiceNameCache();

    // server is not reused between tests as handler is provided from subclass
    // another alternative
    server = new Server();
    server.addConnector(new ServerConnector(server));
    ServletContextHandler handler = new ServletContextHandler();
    setUpHandler(handler);
    server.setHandler(handler);
    server.start();

    assertThat(getPort()).isPositive();

    httpClient = new OkHttpClient.Builder()
        // set to 0 for debugging
        .readTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(false)
        .build();
}
 
Example 3
Source File: TlsCertificateAuthorityService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols("TLSv1.2");
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example 4
Source File: JavaNetReverseProxy.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
public JavaNetReverseProxy(File cacheFolder) throws Exception {
    this.cacheFolder = cacheFolder;
    cacheFolder.mkdirs();
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JavaNetReverseProxy)");
    server = new Server(qtp);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    root.addServlet(new ServletHolder(this), "/");

    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
}
 
Example 5
Source File: TestServer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public TestServer() {
	System.clearProperty("DEBUG");

	jetty = new Server();

	ServerConnector conn = new ServerConnector(jetty);
	conn.setHost(HOST);
	conn.setPort(PORT);
	jetty.addConnector(conn);

	WebAppContext webapp = new WebAppContext();
	webapp.addSystemClass("org.slf4j.");
	webapp.addSystemClass("ch.qos.logback.");
	webapp.setContextPath(RDF4J_CONTEXT);
	// warPath configured in pom.xml maven-war-plugin configuration
	webapp.setWar("./target/rdf4j-server");
	jetty.setHandler(webapp);
}
 
Example 6
Source File: ProxyInboundClientTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  server = new Server();
  ServerConnector connector = new ServerConnector(server);
  server.addConnector(connector);

  Handler handler = new WebsocketEchoHandler();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(handler);
  server.setHandler(context);

  server.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/",host,port));
}
 
Example 7
Source File: ExampleKeePassHttpServer.java    From KeePassJava2 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        Server server = new Server();

        ServerConnector http = new ServerConnector(server);
        http.setHost("127.0.0.1");
        http.setPort(19455);
        http.setIdleTimeout(300000);
        server.addConnector(http);

        KdbxCreds creds = new KdbxCreds("123".getBytes());
        // create a database if we don't have one already
        if (Files.notExists(Paths.get(DEFAULT_DB_FILE))) {
            SimpleDatabase db = new SimpleDatabase();
            db.setName("HTTP Database");
            db.save(creds,new FileOutputStream(DEFAULT_DB_FILE));
        }

        DatabaseAdaptor adaptor = new DatabaseAdaptor.Default(new File(DEFAULT_DB_FILE), creds, new HexPwGenerator(10));
        server.setHandler(new KeePassHttpHandler(adaptor));

        server.start();
        server.join();
    }
 
Example 8
Source File: ConnectionDroppedTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example 9
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 10
Source File: ContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux API endpoint.
 * @param port where the service is available.
 * @return Jetty Server instance
 */
@Named("APIJettyServer")
@Provides
@Singleton
Server getAPIJettyServer(@Named("Api.service.port") int port,
						 @Named("APIResourceConfig")ResourceConfig resourceConfig,
						 @Named("Api.service.acceptors") int acceptorThreads,
						 @Named("Api.service.selectors") int selectorThreads,
						 @Named("Api.service.workers") int maxWorkerThreads,
						 ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
	JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
	provider.setMapper(objectMapper);
	resourceConfig.register(provider);
	QueuedThreadPool threadPool = new QueuedThreadPool();
	threadPool.setMaxThreads(maxWorkerThreads);
	Server server = new Server(threadPool);
	ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
	http.setPort(port);
	server.addConnector(http);
	ServletContextHandler context = new ServletContextHandler(server, "/*");
	ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
	context.addServlet(servlet, "/*");

	final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
	handler.setHandler(context);
	server.setHandler(handler);

	server.setStopAtShutdown(true);
	return server;
}
 
Example 11
Source File: WebServerConfig.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
private Server createJettyServer() {
  final Server server = new Server();

  for (ListenConfig listenConfig : listen)
    server.addConnector(listenConfig.createConnector(server));

  return server;
}
 
Example 12
Source File: JettyHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static void setAddressAndPort(final Server jetty,
    final String bindAddress, final int port) {
  SelectChannelConnector connector = new SelectChannelConnector();
  connector.setPort(port);

  if (!StringUtils.isBlank(bindAddress)) {
    connector.setHost(bindAddress);
  }
  jetty.addConnector(connector);
}
 
Example 13
Source File: JettyHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static void setAddressAndPort(final Server jetty,
    final String bindAddress, final int port) {
  SelectChannelConnector connector = new SelectChannelConnector();
  connector.setPort(port);

  if (!StringUtils.isBlank(bindAddress)) {
    connector.setHost(bindAddress);
  }
  jetty.addConnector(connector);
}
 
Example 14
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ks.jks"));

    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

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

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

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            if (request.getAttribute("javax.servlet.request.X509Certificate") != null) {
                clientSerial = ((java.security.cert.X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate"))[0].getSerialNumber();
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 15
Source File: Start.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
/**
 * Main function, starts the jetty server.
 *
 * @param args
 */
public static void main(String[] args)
{
	System.setProperty("wicket.configuration", "development");

	Server server = new Server();

	HttpConfiguration http_config = new HttpConfiguration();
	http_config.setSecureScheme("https");
	http_config.setSecurePort(8443);
	http_config.setOutputBufferSize(32768);

	ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
	http.setPort(8080);
	http.setIdleTimeout(1000 * 60 * 60);

	server.addConnector(http);

	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.setKeyManagerPassword("wicket");

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

		ServerConnector https = new ServerConnector(server, new SslConnectionFactory(
			sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
		https.setPort(8443);
		https.setIdleTimeout(500000);

		server.addConnector(https);
		System.out.println("SSL access to the examples 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");

	// uncomment next line if you want to test with JSESSIONID encoded in the urls
	// ((AbstractSessionManager)
	// bb.getSessionHandler().getSessionManager()).setUsingCookies(false);

	server.setHandler(bb);

	MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
	MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
	server.addEventListener(mBeanContainer);
	server.addBean(mBeanContainer);

	try
	{
		server.start();
		server.join();
	}
	catch (Exception e)
	{
		e.printStackTrace();
		System.exit(100);
	}
}
 
Example 16
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 17
Source File: HttpdForTests.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an HTTPS server that requires client authentication (though doesn't validate the chain)
 *
 * @param caPath The path to a CA certificate to put in the keystore.
 * @param certificatePath The path to a pem encoded x509 certificate
 * @param keyPath The path to a pem encoded PKCS#8 certificate
 * @throws IOException Any of the keys could not be read
 * @throws KeyStoreException There's a problem writing the key into the keystore
 * @throws CertificateException The certificate was not valid
 * @throws NoSuchAlgorithmException The algorithm used by the certificate/key are invalid
 */
public HttpdForTests(Path caPath, Path certificatePath, Path keyPath)
    throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

  // Configure the logging for jetty. Which uses a singleton. Ho hum.
  Log.setLog(new JavaUtilLog());
  server = new Server();

  String password = "super_sekret";

  ImmutableList<X509Certificate> caCerts =
      ClientCertificateHandler.parseCertificates(Optional.of(caPath), true);
  ClientCertificateHandler.CertificateInfo certInfo =
      ClientCertificateHandler.parseCertificateChain(Optional.of(certificatePath), true).get();
  PrivateKey privateKey =
      ClientCertificateHandler.parsePrivateKey(
              Optional.of(keyPath), certInfo.getPrimaryCert(), true)
          .get();

  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, password.toCharArray());
  for (int i = 0; i < caCerts.size(); i++) {
    ks.setCertificateEntry(String.format("ca%d", i), caCerts.get(i));
  }
  ks.setKeyEntry(
      "private",
      privateKey,
      password.toCharArray(),
      new Certificate[] {certInfo.getPrimaryCert()});

  SslContextFactory sslFactory = new SslContextFactory();
  sslFactory.setKeyStore(ks);
  sslFactory.setKeyStorePassword(password);
  sslFactory.setCertAlias("private");
  sslFactory.setTrustStore(ks);
  sslFactory.setTrustStorePassword(password);
  // *Require* a client cert, but don't validate it (getting TLS auth working properly was a
  // bit of a pain). We'll store peers' certs in the handler, and validate the certs manually
  // in our tests.
  sslFactory.setNeedClientAuth(true);
  sslFactory.setTrustAll(true);

  HttpConfiguration https_config = new HttpConfiguration();
  https_config.setSecurePort(0);
  https_config.setSecureScheme("https");
  https_config.addCustomizer(new SecureRequestCustomizer());

  ServerConnector sslConnector =
      new ServerConnector(
          server,
          new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.toString()),
          new HttpConnectionFactory(https_config));
  server.addConnector(sslConnector);

  handlerList = new HandlerList();
  localhost = getLocalhostAddress(false).getHostAddress();
}
 
Example 18
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 19
Source File: StandardTLSTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

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

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

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 20
Source File: CipherAndProtocolSelectionTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    jettySslContextFactory = new SslContextFactory();
    jettySslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    jettySslContextFactory.setTrustStorePassword("password");
    jettySslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    jettySslContextFactory.setKeyStorePassword("password");
    jettySslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    jettySslContextFactory.setNeedClientAuth(false);
    jettySslContextFactory.setWantClientAuth(false);

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

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(jettySslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            jettyRequestAttributes = new HashMap<>();
            Enumeration<String> requestAttrNames = request.getAttributeNames();

            while (requestAttrNames.hasMoreElements()) {
                String elem = requestAttrNames.nextElement();
                jettyRequestAttributes.put(elem, request.getAttribute(elem).toString());
                System.out.println(elem + " - " + request.getAttribute(elem).toString());
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
}