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

项目: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();
}
项目:mpd-2017-i41d    文件:WeatherWebApp.java   
public static void main(String[] args) throws Exception {
    try(HttpRequest http = new HttpRequest()) {
        WeatherService service = new WeatherServiceCache(new WeatherWebApi(http));
        WeatherController weatherCtr = new WeatherController(service);

        ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
        String resPath = getSystemResource("public").toString();
        holderHome.setInitParameter("resourceBase", resPath);
        holderHome.setInitParameter("dirAllowed", "true");
        holderHome.setInitParameter("pathInfoOnly", "true");

        int[] counter = {0};
        new HttpServer(3000)
                .addHandler("/search", weatherCtr::getSearch)
                .addHandler("/search/city", weatherCtr::searchCity)
                .addHandler("/weather/*", weatherCtr::last30daysWeather)
                .addServletHolder("/public/*", holderHome)
                .run();
    }
}
项目:pinto    文件:Main.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.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);
        new Thread(new Console(getPinto(),port,build, () -> {
            try {
                server.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }), "console_thread").start();
        server.start();
        server.join();
    }
项目:Mastering-Mesos    文件:ApiModule.java   
@Override
protected void configureServlets() {
  if (ENABLE_CORS_FOR.get() != null) {
    filter(API_PATH).through(new CorsFilter(ENABLE_CORS_FOR.get()));
  }
  serve(API_PATH).with(TServlet.class);

  filter(ApiBeta.PATH, ApiBeta.PATH + "/*").through(LeaderRedirectFilter.class);
  filter(ApiBeta.PATH, ApiBeta.PATH + "/*")
      .through(GuiceContainer.class, JettyServerModule.GUICE_CONTAINER_PARAMS);
  bind(ApiBeta.class);

  serve("/apiclient", "/apiclient/*")
      .with(new DefaultServlet(), ImmutableMap.<String, String>builder()
          .put("resourceBase", API_CLIENT_ROOT)
          .put("pathInfoOnly", "true")
          .put("dirAllowed", "false")
          .build());
}
项目:conductor    文件:ServletContextListner.java   
private ServletModule getSwagger() {

    String resourceBasePath = ServletContextListner.class.getResource("/swagger-ui").toExternalForm();
    DefaultServlet ds = new DefaultServlet();

    ServletModule sm = new ServletModule() {
        @Override
        protected void configureServlets() {
            Map<String, String> params = new HashMap<>();
            params.put("resourceBase", resourceBasePath);
            params.put("redirectWelcome", "true");
            serve("/*").with(ds, params);
        }
    };

    return sm;

}
项目:ccow    文件:ParticipantHoster.java   
public ParticipantHoster(final List<ContextParticipantProxy> unregisteredParticipants, final short port) throws Exception {
    participants = unregisteredParticipants;

    participantsUrl = FluentIterable.from(participants).transform(new Function<ContextParticipantProxy, String>() {

        @Override
        public String apply(final ContextParticipantProxy input) {
            // return "/" + input.getApplicationName() +
            // "/ContextParticipant/*";
            return input.getApplicationName();
        }
    }).append("/*");

    server = new Server(port);
    final ServletContextHandler sch = new ServletContextHandler(server, "/");
    sch.addEventListener(new InnerListener());
    sch.addFilter(AppGuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    sch.addServlet(DefaultServlet.class, "/");
    server.start();
}
项目:incubator-zeppelin-druid    文件:ZeppelinServer.java   
private static WebAppContext setupWebAppContext(
    ZeppelinConfiguration conf) {

  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(conf.getServerContextPath());
  File warPath = new File(conf.getString(ConfVars.ZEPPELIN_WAR));
  if (warPath.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warPath.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warPath.getAbsolutePath());
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR));
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  return webApp;
}
项目:tracer    文件:JettyRule.java   
public JettyRule(final Filter filter, final Trace trace) {
    this.server = new Server(0);

    final ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");
    handler.addServlet(new ServletHolder(new AsyncServlet(trace)), "/async");
    handler.addServlet(new ServletHolder(new TraceServlet(trace)), "/traced");
    handler.addServlet(new ServletHolder(new TraceServlet(trace)), "/untraced");
    handler.addServlet(ForwardServlet.class, "/forward");
    handler.addServlet(IncludeServlet.class, "/include");
    handler.addServlet(FailingServlet.class, "/failure");
    handler.addServlet(DefaultServlet.class, "/");

    handler.addFilter(new FilterHolder(filter), "/async", EnumSet.allOf(DispatcherType.class));
    // /untraced is intentionally NOT traced!
    handler.addFilter(new FilterHolder(filter), "/traced", EnumSet.allOf(DispatcherType.class));
    handler.addFilter(new FilterHolder(filter), "/forward", EnumSet.allOf(DispatcherType.class));
    handler.addFilter(new FilterHolder(filter), "/include", EnumSet.allOf(DispatcherType.class));
    handler.addFilter(new FilterHolder(filter), "/failure", EnumSet.allOf(DispatcherType.class));

    server.setHandler(handler);
}
项目:bootique    文件:BQInternalWebServerTestFactory.java   
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

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

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
项目:samza    文件:TestHttpFileSystem.java   
@Test
public void testHttpFileSystemReadTimeouts() throws Exception {
  HttpServer server = new HttpServer("/", 0, null, new ServletHolder(DefaultServlet.class));
  try {
    server.addServlet("/download", new PartialFileFetchServlet());
    server.start();
    String serverUrl = server.getUrl().toString() + "download";
    FileSystemClientThread fileSystemClientThread = new FileSystemClientThread(new URI(serverUrl));
    fileSystemClientThread.start();
    fileSystemClientThread.join();
    Assert.assertEquals(fileSystemClientThread.getTotalBytesRead(), THRESHOLD_BYTES);
    Assert.assertNull(clientException);
    Assert.assertNull(serverException);
  } finally {
    server.stop();
  }
}
项目:incubator-htrace    文件:HBaseSpanViewerServer.java   
public int run(String[] args) throws Exception {
  URI uri = new URI("http://" + conf.get(HTRACE_VIEWER_HTTP_ADDRESS_KEY,
                                         HTRACE_VIEWER_HTTP_ADDRESS_DEFAULT));
  InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
  server = new Server(addr);
  ServletContextHandler root =
    new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
  server.setHandler(root);

  String resourceBase = server.getClass()
                              .getClassLoader()
                              .getResource("webapps/htrace")
                              .toExternalForm();
  root.setResourceBase(resourceBase);
  root.setWelcomeFiles(new String[]{"index.html"});
  root.addServlet(new ServletHolder(new DefaultServlet()),
                  "/");
  root.addServlet(new ServletHolder(new HBaseSpanViewerTracesServlet(conf)),
                  "/gettraces");
  root.addServlet(new ServletHolder(new HBaseSpanViewerSpansServlet(conf)),
                  "/getspans/*");

  server.start();
  server.join();
  return 0;
}
项目:varOne    文件:VarOneServer.java   
private static WebAppContext setupWebAppContext(VarOneConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(conf.getServerContextPath());
    File warPath = new File(conf.getString(ConfVars.VARONE_WAR));
    if (warPath.isDirectory()) {
      webApp.setResourceBase(warPath.getPath());
      webApp.setParentLoaderPriority(true);
    } else {
      // use packaged WAR
      webApp.setWar(warPath.getAbsolutePath());
      File warTempDirectory = new File(conf.getRelativeDir(ConfVars.VARONE_WAR_TEMPDIR));
      warTempDirectory.mkdir();
      LOG.info("VarOneServer Webapp path: {}" + warTempDirectory.getPath());
      webApp.setTempDirectory(warTempDirectory);
    }
    // Explicit bind to root
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    return webApp;
}
项目:partsregister-eventsourcing    文件:TestServer.java   
public static void main(String[] args) {
    Server server = new Server(8180);

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

    ServletHolder jerseyServlet = context
            .addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/rest/*");
    jerseyServlet.setInitOrder(1);
    jerseyServlet
            .setInitParameter("jersey.config.server.provider.packages", "ske.part.partsregister.interfaces.rest");
    String appName = PartsregisterApplication.class.getCanonicalName();
    jerseyServlet.setInitParameter("javax.ws.rs.Application", appName);

    ServletHolder staticServlet = context.addServlet(DefaultServlet.class, "/*");
    staticServlet.setInitParameter("resourceBase", "src/main/webapp");
    staticServlet.setInitParameter("pathInfoOnly", "true");

    try {
        server.start();
        server.join();
    } catch (Throwable t) {
        t.printStackTrace(System.err);
    }
}
项目:bkbc-tools    文件:JettyCrosServer.java   
public JettyCrosServer() throws Exception {
    server = new Server(80);
    HandlerList handlers = new HandlerList();
       ResourceHandler resource_handler = new ResourceHandler();
       resource_handler.setDirectoriesListed(true);
       resource_handler.setWelcomeFiles(new String[] { "index.html" });
       resource_handler.setBaseResource(Resource.newClassPathResource("web"));

       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
       context.setContextPath("/");
       context.setInitParameter("maxInterval", "1000");
       context.setInitParameter("logLevel", "2");

       handlers.setHandlers(new Handler[] { resource_handler, context});

       server.setHandler(handlers);


       FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
       filterHolder.getInitParameters().put(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization");
       context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));

       context.addServlet(new ServletHolder(new JsonServlet()), "/t.json");
       context.addServlet(new ServletHolder(new DefaultServlet()), "/*");

}
项目:titan-web-example    文件:RunApp.java   
public static void main(String[] args) throws Exception {
    System.out.println("Working directory: " + new File("./").getAbsolutePath().toString());
    Server server = new Server(9091);

    WebAppContext context = new WebAppContext();
    context.setDescriptor("/WEB-INF/web.xml");
    context.setResourceBase("src/main/webapp");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);

    context.addServlet(DefaultServlet.class, "/*");
    server.setHandler(context);

    server.start();
    server.join();

}
项目:Explorer    文件:ExplorerServer.java   
private static WebAppContext setupWebAppContext(ExplorerConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    File webapp = new File(conf.getString(ExplorerConfiguration.ConfVars.EXPLORER_WAR));
    if (webapp.isDirectory()) { // Development mode, read from FS
        webApp.setDescriptor(webapp+"/WEB-INF/web.xml");
        webApp.setResourceBase(webapp.getPath());
        webApp.setContextPath("/");
        webApp.setParentLoaderPriority(true);
    } else { //use packaged WAR
        webApp.setWar(webapp.getAbsolutePath());
    }

    ServletHolder servletHolder = new ServletHolder(new DefaultServlet());
    servletHolder.setInitParameter("cacheControl","private, max-age=0, must-revalidate");
    webApp.addServlet(servletHolder, "/*");
    return webApp;
}
项目:Explorer    文件:ExplorerServer.java   
/**
 * Handles the WebApplication for Swagger-ui
 *
 * @return WebAppContext with swagger ui context
 */
private static WebAppContext setupWebAppSwagger(ExplorerConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    File webapp = new File(conf.getString(ExplorerConfiguration.ConfVars.EXPLORER_API_WAR));

    if (webapp.isDirectory()) {
        webApp.setResourceBase(webapp.getPath());
    } else {
        webApp.setWar(webapp.getAbsolutePath());
    }
    webApp.setContextPath("/docs");
    webApp.setParentLoaderPriority(true);
    // Bind swagger-ui to the path HOST/docs
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/docs/*");
    return webApp;
}
项目:feathercon    文件:ServletConfiguration.java   
public ServletConfiguration build() {
    if (built) {
        throw new IllegalStateException("This builder has already built a ServletConfiguration.  Please create a new builder and start over");
    }
    if (servletClass == null) {
        servletClass = DefaultServlet.class;
    }

    ServletHolder servletHolder = servlet != null ? new ServletHolder(servlet) : new ServletHolder(servletClass);

    if (initOrder != null) {
        servletHolder.setInitOrder(initOrder);
    }
    if (servletName != null) {
        servletHolder.setName(servletName);
    }
    servletHolder.setInitParameters(initParameters);

    ServletConfiguration servletConfiguration = new ServletConfiguration(servletHolder, servletClass, pathSpecs, servletName, initOrder, initParameters);
    built = true;
    logger.info("Built {}", this);
    return servletConfiguration;
}
项目:feathercon    文件:ServletConfigurationTest.java   
@Test
public void testBuild() throws Exception {
    builder.withServletClass(DefaultServlet.class)
            .withServletName("superServlet")
            .withInitOrder(1)
            .withInitParameter("k1", "v1")
            .withPathSpec("/css/*")
            .withPathSpec("/js/*");
    ServletConfiguration build = builder.build();
    assertThat(build.initOrder, equalTo(1));
    assertThat(build.servletName, equalTo("superServlet"));
    assertThat(build.servletClass.equals(DefaultServlet.class), equalTo(true));

    assertThat(build.pathSpecs.size(), equalTo(2));
    assertThat(build.pathSpecs.contains("/css/*"), equalTo(true));
    assertThat(build.pathSpecs.contains("/js/*"), equalTo(true));

    assertThat(build.initParameters.containsKey("k1"), equalTo(true));
    assertThat(build.initParameters.get("k1"), equalTo("v1"));
}
项目:feathercon    文件:FeatherConTest.java   
@Test
public void testWithServletConfiguration() throws Exception {
    assertThat(builder.servletConfigurations, is(notNullValue()));
    assertThat(builder.servletConfigurations.size(), equalTo(0));

    ServletConfiguration.Builder servletConfigBuilder = new ServletConfiguration.Builder();
    servletConfigBuilder.withServletClass(DefaultServlet.class)
            .withServletName("superServlet")
            .withInitOrder(1)
            .withInitParameter("k1", "v1")
            .withPathSpec("/css/*")
            .withPathSpec("/js/*");
    ServletConfiguration servletConfiguration = servletConfigBuilder.build();
    builder.withServletConfiguration(servletConfiguration);
    assertThat(builder.servletConfigurations.size(), equalTo(1));
    assertThat(builder.servletConfigurations.contains(servletConfiguration), equalTo(true));
}
项目:feathercon    文件:WebappServerBuilderTest.java   
@Test
public void testWebAppBuilder() throws Exception {
    assertThat(webappServerBuilder.servletConfigurations.size(), equalTo(2));

    ServletConfiguration jaxRsConfig = webappServerBuilder.servletConfigurations.get(0);
    assertThat(jaxRsConfig.servletClass.equals(ServletContainer.class), equalTo(true));
    assertThat(jaxRsConfig.initParameters.get("com.sun.jersey.config.property.packages"), equalTo(jerseyScanPackages));
    assertThat(jaxRsConfig.initParameters.get("com.sun.jersey.api.json.POJOMappingFeature"), equalTo("true"));
    assertThat(jaxRsConfig.pathSpecs.get(0), equalTo(restPathSpec));

    ServletConfiguration staticConfig = webappServerBuilder.servletConfigurations.get(1);
    assertThat(staticConfig.servletClass.equals(DefaultServlet.class), equalTo(true));
    assertThat(staticConfig.initParameters.get("resourceBase"), equalTo(resourceBase));
    assertThat(staticConfig.pathSpecs.get(0), equalTo("/"));
    assertThat(server.port, equalTo(serverPort));
    assertThat(server.contextName, equalTo("/"));
    server.toString();
}
项目:chipster    文件:HttpRangeTest.java   
private static void jetty() throws Exception {
    System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");

    Server jettyInstance = new Server();

    ServerConnector connector = null;
    switch (protocol) {
    case "http":
        connector = new ServerConnector(jettyInstance);        
        break;

    case "https":           
        SslContextFactory contextFactory = KeyAndTrustManager.createSslContextFactory("../chipster-environment/security/filebroker.ks", "password", new String[] {"TLSv1.2"});
        connector = new ServerConnector(jettyInstance, contextFactory);
        break;      
    }

    connector.setPort(8080);
    jettyInstance.setConnectors(new Connector[]{ connector });

    ServletContextHandler root = new ServletContextHandler(jettyInstance, "/", false, false);
    root.setResourceBase(".");
    root.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    jettyInstance.start();  
}
项目:chipster    文件:ParallelDownloadTest.java   
public static Server getJetty() throws Exception {
    Server server = new Server();

    //http
    //ServerConnector connector = new ServerConnector(server);        

    //https
    SslContextFactory factory = new SslContextFactory();
    factory.setKeyStorePath("filebroker.ks");
    factory.setKeyStorePassword("password");
    ServerConnector connector = new ServerConnector(server, factory);

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

    ServletContextHandler handler = new ServletContextHandler(server, "/", false, false);
    handler.setResourceBase(new File("").getAbsolutePath());
    handler.addServlet(new ServletHolder(new DefaultServlet()), "/*");

    return server;
}
项目:Nicobar    文件:ExplorerAppTest.java   
@BeforeClass
public void init() throws Exception {
    System.setProperty("archaius.deployment.applicationId","scriptmanager-app");
    System.setProperty("archaius.deployment.environment","dev");

    server = new Server(TEST_LOCAL_PORT);

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

    context.addFilter(GuiceFilter.class, "/*", 1);
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
}
项目:elastic-job-cloud    文件:RestfulServer.java   
/**
 * 启动内嵌的RESTful服务器.
 *
 * @param packages RESTful实现类所在包
 * @param resourcePath 资源路径
 * @param servletPath servlet路径
 * @throws Exception 启动服务器异常
 */
public void start(final String packages, final Optional<String> resourcePath, final Optional<String> servletPath) throws Exception {
    log.info("Elastic Job: Start RESTful server");
    HandlerList handlers = new HandlerList();
    if (resourcePath.isPresent()) {
        servletContextHandler.setBaseResource(Resource.newClassPathResource(resourcePath.get()));
        servletContextHandler.addServlet(new ServletHolder(DefaultServlet.class), "/*");
    }
    String servletPathStr = (servletPath.isPresent() ? servletPath.get() : "") + "/*";
    servletContextHandler.addServlet(getServletHolder(packages), servletPathStr);
    handlers.addHandler(servletContextHandler);
    server.setHandler(handlers);
    server.start();
}
项目:ja-micro    文件:JettyComposer.java   
public static void compose(Server server) {
    //Servlets + Guice
    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");

    //JMX stuff...
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
}
项目:debug    文件:Profiling.java   
public static void startServer() throws ServletException {
    QueuedThreadPool threadPool = new QueuedThreadPool(10);
    threadPool.setDaemon(true);
    threadPool.setMaxThreads(10);
    Server server = new Server(threadPool);
    server.addBean(new ScheduledExecutorScheduler("JettyScheduler", true), true);
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory());
    http.setPort(2992);
    server.addConnector(http);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setBaseResource(Resource.newClassPathResource("/org/lwjglx/debug/static"));
    context.setWelcomeFiles(new String[] { "index.html" });
    server.setHandler(context);

    WebSocketUpgradeFilter wsfilter = WebSocketUpgradeFilter.configureContext(context);
    // wsfilter.getFactory().getPolicy().setIdleTimeout(5000);
    wsfilter.addMapping(new ServletPathSpec("/ws"), new ProfilingConnectionCreator());

    ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
    holderDefault.setInitParameter("dirAllowed", "true");
    context.addServlet(holderDefault, "/");

    try {
        server.start();
    } catch (Exception e) {
        throw new AssertionError("Could not start profiling server", e);
    }
}
项目:GroupControlDroidClient    文件:JettyServer.java   
public void run() {
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContextHandler.setContextPath("/");
    servletContextHandler.setResourceBase("./res");
    servletContextHandler.addFilter(CommonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));//增加过滤器
    servletContextHandler.addServlet(LoginServlet.class, "/login.cgi");
    servletContextHandler.addServlet(UserinfoServlet.class, "/userinfo.cgi");
    servletContextHandler.addServlet(FileBrowseServlet.class, "/file_browse.cgi");
    servletContextHandler.addServlet(DefaultServlet.class, "/");
    servletContextHandler.addServlet(ChangePassword.class, "/changepassword.cgi");
    servletContextHandler.addServlet(AddDeviceToGroupServlet.class, "/device/add_device_to_group.cgi");
    servletContextHandler.addServlet(AddGroupServlet.class, "/group/add_group.cgi");
    servletContextHandler.addServlet(GetGroupsServlet.class , "/group/get_groups.cgi");
    servletContextHandler.addServlet(EditGroupServlet.class, "/group/edit_group.cgi");
    servletContextHandler.addServlet(GetAllGroupsServlet.class, "/group/get_all_groups.cgi");
    servletContextHandler.addServlet(DeteleGroupServlet.class, "/group/delete_group.cgi");
    servletContextHandler.addServlet(AddDeviceToGroupServlet.class, "/group/add_device_to_group.cgi");
    servletContextHandler.addServlet(DeleteDeviceFromGroupServlet.class,"/group/delete_device_from_group.cgi");

    ServletHolder fileUploadServletHolder = new ServletHolder(new UploadServlet());
    fileUploadServletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement(System.getProperty("user.dir") +JettyConfig.UPLOAD_TMP_PATH));
    servletContextHandler.addServlet(fileUploadServletHolder, "/upload.cgi");

    servletContextHandler.setClassLoader(Thread.currentThread().getContextClassLoader());

       server.setHandler(servletContextHandler);
       try {
        server.start();
        server.join();

    } catch (Exception e) {
        logger.error("",e);
    }
}
项目:Mastering-Mesos    文件:JettyServerModule.java   
@VisibleForTesting
static ServletContextListener makeServletContextListener(
    final Injector parentInjector,
    final Module childModule) {

  return new GuiceServletContextListener() {
    @Override
    protected Injector getInjector() {
      return parentInjector.createChildInjector(
          childModule,
          new JerseyServletModule() {
            @Override
            protected void configureServlets() {
              bind(HttpStatsFilter.class).in(Singleton.class);
              filter("*").through(HttpStatsFilter.class);

              bind(LeaderRedirectFilter.class).in(Singleton.class);
              filterRegex(allOf(LEADER_ENDPOINTS))
                  .through(LeaderRedirectFilter.class);

              bind(GuiceContainer.class).in(Singleton.class);
              filterRegex(allOf(ImmutableSet.copyOf(JAX_RS_ENDPOINTS.values())))
                  .through(GuiceContainer.class, GUICE_CONTAINER_PARAMS);

              filterRegex("/assets/scheduler(?:/.*)?").through(LeaderRedirectFilter.class);

              serve("/assets", "/assets/*")
                  .with(new DefaultServlet(), ImmutableMap.of(
                      "resourceBase", STATIC_ASSETS_ROOT,
                      "dirAllowed", "false"));

              for (Class<?> jaxRsHandler : JAX_RS_ENDPOINTS.keySet()) {
                bind(jaxRsHandler);
              }
            }
          });
    }
  };
}
项目:conductor    文件:ConductorServer.java   
public synchronized void start(int port, boolean join) throws Exception {

    if(server != null) {
        throw new IllegalStateException("Server is already running");
    }

    Guice.createInjector(sm);

    //Swagger
    String resourceBasePath = Main.class.getResource("/swagger-ui").toExternalForm();
    this.server = new Server(port);

    ServletContextHandler context = new ServletContextHandler();
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.setResourceBase(resourceBasePath);
    context.setWelcomeFiles(new String[] { "index.html" });

    server.setHandler(context);


    DefaultServlet staticServlet = new DefaultServlet();
    context.addServlet(new ServletHolder(staticServlet), "/*");

    server.start();
    System.out.println("Started server on http://localhost:" + port + "/");
    try {
        boolean create = Boolean.getBoolean("loadSample");
        if(create) {
            System.out.println("Creating kitchensink workflow");
            createKitchenSink(port);
        }
    }catch(Exception e) {
        logger.error(e.getMessage(), e);
    }

    if(join) {
        server.join();
    }

}
项目:apache-archiva    文件:DownloadRemoteIndexTaskTest.java   
protected void createContext( Server server, File repositoryDirectory )
    throws IOException
{
    ServletContextHandler context = new ServletContextHandler();
    context.setResourceBase( repositoryDirectory.getAbsolutePath() );
    context.setContextPath( "/" );
    ServletHolder sh = new ServletHolder( DefaultServlet.class );
    context.addServlet( sh, "/" );
    server.setHandler( context );

}
项目:ccow    文件:ClientTestSuite.java   
@BeforeClass
public static void beforeClass() throws Exception {
    server = new Server(port);
    final ServletContextHandler sch = new ServletContextHandler(server, "/");
    sch.addEventListener(new CCOWContextListener(commonContext, new InlinedContextAgentRepositoryModule()));
    sch.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    sch.addServlet(DefaultServlet.class, "/");
    server.start();
}
项目:ccow    文件:IntegrationTests.java   
@BeforeClass
public static void beforeClass() throws Exception {
    ccowServer = new Server(serverPort);
    final ServletContextHandler sch = new ServletContextHandler(ccowServer, "/");
    sch.addEventListener(new CCOWContextListener(commonContext, new InlinedContextAgentRepositoryModule()));
    sch.addFilter(AppGuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    sch.addServlet(DefaultServlet.class, "/");
    ccowServer.start();
}
项目:leopard    文件:LeopardDefaultServlet.java   
protected void initUseFileMappedBuffer() throws Exception {
    Field field = DefaultServlet.class.getDeclaredField("_cache");
    field.setAccessible(true);
    CachedContentFactory cache = (CachedContentFactory) field.get(this);
    Field bufferField = CachedContentFactory.class.getDeclaredField("_useFileMappedBuffer");
    bufferField.setAccessible(true);
    bufferField.set(cache, false);
    // _useFileMappedBuffer
    // cache.
}
项目:carbon    文件:StaticHandler.java   
@AfterInject
public void afterInject() throws Exception {
    WebProperty.Resource resource = config.getResource();
    if (resource == null || resource.getDirectory() == null || resource.getOutPath() == null) {
        logger.info("Not found resource setting, so skip Resource handler mapping");
        return;
    }

    this.enabled = true;

    ServletHolder resourceServletHolder = new ServletHolder(DefaultServlet.class);
    resourceServletHolder.setInitParameter("acceptRanges", "f");
    resourceServletHolder.setInitParameter("dirAllowed","f");
    resourceServletHolder.setInitParameter("redirectWelcome","f");
    resourceServletHolder.setInitParameter("welcomeServlets", "f");
    resourceServletHolder.setInitParameter("gzip", "t");
    resourceServletHolder.setInitParameter("etags", "t");
    resourceServletHolder.setInitParameter("cacheControl", "t");

    String resourceDirectory = resource.getDirectory();
    String resourceBase = Optional.ofNullable(getClass().getClassLoader().getResource(resourceDirectory))
            .map(URL::toString)
            .orElseThrow(() -> new ServerStartupException(resourceSetupFailMessage(resourceDirectory)));
    resourceServletHolder.setInitParameter("resourceBase", resourceBase);

    this.resourcePath = config.getResource().getOutPath();
    String context = Paths.get("/", this.resourcePath).toString();
    this.setContextPath(context);
    this.addServlet(resourceServletHolder, "/");
}
项目:europa    文件:Europa.java   
public void start()
{
    _dispatchRepoMonitorTasks.schedule();

    WebServlet<EuropaRequestContext> servlet =
        new WebServlet<EuropaRequestContext>(_webappRouteMatcher, _requestHandlerFactory);
    servlet.setRequestContextFactory(_requestContextFactory);
    if(_webappFilters != null)
        servlet.setRequestFilters(_webappFilters);

    WebServer webServer = new WebServer(_port, servlet, "/", _sslPort, _sslContextFactory);

    ServletHolder staticHolder = new ServletHolder(DefaultServlet.class);
    staticHolder.setInitParameter("resourceBase", "./public");
    staticHolder.setInitParameter("dirAllowed","true");
    staticHolder.setInitParameter("pathInfoOnly","true");
    staticHolder.setInitParameter("etags", "true");
    staticHolder.setInitParameter("gzip", "true");
    staticHolder.setInitParameter("cacheControl", "max-age=3600");
    webServer.addStandardServlet("/public/*", staticHolder);

    WebServlet<EuropaRequestContext> registryApiServlet =
        new WebServlet<EuropaRequestContext>(_registryApiRouteMatcher, _requestHandlerFactory);
    servlet.setRequestContextFactory(_requestContextFactory);

    //Registry API Servlet uses the same request context (and
    //similar factory) as the main webapp servlet with the only
    //difference being that unmarshallJson is set to false
    registryApiServlet.setRequestContextFactory(new RequestContextFactory() {
            public RequestContext getRequestContext(HTTPMethod method, HttpServletRequest request) {
                return new EuropaRequestContext(method, request, false);
            }
        });
    registryApiServlet.setRequestFilters(_registryApiFilters);
    webServer.addWebServlet("/v2/*", registryApiServlet);
    webServer.addWebServlet("/v1/*", registryApiServlet);

    webServer.setErrorHandler(_staticContentErrorHandler);
    webServer.start();
}
项目:Camel    文件:WebsocketComponent.java   
protected Server createStaticResourcesServer(Server server, ServletContextHandler context, String home) throws Exception {

        context.setContextPath("/");

        SessionManager sm = new HashSessionManager();
        SessionHandler sh = new SessionHandler(sm);
        context.setSessionHandler(sh);

        if (home != null) {
            String[] resources = home.split(":");
            if (LOG.isDebugEnabled()) {
                LOG.debug(">>> Protocol found: " + resources[0] + ", and resource: " + resources[1]);
            }

            if (resources[0].equals("classpath")) {
                // Does not work when deployed as a bundle
                // context.setBaseResource(new JettyClassPathResource(getCamelContext().getClassResolver(), resources[1]));
                URL url = this.getCamelContext().getClassResolver().loadResourceAsURL(resources[1]);
                context.setBaseResource(Resource.newResource(url));
            } else if (resources[0].equals("file")) {
                context.setBaseResource(Resource.newResource(resources[1]));
            }
            DefaultServlet defaultServlet = new DefaultServlet();
            ServletHolder holder = new ServletHolder(defaultServlet);

            // avoid file locking on windows
            // http://stackoverflow.com/questions/184312/how-to-make-jetty-dynamically-load-static-pages
            holder.setInitParameter("useFileMappedBuffer", "false");
            context.addServlet(holder, "/");
        }

        server.setHandler(context);

        return server;
    }
项目:zeppelin    文件:ZeppelinServer.java   
private static WebAppContext setupWebAppContext(ContextHandlerCollection contexts,
                                                ZeppelinConfiguration conf) {

  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(conf.getServerContextPath());
  File warPath = new File(conf.getString(ConfVars.ZEPPELIN_WAR));
  if (warPath.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warPath.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warPath.getAbsolutePath());
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR));
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  contexts.addHandler(webApp);

  webApp.addFilter(new FilterHolder(CorsFilter.class), "/*",
      EnumSet.allOf(DispatcherType.class));

  webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed",
          Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED)));

  return webApp;

}
项目:samza    文件:TestHostAwareContainerAllocator.java   
private JobModelManager initializeJobModelManager(Config config, int containerCount) {
  Map<String, Map<String, String>> localityMap = new HashMap<>();
  localityMap.put("0", new HashMap<String, String>() { {
      put(SetContainerHostMapping.HOST_KEY, "abc");
    } });
  LocalityManager mockLocalityManager = mock(LocalityManager.class);
  when(mockLocalityManager.readContainerLocality()).thenReturn(localityMap);

  return JobModelManagerTestUtil.getJobModelManagerWithLocalityManager(getConfig(), containerCount, mockLocalityManager,
      new MockHttpServer("/", 7777, null, new ServletHolder(DefaultServlet.class)));
}