Java 类org.eclipse.jetty.servlet.ServletContextHandler 实例源码

项目:otus_java_2017_06    文件:Main.java   
public static void main(String[] args) throws Exception {

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setResourceBase(PUBLIC_HTML);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        //page reloaded by the timer
        context.addServlet(TimerServlet.class, "/timer");
        //part of a page reloaded by the timer
        context.addServlet(AjaxTimerServlet.class, "/server-time");
        //long-polling waits till a message
        context.addServlet(new ServletHolder(new MessengerServlet()), "/messenger");
        //web chat
        context.addServlet(WebSocketChatServlet.class, "/chat");

        Server server = new Server(PORT);
        server.setHandler(new HandlerList(resourceHandler, context));

        server.start();
        server.join();
    }
项目:websocket    文件:WebSocketServer.java   
/**
 * start server
 * 
 * @param port
 * @param path
 * @param handlerClass
 */
public static void startWebSocket(int port, String path, String handlerClass) {
    try {
        Server server = new Server(port);
        HandlerList handlerList = new HandlerList();
        ServletContextHandler context = new ServletContextHandler(
                ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.addServlet(new ServletHolder(new Jwservlet(handlerClass)),
                path);
        handlerList.addHandler(context);
        handlerList.addHandler(new DefaultHandler());
        server.setHandler(handlerList);
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.LOG("start websocket server error:" + e.getMessage(),
                LogLev.ERROR, WebSocketServer.class);
        System.exit(1);
    }
}
项目:crawling-framework    文件:Application.java   
public static void main(String[] args) {
    int port = Configuration.INSTANCE.getInt("port", 8080);
    Server server = new Server(port);
    ServletContextHandler contextHandler
            = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    ServletHolder sh = new ServletHolder(new VaadinServlet());
    contextHandler.addServlet(sh, "/*");
    contextHandler.setInitParameter("ui", CrawlerAdminUI.class.getCanonicalName());
    contextHandler.setInitParameter("productionMode", String.valueOf(PRODUCTION_MODE));
    server.setHandler(contextHandler);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOG.error("Failed to start application", e);
    }
}
项目:minijax    文件:Minijax.java   
private void addApplication(final ServletContextHandler context, final MinijaxApplication application)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    // (0) Sort the resource methods by literal length
    application.sortResourceMethods();

    // (1) Add Minijax filter (must come before websocket!)
    context.addFilter(new FilterHolder(new MinijaxFilter(application)), "/*", EnumSet.of(DispatcherType.REQUEST));

    // (2) WebSocket endpoints
    if (OptionalClasses.WEB_SOCKET_UTILS != null) {
        OptionalClasses.WEB_SOCKET_UTILS
                .getMethod("init", ServletContextHandler.class, MinijaxApplication.class)
                .invoke(null, context, application);
    }

    // (3) Dynamic JAX-RS content
    final MinijaxServlet servlet = new MinijaxServlet(application);
    final ServletHolder servletHolder = new ServletHolder(servlet);
    servletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
    context.addServlet(servletHolder, "/*");
}
项目:pinto    文件:Demo.java   
public void run() throws Exception {
    org.eclipse.jetty.util.log.Log.setLog(new Slf4jLog());
    Server server = new Server(port);
       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       context.setContextPath("/");
       context.setWelcomeFiles(new String[]{ "demo.html" });
       context.setResourceBase(httpPath);
       HashSessionIdManager idmanager = new HashSessionIdManager();
       server.setSessionIdManager(idmanager);
       HashSessionManager manager = new HashSessionManager();
       SessionHandler sessions = new SessionHandler(manager);
       sessions.setHandler(context);
       context.addServlet(new ServletHolder(new Servlet(this::getPinto)),"/pinto/*");
       ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
       context.addServlet(holderPwd,"/*");
       server.setHandler(sessions);
       server.start();
       server.join();
}
项目:guice-websocket    文件:JettyServer.java   
public void start() throws Exception {
    server = new Server(port);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.addFilter(AuthenticationFilter.class, "/*", null);
    context.setServer(server);

    // Add static files handler
    context.setBaseResource(Resource.newResource(JettyServer.class.getResource("/webapp")));
    context.addServlet(DefaultServlet.class,"/");
    context.setWelcomeFiles(new String[]{"index.html"});

    ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context);
    wsContainer.addEndpoint(createEndpointConfig(EchoEndpoint.class));

    server.setHandler(context);
    server.start();
}
项目: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;
}
项目:crawling-framework    文件:Application.java   
public static void main(String[] args) {
    int port = Configuration.INSTANCE.getInt("port", 8080);
    Server server = new Server(port);
    ServletContextHandler contextHandler
            = new ServletContextHandler(ServletContextHandler.SESSIONS);
    contextHandler.setContextPath("/");
    ServletHolder sh = new ServletHolder(new VaadinServlet());
    contextHandler.addServlet(sh, "/*");
    contextHandler.setInitParameter("ui", AnalysisUI.class.getCanonicalName());
    contextHandler.setInitParameter("productionMode", String.valueOf(PRODUCTION_MODE));
    server.setHandler(contextHandler);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOG.error("Failed to start application", e);
    }
}
项目:jetty-embed-reverse-proxy-example    文件:ProxyServer.java   
private static void reverseProxy() throws Exception{
  Server server = new Server();

  SocketConnector connector = new SocketConnector();
  connector.setHost("127.0.0.1");
  connector.setPort(8888);

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

  // Setup proxy handler to handle CONNECT methods
  ConnectHandler proxy = new ConnectHandler();
  server.setHandler(proxy);

  // Setup proxy servlet
  ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS);
  ServletHolder proxyServlet = new ServletHolder(ProxyServlet.Transparent.class);
  proxyServlet.setInitParameter("ProxyTo", "https://localhost:54321/");
  proxyServlet.setInitParameter("Prefix", "/");
  context.addServlet(proxyServlet, "/*");

  server.start();
}
项目:jmeter-prometheus-plugin    文件:PrometheusListener.java   
public void testStarted() {
    // update the configuration
    this.reconfigure();
    this.server = new Server(this.getSaveConfig().getPort());

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");

    try {
        server.start();
    } catch (Exception e) {
        log.error("Couldn't start http server", e);
    }

}
项目:traccar-service    文件:WebServer.java   
private void initClientProxy() {
    int port = Context.getConfig().getInteger("osmand.port");
    if (port != 0) {
        ServletContextHandler servletHandler = new ServletContextHandler() {
            @Override
            public void doScope(
                    String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                    throws IOException, ServletException {
                if (target.equals("/") && request.getMethod().equals(HttpMethod.POST.asString())) {
                    super.doScope(target, baseRequest, request, response);
                }
            }
        };
        ServletHolder servletHolder = new ServletHolder(new AsyncProxyServlet.Transparent());
        servletHolder.setInitParameter("proxyTo", "http://localhost:" + port);
        servletHandler.addServlet(servletHolder, "/");
        handlers.addHandler(servletHandler);
    }
}
项目:traccar-service    文件:WebServer.java   
private void initApi() {
    ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setContextPath("/api");
    servletHandler.getSessionHandler().setSessionManager(sessionManager);

    servletHandler.addServlet(new ServletHolder(new AsyncSocketServlet()), "/socket");

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.registerClasses(JacksonFeature.class, ObjectMapperProvider.class, ResourceErrorHandler.class);
    resourceConfig.registerClasses(SecurityRequestFilter.class, CorsResponseFilter.class);
    resourceConfig.packages(ServerResource.class.getPackage().getName());

    servletHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    handlers.addHandler(servletHandler);
}
项目:OpenChatAlytics    文件:ServerMain.java   
/**
 *
 * @param context the context to add the web socket endpoints to
 * @param rtEventResource The instance of the websocket endpoint to return
 * @throws DeploymentException
 */
private static void setWebSocketEndpoints(ServletContextHandler context,
                                          EventsResource rtEventResource)
        throws DeploymentException, ServletException {

    ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context);

    ServerEndpointConfig serverConfig =
            ServerEndpointConfig.Builder
                                .create(EventsResource.class, EventsResource.RT_EVENT_ENDPOINT)
                                .configurator(new Configurator() {
                                    @Override
                                    public <T> T getEndpointInstance(Class<T> endpointClass)
                                            throws InstantiationException {
                                        return endpointClass.cast(rtEventResource);
                                    }
                                }).build();

    wsContainer.addEndpoint(serverConfig);
}
项目: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 + "].");
}
项目:act-platform    文件:ApiServer.java   
@Override
public void startComponent() {
  // Initialize servlet using RESTEasy and it's Guice bridge.
  // The listener must be injected by the same Guice module which also binds the REST endpoints.
  ServletContextHandler servletHandler = new ServletContextHandler();
  servletHandler.addEventListener(listener);
  servletHandler.addServlet(HttpServletDispatcher.class, "/*");

  // Starting up Jetty to serve the REST API.
  server = new Server(port);
  server.setHandler(servletHandler);

  try {
    server.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
项目:otus_java_2017_06    文件:Main.java   
private void start() throws Exception {
    resourcesExample();

    ResourceHandler resourceHandler = new ResourceHandler();
    Resource resource = Resource.newClassPathResource(PUBLIC_HTML);
    resourceHandler.setBaseResource(resource);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    context.addServlet(new ServletHolder(new TimerServlet()), "/timer");

    Server server = new Server(PORT);
    server.setHandler(new HandlerList(resourceHandler, context));

    server.start();
    server.join();
}
项目:otus_java_2017_06    文件:Main.java   
public static void main(String[] args) throws Exception {

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setResourceBase(PUBLIC_HTML);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        context.addServlet(new ServletHolder(new LoginServlet("anonymous")), "/login");
        context.addServlet(AdminServlet.class, "/admin");
        context.addServlet(TimerServlet.class, "/timer");

        Server server = new Server(PORT);
        server.setHandler(new HandlerList(resourceHandler, context));

        server.start();
        server.join();
    }
项目:Avalon-Executive    文件:MainServer.java   
public static void main(String[] args) throws Exception {
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    Initiator.init();

    Server server = new Server(PORT);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(CONTEXT_PATH);
    server.setHandler(context);
    server.setStopAtShutdown(true);

    context.addServlet(new ServletHolder(new GetAllLang()), "/get_all_lang");
    context.addServlet(new ServletHolder(new Compile()), "/compile");
    context.addServlet(new ServletHolder(new Run()), "/run");
    server.join();
    server.start();

    LOGGER.info("Avalon-Executive server is now running at http://127.0.0.1:" + PORT + CONTEXT_PATH);
}
项目: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();
}
项目:otter-G    文件:JettyEmbedServer.java   
public void afterPropertiesSet() throws Exception {
    Resource configXml = Resource.newSystemResource(config);
    XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream());
    server = (Server) configuration.configure();
    Integer port = getPort();
    if (port != null && port > 0) {
        Connector[] connectors = server.getConnectors();
        for (Connector connector : connectors) {
            connector.setPort(port);
        }
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", htdocsDir);
    }

    server.start();
    if (logger.isInfoEnabled()) {
        logger.info("##Jetty Embed Server is startup!");
    }
}
项目:otter-G    文件:JettyEmbedIntegration.java   
public static void main(String args[]) throws Exception {
    Resource jetty_xml = Resource.newSystemResource("jetty/jetty.xml");
    XmlConfiguration configuration = new XmlConfiguration(jetty_xml.getInputStream());
    Server server = (Server) configuration.configure();
    int port = 8081;
    Connector[] connectors = server.getConnectors();
    for (Connector connector : connectors) {
        connector.setPort(port);
    }

    Handler handler = server.getHandler();
    if (handler != null && handler instanceof ServletContextHandler) {
        ServletContextHandler servletHandler = (ServletContextHandler) handler;
        servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", "/tmp/");
    }

    server.start();
    server.join();
}
项目: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 + "/*");
}
项目: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);
    }
}
项目:otus_java_2017_04    文件:Main.java   
public static void main(String[] args) throws Exception {

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setResourceBase(PUBLIC_HTML);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        context.addServlet(new ServletHolder(new LoginServlet("anonymous")), "/login");
        context.addServlet(AdminServlet.class, "/admin");
        context.addServlet(TimerServlet.class, "/timer");

        Server server = new Server(PORT);
        server.setHandler(new HandlerList(resourceHandler, context));

        server.start();
        server.join();
    }
项目:wisp    文件:ServerMain.java   
public static void main(String[] args) throws Exception {

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

        Server jettyServer = new Server(8067);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(
                org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Tells the Jersey Servlet which REST service/class to load.
        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                EntryPointTestHandler.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
项目:skywalking-mock-collector    文件:Main.java   
public static void main(String[] args) throws Exception {
    NettyServerBuilder.forAddress(LocalAddress.ANY).forPort(19876)
        .maxConcurrentCallsPerConnection(12).maxMessageSize(16777216)
        .addService(new MockApplicationRegisterService())
        .addService(new MockInstanceDiscoveryService())
        .addService(new MockJVMMetricsService())
        .addService(new MockServiceNameDiscoveryService())
        .addService(new MockTraceSegmentService()).build().start();

    Server jettyServer = new Server(new InetSocketAddress("0.0.0.0",
        Integer.valueOf(12800)));
    String contextPath = "/";
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath(contextPath);
    servletContextHandler.addServlet(GrpcAddressHttpService.class, GrpcAddressHttpService.SERVLET_PATH);
    servletContextHandler.addServlet(ReceiveDataService.class, ReceiveDataService.SERVLET_PATH);
    servletContextHandler.addServlet(ClearReceiveDataService.class, ClearReceiveDataService.SERVLET_PATH);
    jettyServer.setHandler(servletContextHandler);
    jettyServer.start();
}
项目:strictfp-back-end    文件:MainServer.java   
public static void main(@NotNull @NonNls String[] args) throws Exception {
    PropertyConfigurator.configure(System.getProperty("user.dir") + "/log4j.properties");
    logger.warn("StrictFP | Back-end");
    logger.info("StrictFP Back-end is now running...");
    Server server = new Server(Constant.SERVER.SERVER_PORT);
    ServletContextHandler context =
            new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/api/v0");
    server.setHandler(context);
    server.setStopAtShutdown(true);
    // 像下面这行一样
    context.addServlet(new ServletHolder(new GetQuiz()), "/misc/getquiz");
    context.addServlet(new ServletHolder(new TimeLine()), "/timeline");
    context.addServlet(new ServletHolder(new Counter()), "/misc/counter");
    context.addServlet(new ServletHolder(new User()), "/user");
    context.addServlet(new ServletHolder(new Heartbeat()), "/misc/heartbeat");
    context.addServlet(new ServletHolder(new SafeCheck()), "/misc/safecheck");
    context.addServlet(new ServletHolder(new CheckCert()), "/auth/check_cert");
    //
    server.start();
    server.join();
}
项目: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    文件:WebsocketComponent.java   
protected WebsocketComponentServlet addServlet(NodeSynchronization sync, WebsocketProducerConsumer prodcon, String resourceUri) throws Exception {

        // Get Connector from one of the Jetty Instances to add WebSocket Servlet
        WebsocketEndpoint endpoint = prodcon.getEndpoint();
        String key = getConnectorKey(endpoint);
        ConnectorRef connectorRef = getConnectors().get(key);

        WebsocketComponentServlet servlet;

        if (connectorRef != null) {
            String pathSpec = createPathSpec(resourceUri);
            servlet = servlets.get(pathSpec);
            if (servlet == null) {
                // Retrieve Context
                ServletContextHandler context = (ServletContextHandler) connectorRef.server.getHandler();
                servlet = createServlet(sync, pathSpec, servlets, context);
                connectorRef.servlet = servlet;
                LOG.debug("WebSocket servlet added for the following path : " + pathSpec + ", to the Jetty Server : " + key);
            }

            return servlet;
        } else {
            throw new Exception("Jetty instance has not been retrieved for : " + key);
        }
    }
项目:jobimservice    文件:RestServer.java   
public void start() throws Exception {
    Server server = new Server(REST_SERVICE_PORT);

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

    ServletHolder servletHolder = servletContextHandler.addServlet(
            org.glassfish.jersey.servlet.ServletContainer.class, "/*"
    );
    servletHolder.setInitOrder(0);
    servletHolder.setInitParameter(
            "jersey.config.server.provider.classnames",
            RestInterface.class.getCanonicalName()
    );

    try {
        server.start();
        server.join();
    } finally {
        server.destroy();
    }
}
项目:endpoints-management-java    文件:IntegrationTestServer.java   
public void start() throws Exception {
  URL keystoreUrl = IntegrationTestServer.class.getClassLoader().getResource("keystore.jks");
  SslContextFactory sslContextFactory = new SslContextFactory();
  sslContextFactory.setKeyStorePath(keystoreUrl.getPath());
  sslContextFactory.setKeyStorePassword("keystore");

  SecureRequestCustomizer src = new SecureRequestCustomizer();
  HttpConfiguration httpsConfiguration = new HttpConfiguration();
  httpsConfiguration.setSecureScheme("https");
  httpsConfiguration.addCustomizer(src);

  ServerConnector https = new ServerConnector(server,
      new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
          new HttpConnectionFactory(httpsConfiguration));
  https.setPort(this.httpsPort);

  this.server.setConnectors(new Connector[] { https });

  ResourceConfig resourceConfig = new ResourceConfig(this.resourceClass);
  ServletContainer servletContainer = new ServletContainer(resourceConfig);
  ServletHolder servletHolder = new ServletHolder(servletContainer);
  ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/*");
  servletContextHandler.addServlet(servletHolder, "/*");

  this.server.start();
}
项目:Camel    文件:CometdCrossOriginConsumerTest.java   
@Test
public void testCrossOriginFilterAddedWhenOn() throws Exception {
    // setup
    CometdComponent component = context.getComponent("cometd", CometdComponent.class);
    Server server = new Server();

    when(endpoint.isCrossOriginFilterOn()).thenReturn(true);
    when(endpoint.getFilterPath()).thenReturn(FILTER_PATH);
    when(endpoint.getAllowedOrigins()).thenReturn(ALLOWED_ORIGINS);

    // act
    component.createServletForConnector(server, connector, endpoint);

    // assert
    ServletContextHandler handler = (ServletContextHandler) server.getHandler();
    assertEquals(1, handler.getServletHandler().getFilters().length);

    FilterHolder filterHolder = handler.getServletHandler().getFilters()[0];
    Filter filter = filterHolder.getFilter();
    assertTrue(filter instanceof CrossOriginFilter);
}
项目:Shape-Shmup    文件:MainServer.java   
public static void main(String[] args) {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.addConnector(connector);

    // Setup the basic application "context" for this application at "/"
    // This is also known as the handler tree (in jetty speak)
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    ServletHolder holder = new ServletHolder("socket", WebServlet.class);
    context.addServlet(holder, "/socket/*");

    try {
        server.start();
        server.dump(System.err);
        server.join();
    } catch (Throwable t) {
        t.printStackTrace(System.err);
    }
}
项目:Camel    文件:JettyTestServer.java   
public void startServer() {
    server = new Server(PORT);
    port = PORT;

    ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContext.setSecurityHandler(basicAuth("camel", "camelPass", "Private!"));
    servletContext.setContextPath("/");
    server.setHandler(servletContext);
    servletContext.addServlet(new ServletHolder(new MyHttpServlet()), "/*");
    try {
        server.start();
    } catch (Exception ex) {
        LOG.error("Could not start Server!", ex);
        fail(ex.getLocalizedMessage());
    }
}
项目:sparkled    文件:RestApiServerImpl.java   
private void addStaticResourceConfig(ServletContextHandler context) {
    URL webappLocation = getClass().getResource("/webapp/index.html");
    if (webappLocation == null) {
        System.err.println("Couldn't get webapp location.");
    } else {
        try {
            URI webRootUri = URI.create(webappLocation.toURI().toASCIIString().replaceFirst("/index.html$", "/"));
            context.setBaseResource(Resource.newResource(webRootUri));
            context.setWelcomeFiles(new String[]{"index.html"});

            GzipHandler gzipHandler = new GzipHandler();
            gzipHandler.setIncludedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name());
            context.setGzipHandler(gzipHandler);
            context.addFilter(TryFilesFilter.class, "*", EnumSet.of(DispatcherType.REQUEST));
        } catch (URISyntaxException | MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
项目:embedded-jetty-http2    文件:Application.java   
private ServletContextHandler createServletHandlerWithServlet() {
    ServletContextHandler context = new ServletContextHandler(
            ServletContextHandler.SESSIONS);

    FilterHolder pushCacheFilter = context.addFilter(PushCacheFilter.class, "/*",
            null);
    Map<String, String> config = new HashMap<>();
    config.put("maxAssociations", "32");
    config.put("ports", Objects.toString(SSL_PORT));
    pushCacheFilter.setInitParameters(config);

    context.addServlet(NoopServlet.class, "/*");
    context.setContextPath("/");

    return context;
}
项目:storytime-backend    文件:StartServer.java   
/**
 * 
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");
    Logger mainLogger = Logger.getInstance();
    mainLogger.out(Level.INFORMATIVE, "Main", "Starting server");
    Server server = new Server(8080);
    mainLogger.out(Level.INFORMATIVE, "Main", "Set handler");
    server.setHandler(context);

    ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

    jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
    jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "view");

    server.start();
    server.join();
    mainLogger.out(Level.INFORMATIVE, "Main", "Server started");
}
项目:ensemble    文件:RestServer.java   
public void start(Controller controller) throws Exception {
    this.controller = controller;

    Server server = new Server(REST_SERVICE_PORT);

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("");
    servletContextHandler.addServlet(new ServletHolder(new ServletContainer(resourceConfig(controller))), "/*");
    server.setHandler(servletContextHandler);

    try {
        server.start();
        server.join();
    } finally {
        server.destroy();
    }
}
项目:step    文件:Grid.java   
private void initializeServer() {
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(GridServices.class.getPackage().getName());
    resourceConfig.register(JacksonJaxbJsonProvider.class);
    final Grid grid = this;

    resourceConfig.register(new AbstractBinder() {  
        @Override
        protected void configure() {
            bind(grid).to(Grid.class);
            bind(fileManager).to(FileProvider.class);
        }
    });
    ServletContainer servletContainer = new ServletContainer(resourceConfig);

    ServletHolder sh = new ServletHolder(servletContainer);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(sh, "/*");

    server = new Server(port);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
       contexts.setHandlers(new Handler[] { context});
    server.setHandler(contexts);
}
项目:rdf-delta    文件:PatchLogServer.java   
/** Build a ServletContextHandler. */
private static ServletContextHandler buildServletContext(String contextPath) {
    if ( contextPath == null || contextPath.isEmpty() )
        contextPath = "/" ;
    else if ( !contextPath.startsWith("/") )
        contextPath = "/" + contextPath ;
    ServletContextHandler context = new ServletContextHandler() ;
    context.setDisplayName("PatchLogServer") ;
    MimeTypes mt = new MimeTypes();
    addMimeType(mt, Lang.TTL);
    addMimeType(mt, Lang.NT);
    addMimeType(mt, Lang.TRIG);
    addMimeType(mt, Lang.NQ);
    addMimeType(mt, Lang.RDFXML);
    context.setMimeTypes(mt);
    ErrorHandler eh = new HttpErrorHandler();
    context.setErrorHandler(eh) ;
    return context ;
}