Java 类org.eclipse.jetty.server.ServerConnector 实例源码

项目:spring-reactive-sample    文件:Application.java   
@Bean
public Server jettyServer(ApplicationContext context) throws Exception {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    Servlet servlet = new JettyHttpHandlerAdapter(handler);

    Server server = new Server();
    ServletContextHandler contextHandler = new ServletContextHandler(server, "");
    contextHandler.addServlet(new ServletHolder(servlet), "/");
    contextHandler.start();

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

    return server;
}
项目:java-spring-web    文件:MVCJettyITest.java   
@BeforeClass
public static void beforeClass() throws Exception {
    jettyServer = new Server(0);

    WebAppContext webApp = new WebAppContext();
    webApp.setServer(jettyServer);
    webApp.setContextPath(CONTEXT_PATH);
    webApp.setWar("src/test/webapp");

    jettyServer.setHandler(webApp);
    jettyServer.start();
    serverPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort();

    testRestTemplate = new TestRestTemplate(new RestTemplateBuilder()
            .rootUri("http://localhost:" + serverPort + CONTEXT_PATH));
}
项目:burpextender-proxyhistory-webui    文件:WebUIApp.java   
public void start(int listenPort, String dbname) throws Exception {
    if (Objects.nonNull(server) && server.isRunning()) {
        LOG.info("ineternal webui already running at port [" + listenPort + "].");
        throw new Exception("already running at port[" + listenPort + "]");
    }
    // remove old connectors
    Connector[] oldConnectors = server.getConnectors();
    if (Objects.nonNull(oldConnectors)) {
        for (Connector oldc : oldConnectors) {
            server.removeConnector(oldc);
        }
    }
    // add new connector
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(listenPort);
    server.setConnectors(new Connector[] { connector });
    // set dbname
    ServletContextHandler contextHandler = (ServletContextHandler) server.getHandler();
    contextHandler.setAttribute("dbname", dbname);
    server.start();
    LOG.info("internal webui server started with listening port [" + listenPort + "].");
}
项目:buabook-api-interface    文件:BuaBookApiInterface.java   
private void startJetty() throws Exception {
    QueuedThreadPool jettyThreadPool = new QueuedThreadPool(jettyServerThreads);
    Server server = new Server(jettyThreadPool);

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory());
    http.setPort(jettyListenPort);

    server.addConnector(http);

    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setHandler(botSocketHandler);
    server.setHandler(contextHandler);

    server.start();
    server.join();
}
项目:grpc-proxy    文件:LegacyHttpServer.java   
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
项目:JInsight    文件:JettyFilterInstrumentationTest.java   
@BeforeClass
public static void setUp() throws Exception {
  System.out.println("Jetty [Configuring]");

  ServletContextHandler servletContext = new ServletContextHandler();
  servletContext.setContextPath("/");
  servletContext.addServlet(PingPongServlet.class, PingPongServlet.PATH);
  servletContext.addServlet(ExceptionServlet.class, ExceptionServlet.PATH);
  ServletHolder servletHolder = servletContext.addServlet(AsyncServlet.class, AsyncServlet.PATH);
  servletHolder.setAsyncSupported(true);

  jetty = new Server(0);
  jetty.setHandler(servletContext);
  System.out.println("Jetty [Starting]");
  jetty.start();
  System.out.println("Jetty [Started]");
  serverPort = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort();
}
项目:boutique-de-jus    文件:BoutiqueDeJusWebServer.java   
/**
 * Attaches a server connector listening on the specified port to the server. Further the connector
 * is hooked into the configuration system to received runtime port changes
 *
 * @param server
 *         the Jetty server
 *
 * @return the created conector
 */
private static ServerConnector attachServerConnector(final Server server) {

    int initialHttpPort = Configuration.getInteger("jetty.http.port", 8080);

    //TODO config set accept queue size
    //TODO config acceptor num
    //TODO config selector num
    //TODO config idle timeout
    final ServerConnector connector = new ServerConnector(server);
    connector.setPort(initialHttpPort);
    server.addConnector(connector);

    Configuration.addListener(ConfigChangeListener.forConfigProperty("jetty.http.port", (k, v) -> {
        LOG.info("Changing http port to " + v);
        connector.setPort(Integer.parseInt(v));
        try {
            connector.stop();
            connector.start();
            LOG.info("HTTP Port changed");
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Restarting connector failed", e);
        }
    }));
    return connector;
}
项目:https-github.com-apache-zookeeper    文件:JettyAdminServer.java   
public JettyAdminServer(String address, int port, int timeout, String commandUrl) {
    this.port = port;
    this.idleTimeout = timeout;
    this.commandUrl = commandUrl;
    this.address = address;

    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address);
    connector.setPort(port);
    connector.setIdleTimeout(idleTimeout);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/*");
    server.setHandler(context);

    context.addServlet(new ServletHolder(new CommandServlet()), commandUrl + "/*");
}
项目:verify-service-provider    文件:UsefulApplicationUrlsTableFormatter.java   
private static List<ApplicationUrlsGenerator> extractTableRowForDefaultServer(Environment environment, ServerConnector connector) {
    String protocol = connector.getDefaultProtocol();
    int port = connector.getLocalPort();

    if ("admin".equals(connector.getName())) {
        String adminContextPath = environment.getAdminContext().getContextPath();

        return ImmutableList.of(
            new ApplicationUrlsGenerator(ADMIN_URL_TYPE, isHttps(protocol), port, adminContextPath),
            new ApplicationUrlsGenerator(HEALTHCHECK_URL_TYPE, isHttps(protocol), port, adminContextPath)
        );
    }

    return ImmutableList.of(
        new ApplicationUrlsGenerator(APPLICATION_URL_TYPE, isHttps(protocol), port, environment.getApplicationContext().getContextPath())
    );
}
项目:verify-service-provider    文件:UsefulApplicationUrlsTableFormatter.java   
private static List<ApplicationUrlsGenerator> extractRowsForSimpleServer(Environment environment, ServerConnector connector) {
    return ImmutableList.of(
        new ApplicationUrlsGenerator(
            APPLICATION_URL_TYPE,
            isHttps(connector.getDefaultProtocol()),
            connector.getLocalPort(),
            environment.getApplicationContext().getContextPath()
        ),
        new ApplicationUrlsGenerator(
            ADMIN_URL_TYPE,
            isHttps(connector.getDefaultProtocol()),
            connector.getLocalPort(),
            environment.getAdminContext().getContextPath()
        ),
        new ApplicationUrlsGenerator(
            HEALTHCHECK_URL_TYPE,
            isHttps(connector.getDefaultProtocol()),
            connector.getLocalPort(),
            environment.getAdminContext().getContextPath()
        )
    );
}
项目:minijax    文件:Minijax.java   
public void run(final int port) {
    try {
        final Server server = createServer();

        final ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server.setHandler(context);

        for (final MinijaxApplication application : applications) {
            addApplication(context, application);
        }

        final ServerConnector connector = createConnector(server);
        connector.setPort(port);
        server.setConnectors(new Connector[] { connector });
        server.start();
        server.join();

    } catch (final Exception ex) {
        throw new MinijaxException(ex);
    }
}
项目:minijax    文件:Minijax.java   
/**
 * Creates a server connector.
 *
 * If an HTTPS key store is configured, returns a SSL connector for HTTPS.
 *
 * Otherwise, returns a normal HTTP connector by default.
 *
 * @param server The server.
 * @return The server connector.
 */
@SuppressWarnings("squid:S2095")
private ServerConnector createConnector(final Server server) {
    final String keyStorePath = (String) configuration.get(MinijaxProperties.SSL_KEY_STORE_PATH);

    if (keyStorePath == null || keyStorePath.isEmpty()) {
        // Normal HTTP
        return new ServerConnector(server);
    }

    final String keyStorePassword = (String) configuration.get(MinijaxProperties.SSL_KEY_STORE_PASSWORD);
    final String keyManagerPassword = (String) configuration.get(MinijaxProperties.SSL_KEY_MANAGER_PASSWORD);

    final HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());

    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(Minijax.class.getClassLoader().getResource(keyStorePath).toExternalForm());
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);

    return new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));
}
项目:Cognizant-Intelligent-Test-Scripter    文件:DashBoardServer.java   
public void prepare() {
    try {
        Tools.verifyLocalPort("DBServer ", port());
        server = new Server();
        DefaultHandler webHandler = new DefaultHandler();
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{getResourceHandler(),
            getUIWSHandler(), webHandler});

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

        LOG.log(Level.INFO, "DB Server on : http://{0}:{1}",
                new Object[]{Tools.IP(), port() + ""});

    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
}
项目:kafka-0.11.0.0-src-with-comment    文件:RestServer.java   
/**
 * Create a REST server for this herder using the specified configs.
 */
public RestServer(WorkerConfig config) {
    this.config = config;

    // To make the advertised port available immediately, we need to do some configuration here
    String hostname = config.getString(WorkerConfig.REST_HOST_NAME_CONFIG);
    Integer port = config.getInt(WorkerConfig.REST_PORT_CONFIG);

    jettyServer = new Server();

    ServerConnector connector = new ServerConnector(jettyServer);
    if (hostname != null && !hostname.isEmpty())
        connector.setHost(hostname);
    connector.setPort(port);
    jettyServer.setConnectors(new Connector[]{connector});
}
项目:uavstack    文件:JettyPlusIT.java   
/**
 * startUAVServer
 */
public void startServer(Object... args) {

    Server server = (Server) args[0];

    // integrate Tomcat log
    UAVServer.instance().setLog(new JettyLog("MonitorServer"));
    // start Monitor Server when server starts
    UAVServer.instance().start(new Object[] { UAVServer.ServerVendor.JETTY });

    // get server port
    if (UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT) == null) {
        // set port
        ServerConnector sc = (ServerConnector) server.getConnectors()[0];

        String protocol = sc.getDefaultProtocol();
        if (protocol.toLowerCase().indexOf("http") >= 0) {
            UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT, sc.getPort());
        }
    }

}
项目:calcite-avatica    文件:HttpServer.java   
/**
 * Configures the <code>connector</code> given the <code>config</code> for using SPNEGO.
 *
 * @param connector The connector to configure
 * @param config The configuration
 */
protected ConstraintSecurityHandler configureSpnego(Server server, ServerConnector connector,
    AvaticaServerConfiguration config) {
  final String realm = Objects.requireNonNull(config.getKerberosRealm());
  final String principal = Objects.requireNonNull(config.getKerberosPrincipal());

  // A customization of SpnegoLoginService to explicitly set the server's principal, otherwise
  // we would have to require a custom file to set the server's principal.
  PropertyBasedSpnegoLoginService spnegoLoginService =
      new PropertyBasedSpnegoLoginService(realm, principal);

  // Roles are "realms" for Kerberos/SPNEGO
  final String[] allowedRealms = getAllowedRealms(realm, config);

  return configureCommonAuthentication(server, connector, config, Constraint.__SPNEGO_AUTH,
      allowedRealms, new AvaticaSpnegoAuthenticator(), realm, spnegoLoginService);
}
项目:calcite-avatica    文件:HttpServer.java   
protected ConstraintSecurityHandler configureCommonAuthentication(Server server,
    ServerConnector connector, AvaticaServerConfiguration config, String constraintName,
    String[] allowedRoles, Authenticator authenticator, String realm,
    LoginService loginService) {

  Constraint constraint = new Constraint();
  constraint.setName(constraintName);
  constraint.setRoles(allowedRoles);
  // This is telling Jetty to not allow unauthenticated requests through (very important!)
  constraint.setAuthenticate(true);

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

  ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
  sh.setAuthenticator(authenticator);
  sh.setLoginService(loginService);
  sh.setConstraintMappings(new ConstraintMapping[]{cm});
  sh.setRealmName(realm);

  return sh;
}
项目:abhot    文件:Launcher.java   
public static Server createDevServer(int port, String contextPath) {

        Server server = new Server();
        server.setStopAtShutdown(true);

        ServerConnector connector = new ServerConnector(server);
        // 设置服务端口
        connector.setPort(port);
        connector.setReuseAddress(false);
        server.setConnectors(new Connector[] {connector});

        // 设置web资源根路径以及访问web的根路径
        WebAppContext webAppCtx = new WebAppContext(DEFAULT_APP_CONTEXT_PATH, contextPath);
        webAppCtx.setDescriptor(DEFAULT_APP_CONTEXT_PATH + "/WEB-INF/web.xml");
        webAppCtx.setResourceBase(DEFAULT_APP_CONTEXT_PATH);
        webAppCtx.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webAppCtx);

        return server;
    }
项目:cassandra-prometheus    文件:PrometheusExporter.java   
public PrometheusExporter(int port, String path) {

    QueuedThreadPool threadPool = new QueuedThreadPool(25);
    server = new Server(threadPool);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);

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

    CollectorRegistry collectorRegistry = new CollectorRegistry();

    collectorRegistry.register(new PrometheusExports(CassandraMetricsRegistry.Metrics));

    MetricsServlet metricsServlet = new MetricsServlet(collectorRegistry);

    context.addServlet(new ServletHolder(metricsServlet), "/" + path);
    try {
        server.start();
    } catch (Exception e) {
        System.err.println("cannot start metrics http server " + e.getMessage());
    }
}
项目:Camel    文件:AbstractBaseEsbPerformanceIntegrationTest.java   
@Before
@Override
public void setUp() throws Exception {
    server = new Server(9000);

    ServerConnector connector0 = new ServerConnector(server);
    connector0.setReuseAddress(true);
    server.setConnectors(new Connector[]{connector0});

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/service");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new EchoService()), "/EchoService");
    server.start();

    payload = readPayload();

    super.setUp();
}
项目:webdav-embedded-server    文件:MiltonWebDAVFileServer.java   
/**
 * Creates and starts the server with the current state (credentials, port). After startup, the method will return
 * and not block.
 *
 * @throws IllegalStateException if the server has already been started
 * @throws Exception             if creation of the server fails
 */
public void start() throws Exception {
    if (jettyServer != null) {
        throw new IllegalStateException("Server already started");
    }

    jettyServer = new Server(0);

    connector = new ServerConnector(jettyServer); // NOSONAR
    connector.setPort(getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    HttpManagerBuilder builder = new HttpManagerBuilder();
    builder.setResourceFactory(new MiltonWebDAVResourceFactory(this.rootFolder, userCredentials));
    builder.setEnableBasicAuth(userCredentials != null && !userCredentials.isEmpty());
    HttpManager mgr = builder.buildHttpManager();

    jettyServer.setHandler(new MiltonHandler(mgr));

    jettyServer.start();

    while (!jettyServer.isStarted()) {
        Thread.sleep(50);
    }
}
项目:nifi-minifi    文件:PullHttpChangeIngestorSSLTest.java   
@Override
public void pullHttpChangeIngestorInit(Properties properties) {
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_LOCATION_KEY, "./src/test/resources/localhost-ts.jks");
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_TYPE_KEY, "JKS");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_LOCATION_KEY, "./src/test/resources/localhost-ks.jks");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_TYPE_KEY, "JKS");
    port = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort();
    properties.put(PullHttpChangeIngestor.PORT_KEY, String.valueOf(port));
    properties.put(PullHttpChangeIngestor.HOST_KEY, "localhost");

    pullHttpChangeIngestor = new PullHttpChangeIngestor();

    pullHttpChangeIngestor.initialize(properties, Mockito.mock(ConfigurationFileHolder.class), testNotifier);
    pullHttpChangeIngestor.setDifferentiator(mockDifferentiator);
}
项目:robotoy    文件:WebServer.java   
private void setupSSL(Server server,HttpConfiguration http_config) {
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (sslKeyStoreFile!=null)
        sslContextFactory.setKeyStorePath(sslKeyStoreFile);
    else if (sslKeyStore!=null)
        sslContextFactory.setKeyStore(sslKeyStore);
    else {
        log.log(Level.SEVERE,"Error while configuring SSL connection. Missing KeyStore!");
        return;
    }
    sslContextFactory.setKeyStorePassword(new String(sslKeyStorePassword));
    sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA",
            "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(daemonPortSecure);
    server.addConnector(sslConnector);
}
项目:Camel    文件:WebsocketComponent.java   
@Override
protected void doStart() throws Exception {
    super.doStart();

    if (staticResources != null) {
        // host and port must be configured
        ObjectHelper.notEmpty(host, "host", this);
        ObjectHelper.notNull(port, "port", this);

        LOG.info("Starting static resources server {}:{} with static resource: {}", new Object[]{host, port, staticResources});
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        staticResourcesServer = createStaticResourcesServer(context, host, port, staticResources);
        staticResourcesServer.start();
        ServerConnector connector = (ServerConnector) staticResourcesServer.getConnectors()[0];

        // must add static resource server to CONNECTORS in case the websocket producers/consumers
        // uses the same port number, and therefore we must be part of this
        MemoryWebsocketStore memoryStore = new MemoryWebsocketStore();
        ConnectorRef ref = new ConnectorRef(staticResourcesServer, connector, null, memoryStore);
        String key = "websocket:" + host + ":" + port;
        CONNECTORS.put(key, ref);
    }
}
项目:parsec-libraries    文件:JettyHttpTestServer.java   
public JettyHttpTestServer(String host, int port){
       this.host = host;
       this.port = port;
    server = new Server();

       ServerConnector http = new ServerConnector(server);
       http.setHost(host);
       http.setPort(port);
       http.setIdleTimeout(30000);

       server.addConnector(http);
       server.setHandler(new RequestHandler());

       try {
           server.start();
       } catch (Exception e) {
           e.printStackTrace();
       }

       this.port = http.getLocalPort();
}
项目:steve-plugsurfing    文件:JettyServer.java   
private String getConnectorPath(ServerConnector sc) {
    String prefix = "http";
    String host = sc.getHost();
    int port = sc.getPort();

    ConnectionFactory cf = sc.getDefaultConnectionFactory();
    if (cf instanceof SslConnectionFactory) {
        prefix = "https";
    }

    if (host == null || host.equals("0.0.0.0")) {
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            // Well, we failed to read from system, fall back to main.properties.
            // Better than nothing
            host = CONFIG.getJetty().getServerHost();
        }
    }

    String layout = "%s://%s:%d" + CONFIG.getContextPath();

    return String.format(layout, prefix, host, port);
}
项目:Camel    文件:WebsocketComponentTest.java   
@Before
public void setUp() throws Exception {
    component = new WebsocketComponent();
    component.setCamelContext(new DefaultCamelContext());
    System.out.println("Server : " + server.isStarted());
    server = component.createServer();
    System.out.println("Server : " + server.isStarted());
    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(1988);
    server.addConnector(connector);

    WebsocketEndpoint endpoint = (WebsocketEndpoint) component.createEndpoint("websocket://x");
    producer = (WebsocketProducer) endpoint.createProducer();
    component.connect(producer);

    // wire the consumer with the endpoint so that WebSocketComponent.getConnectorKey() works without throwing NPE
    when(consumer.getEndpoint()).thenReturn(endpoint);
}
项目:spring4-understanding    文件:JettyWebSocketClientTests.java   
public TestJettyWebSocketServer(int port, final WebSocketHandler webSocketHandler) {

            this.server = new Server();
            ServerConnector connector = new ServerConnector(this.server);
            connector.setPort(port);

            this.server.addConnector(connector);
            this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
                @Override
                public void configure(WebSocketServletFactory factory) {
                    factory.setCreator(new WebSocketCreator() {
                        @Override
                        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
                            if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
                                resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
                            }
                            JettyWebSocketSession session = new JettyWebSocketSession(null, null);
                            return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
                        }
                    });
                }
            });
        }
项目:graviteeio-access-management    文件:JettyHttpServer.java   
@Override
protected void doStart() throws Exception {
    attachNoContentHandler();
    attachHandlers();

    server.setStopAtShutdown(true);

    try {
        server.join();

        // Start HTTP server...
        server.start();

        logger.info("HTTP Server is now started and listening on port {}",
                ((ServerConnector) server.getConnectors()[0]).getPort());
    } catch (InterruptedException ex) {
        logger.error("An error occurs while trying to initialize HTTP server", ex);
    }
}
项目:kasije    文件:KasijeServer.java   
private ServerConnector createSSLServerConnector(Connector connectorConfig)
{
    SslContextFactory sslFact = new SslContextFactory();
    if (StringUtils.isNotBlank(connectorConfig.getKeyStorePath()))
    {
        sslFact.setKeyStorePath(connectorConfig.getKeyStorePath());
    }
    if (StringUtils.isNotBlank(connectorConfig.getKeyStorePassword()))
    {
        sslFact.setKeyStorePassword(connectorConfig.getKeyStorePassword());
    }
    if (StringUtils.isNotBlank(connectorConfig.getKeyManagerPassword()))
    {
        sslFact.setKeyManagerPassword(connectorConfig.getKeyManagerPassword());
    }
    if (StringUtils.isNotBlank(connectorConfig.getTrustStorePath()))
    {
        sslFact.setTrustStorePath(connectorConfig.getTrustStorePath());
    }
    if (StringUtils.isNotBlank(connectorConfig.getTrustStorePassword()))
    {
        sslFact.setTrustStorePassword(connectorConfig.getTrustStorePassword());
    }

    return new ServerConnector(internal, sslFact);
}
项目:tired    文件:WebServer.java   
public void start() {
    try {
        final ServerConnector httpConnector = new ServerConnector(server);

        httpConnector.setHost(root.host);
        httpConnector.setPort(root.port);
        httpConnector.setIdleTimeout(config.getInt("web.idle-timeout"));
        server.addConnector(httpConnector);

        final HandlerList handlers = new HandlerList();

        handlers.addHandler(inContext("/static", newResourcesHandler()));
        handlers.addHandler(inContext("/", new RootHandler(version, routes)));

        server.setHandler(handlers);
        server.start();

        log.info("Web Server started on http://" + root.host + ":" + root.port);
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}
项目:rpc-example    文件:JettyHttp2ServerConfig.java   
@Override
public void customize(Server server) {
    // HTTPS Configuration
    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.setSecureScheme("https");
    httpsConfig.setSecurePort(8443);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Context Factory for HTTPS and HTTP/2
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStoreResource(newClassPathResource("keystore"));
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);

    // SSL Connection Factory
    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "h2");

    // HTTP/2 Connector
    ServerConnector http2Connector = new ServerConnector(server, ssl, new HTTP2ServerConnectionFactory(httpsConfig));
    http2Connector.setPort(8443);
    server.addConnector(http2Connector);
}
项目:megaphone    文件:TestUtils.java   
public static void addHttpsConnector(Server server, int port) throws IOException, URISyntaxException {

        String keyStoreFile = resourceAsFile("ssltest-keystore.jks").getAbsolutePath();
        SslContextFactory sslContextFactory = new SslContextFactory(keyStoreFile);
        sslContextFactory.setKeyStorePassword("changeit");

        String trustStoreFile = resourceAsFile("ssltest-cacerts.jks").getAbsolutePath();
        sslContextFactory.setTrustStorePath(trustStoreFile);
        sslContextFactory.setTrustStorePassword("changeit");

        HttpConfiguration httpsConfig = new HttpConfiguration();
        httpsConfig.setSecureScheme("https");
        httpsConfig.setSecurePort(port);
        httpsConfig.addCustomizer(new SecureRequestCustomizer());

        ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
        connector.setPort(port);

        server.addConnector(connector);
    }
项目:app-runner    文件:WebServerTest.java   
TestServer() throws Exception {
    jettyServer = new Server(0);
    jettyServer.setHandler(new AbstractHandler() {
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            if (target.equals("/test-app")) {
                response.sendRedirect("/test-app/");
            } else if (target.equalsIgnoreCase("/test-app/slow")) {
                try {
                    Thread.sleep(Long.parseLong(request.getParameter("millis")));
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
                response.getWriter().append("This was slow");
            } else {
                response.setHeader("Server", "Test-Server");
                response.getWriter().append("Hello from test server").close();
            }
            baseRequest.setHandled(true);
        }
    });

    jettyServer.start();

    int port = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
    url = new URL("http://localhost:" + port + "/test-app");
}
项目:monsoon    文件:ApiServer.java   
private static void installListeners(Server server, Collection<? extends InetSocketAddress> addresses) {
    final List<Connector> connectors = new ArrayList<>(addresses.size());

    for (InetSocketAddress address : addresses) {
        final ServerConnector server_connector = new ServerConnector(server);
        server_connector.setReuseAddress(true);
        if (address.getAddress() != null) {
            if (!address.getAddress().isAnyLocalAddress()) {
                LOG.log(Level.INFO, "Binding API server address: {0}", address.getAddress().getHostAddress());
                server_connector.setHost(address.getAddress().getHostAddress());
            }
        } else if (address.getHostString() != null) {
            LOG.log(Level.INFO, "Binding API server address name: {0}", address.getHostString());
            server_connector.setHost(address.getHostString());
        }
        LOG.log(Level.INFO, "Binding API server port: {0}", address.getPort());
        server_connector.setPort(address.getPort());
        connectors.add(server_connector);
    }

    server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}
项目:http-fetcher    文件:SimpleHttpFetcherTest.java   
@Test
public final void testStaleConnection() throws Exception {
    startServer(new ResourcesResponseHandler(), 8089);
    ServerConnector sc = (ServerConnector) getServer().getConnectors()[0];
    sc.setSoLingerTime(-1);

    BaseFetcher fetcher = new SimpleHttpFetcher(1, TestUtils.CC_TEST_AGENT);
    String url = "http://localhost:8089/simple-page.html";
    fetcher.get(url);

    // TODO KKr - control keep-alive (linger?) value for Jetty, so we can
    // set it
    // to something short and thus make this sleep delay much shorter.
    Thread.sleep(2000);

    fetcher.get(url);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:JettyEmbeddedServletContainerFactoryTests.java   
@Test
public void sslCiphersConfiguration() throws Exception {
    Ssl ssl = new Ssl();
    ssl.setKeyStore("src/test/resources/test.jks");
    ssl.setKeyStorePassword("secret");
    ssl.setKeyPassword("password");
    ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" });

    JettyEmbeddedServletContainerFactory factory = getFactory();
    factory.setSsl(ssl);

    this.container = factory.getEmbeddedServletContainer();
    this.container.start();

    JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container;
    ServerConnector connector = (ServerConnector) jettyContainer.getServer()
            .getConnectors()[0];
    SslConnectionFactory connectionFactory = connector
            .getConnectionFactory(SslConnectionFactory.class);
    assertThat(connectionFactory.getSslContextFactory().getIncludeCipherSuites())
            .containsExactly("ALPHA", "BRAVO", "CHARLIE");
    assertThat(connectionFactory.getSslContextFactory().getExcludeCipherSuites())
            .isEmpty();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:JettyEmbeddedServletContainerFactoryTests.java   
@Test
public void sslEnabledMultiProtocolsConfiguration() throws Exception {
    Ssl ssl = new Ssl();
    ssl.setKeyStore("src/test/resources/test.jks");
    ssl.setKeyStorePassword("secret");
    ssl.setKeyPassword("password");
    ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" });
    ssl.setEnabledProtocols(new String[] { "TLSv1.1", "TLSv1.2" });

    JettyEmbeddedServletContainerFactory factory = getFactory();
    factory.setSsl(ssl);

    this.container = factory.getEmbeddedServletContainer();
    this.container.start();

    JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container;
    ServerConnector connector = (ServerConnector) jettyContainer.getServer()
            .getConnectors()[0];
    SslConnectionFactory connectionFactory = connector
            .getConnectionFactory(SslConnectionFactory.class);

    assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols())
            .isEqualTo(new String[] { "TLSv1.1", "TLSv1.2" });
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:JettyEmbeddedServletContainerFactoryTests.java   
@Test
public void sslEnabledProtocolsConfiguration() throws Exception {
    Ssl ssl = new Ssl();
    ssl.setKeyStore("src/test/resources/test.jks");
    ssl.setKeyStorePassword("secret");
    ssl.setKeyPassword("password");
    ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" });
    ssl.setEnabledProtocols(new String[] { "TLSv1.1" });

    JettyEmbeddedServletContainerFactory factory = getFactory();
    factory.setSsl(ssl);

    this.container = factory.getEmbeddedServletContainer();
    this.container.start();

    JettyEmbeddedServletContainer jettyContainer = (JettyEmbeddedServletContainer) this.container;
    ServerConnector connector = (ServerConnector) jettyContainer.getServer()
            .getConnectors()[0];
    SslConnectionFactory connectionFactory = connector
            .getConnectionFactory(SslConnectionFactory.class);

    assertThat(connectionFactory.getSslContextFactory().getIncludeProtocols())
            .isEqualTo(new String[] { "TLSv1.1" });
}
项目:hdfs-mesos    文件:HttpServer.java   
public void start() throws Exception {
    if (server != null) throw new IllegalStateException("started");
    Scheduler.Config config = Scheduler.$.config;

    QueuedThreadPool threadPool = new QueuedThreadPool(Runtime.getRuntime().availableProcessors() * 16);
    threadPool.setName("Jetty");

    server = new Server(threadPool);
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(config.apiPort());
    connector.setIdleTimeout(60 * 1000);

    ServletContextHandler handler = new ServletContextHandler();
    handler.addServlet(new ServletHolder(new Servlet()), "/");
    handler.setErrorHandler(new ErrorHandler());

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

    logger.info("started on port " + connector.getLocalPort());
}