コード例 #1
0
  @Override
  public Server apply(@Nullable String baseResource) {
    if (!jetty.getState().equals(Server.STARTED)
        // TODO code smell = hard coding addresses or ports!!
        && !new InetSocketAddressConnect().apply(new IPSocket("localhost", port))) {
      ResourceHandler resource_handler = new ResourceHandler();
      resource_handler.setDirectoriesListed(true);
      resource_handler.setWelcomeFiles(new String[] {"index.html"});

      resource_handler.setResourceBase(baseResource);
      logger.info("serving " + resource_handler.getBaseResource());

      HandlerList handlers = new HandlerList();
      handlers.setHandlers(new Handler[] {resource_handler, new DefaultHandler()});
      jetty.setHandler(handlers);

      try {
        jetty.start();
      } catch (Exception e) {
        logger.error(e, "Server jetty could not be started at this %s", baseResource);
      }
      return jetty;
    } else {
      logger.debug("Server jetty serving %s already running. Skipping start", baseResource);
      return jetty;
    }
  }
コード例 #2
0
ファイル: GHServer.java プロジェクト: cloudbearings/SMART-GH
  public void start(Injector injector) throws Exception {
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setDirectoriesListed(false);
    resHandler.setWelcomeFiles(new String[] {"index.html"});
    resHandler.setResourceBase(args.get("jetty.resourcebase", "./src/main/webapp"));

    server = new Server();
    // getSessionHandler and getSecurityHandler should always return null
    ServletContextHandler servHandler =
        new ServletContextHandler(
            ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servHandler.setContextPath("/");

    servHandler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    SelectChannelConnector connector0 = new SelectChannelConnector();
    int httpPort = args.getInt("jetty.port", 8989);
    String host = args.get("jetty.host", "");
    connector0.setPort(httpPort);
    if (!host.isEmpty()) connector0.setHost(host);

    server.addConnector(connector0);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resHandler, servHandler});
    server.setHandler(handlers);
    server.start();
    logger.info("Started server at HTTP " + host + ":" + httpPort);
  }
コード例 #3
0
ファイル: App.java プロジェクト: michaeldeluna/app-runner
 private static Handler resourceHandler() {
   ResourceHandler resourceHandler = new ResourceHandler();
   resourceHandler.setBaseResource(Resource.newClassPathResource("/web", false, false));
   resourceHandler.setWelcomeFiles(new String[] {"index.html"});
   resourceHandler.setMinMemoryMappedContentLength(-1);
   return resourceHandler;
 }
コード例 #4
0
  @Test
  public void testReplaceHandler() throws Exception {
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    ServletHolder sh = new ServletHolder(new TestServlet());
    servletContextHandler.addServlet(sh, "/foo");
    final AtomicBoolean contextInit = new AtomicBoolean(false);
    final AtomicBoolean contextDestroy = new AtomicBoolean(false);

    servletContextHandler.addEventListener(
        new ServletContextListener() {

          @Override
          public void contextInitialized(ServletContextEvent sce) {
            if (sce.getServletContext() != null) contextInit.set(true);
          }

          @Override
          public void contextDestroyed(ServletContextEvent sce) {
            if (sce.getServletContext() != null) contextDestroy.set(true);
          }
        });
    ServletHandler shandler = servletContextHandler.getServletHandler();

    ResourceHandler rh = new ResourceHandler();

    servletContextHandler.insertHandler(rh);
    assertEquals(shandler, servletContextHandler.getServletHandler());
    assertEquals(rh, servletContextHandler.getHandler());
    assertEquals(rh.getHandler(), shandler);
    _server.setHandler(servletContextHandler);
    _server.start();
    assertTrue(contextInit.get());
    _server.stop();
    assertTrue(contextDestroy.get());
  }
コード例 #5
0
  public static void main(String[] args) throws Exception {
    int port = 8080;
    if (args.length == 1) {
      String portString = args[0];
      port = Integer.valueOf(portString);
    }

    System.out.append("Starting at port: ").append(String.valueOf(port)).append('\n');

    AccountService accountService = new AccountService();

    Servlet frontend = new Frontend();
    Servlet auth = new AuthServlet(accountService);
    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(frontend), "/api/v1/auth/signin");
    context.addServlet(new ServletHolder(auth), "/auth/*");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase("public_html");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, context});
    server.setHandler(handlers);

    server.start();
    server.join();
  }
コード例 #6
0
ファイル: DartServer.java プロジェクト: swarupsahoo/dart
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      throw new RuntimeException("Expected >=1 command line arguments");
    }
    String sourceDir = args[0];
    logger.log(Level.INFO, "Source directory: " + sourceDir);

    int port = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    Server server = new Server(port);

    ServletContextHandler servletHandler =
        new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletHandler.setContextPath("/");
    servletHandler.addServlet(ProxyingServlet.class, "/mirror");
    servletHandler.addServlet(AwtThumbnailServlet.class, "/thumb");
    servletHandler.addServlet(OAuthServlet.class, "/oauth");

    final ResourceHandler fileServlet = new ResourceHandler();
    fileServlet.setResourceBase(sourceDir);
    fileServlet.setDirectoriesListed(true);
    // Don't let the corp proxy cache content served out of the filesystem,
    // since we expect this may be used by a developer who's modifying it.
    fileServlet.setCacheControl("no-cache");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(
        new Handler[] {
          fileServlet, servletHandler, new DartHandler(sourceDir), new DefaultHandler()
        });
    server.setHandler(handlers);

    System.out.println("Sample dart apps served at:\n" + "http://localhost:" + port + "/samples/");
    server.start();
    server.join();
  }
コード例 #7
0
ファイル: WebServiceEngine.java プロジェクト: eowyn36/A-CMAv2
  private void initialize(int port) throws Exception {
    System.out.println("Starting web server...");

    webServer = new Server(port);

    ServletContextHandler requestHandler = new ServletContextHandler();
    requestHandler.setContextPath("/");
    requestHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    requestHandler.addServlet(new ServletHolder(new RequestServlet()), "/xmlrpc/*");

    ServletContextHandler uploadHandler = new ServletContextHandler();
    uploadHandler.setContextPath("/upload");
    uploadHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    uploadHandler.addFilter(MultiPartFilter.class, "/", FilterMapping.ALL);
    uploadHandler.addServlet(new ServletHolder(new DesignUploadServlet()), "/");

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(false);
    resourceHandler.setResourceBase("./web");
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});

    HandlerList handlers = new HandlerList();
    handlers.addHandler(requestHandler);
    handlers.addHandler(uploadHandler);
    handlers.addHandler(resourceHandler);

    webServer.setHandler(handlers);
  }
コード例 #8
0
  @Test
  public void test() throws Exception {
    // Create a basic Jetty server object that will listen on port 8080.  Note that if you set this
    // to port 0
    // then a randomly available port will be assigned that you can either look in the logs for the
    // port,
    // or programmatically obtain it for use in test cases.
    Server server = new Server(8080);

    // Create the ResourceHandler. It is the object that will actually handle the request for a
    // given file. It is
    // a Jetty Handler object so it is suitable for chaining with other handlers as you will see in
    // other examples.
    ResourceHandler resource_handler = new ResourceHandler();
    // Configure the ResourceHandler. Setting the resource base indicates where the files should be
    // served out of.
    // In this example it is the current directory but it can be configured to anything that the jvm
    // has access to.
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase("C:\\work\\wget_files");

    // Add the ResourceHandler to the server.
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, new DefaultHandler()});
    server.setHandler(handlers);

    // Start things up! By using the server.join() the server thread will join with the current
    // thread.
    // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more
    // details.
    server.start();
    server.join();
  }
コード例 #9
0
  public void applyHandle(Boolean warDeployFlag) {
    if (StringUtils.isBlank(webDefault)) {
      webDefault = "org.eclipse.jetty.webapp.webdefault.xml";
    }

    // contexts handler
    ContextHandlerCollection contexthandler = new ContextHandlerCollection();

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    webapp.setDefaultsDescriptor(webDefault);
    webapp.setTempDirectory(new File(warTmp));

    // webapp.setParentLoaderPriority(true);
    if (!warDeployFlag) {
      webapp.setResourceBase(resourceBase);
      webapp.setDescriptor(webXmlPath);
    } else {
      webapp.setWar(warPath);
    }

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(resourceBase);

    contexthandler.setHandlers(
        new Handler[] {
          webapp, resource_handler, new DefaultHandler(), new StatisticsHandler(), new GzipHandler()
        });

    super.setHandler(contexthandler);
  }
コード例 #10
0
 private ResourceHandler buildStaticResourcesHandler() {
   ResourceHandler staticHandler = new ResourceHandler();
   URL staticResources = TestWebServer.class.getClassLoader().getResource("website/static");
   staticHandler.setResourceBase(staticResources.toExternalForm());
   staticHandler.setWelcomeFiles(new String[] {"index.html"});
   staticHandler.setDirectoriesListed(false);
   return staticHandler;
 }
コード例 #11
0
 @BeforeClass
 public static void setup() throws Exception {
   server.setStopAtShutdown(true);
   ResourceHandler handler = new ResourceHandler();
   handler.setBaseResource(Resource.newClassPathResource("/ontologies/import/"));
   server.setHandler(handler);
   server.start();
 }
コード例 #12
0
ファイル: JettyServer.java プロジェクト: angelndevil2/LoadT
  public void run() {

    Properties jettyProperties = new Properties();
    String pFileName = PropertiesUtil.getJettyPropertiesFile();
    try {
      jettyProperties.load(new FileInputStream(pFileName));
    } catch (IOException e) {
      log.error("load properties from {} error.", pFileName);
      return;
    }

    // crate server
    server = new Server(Integer.parseInt(jettyProperties.getProperty(PropList.HTTP_PORT)));

    // Create the ResourceHandler. It is the object that will actually handle the request for a
    // given file. It is
    // a Jetty Handler object so it is suitable for chaining with other handlers as you will see in
    // other examples.
    ResourceHandler resource_handler = new ResourceHandler();
    // Configure the ResourceHandler. Setting the resource base indicates where the files should be
    // served out of.
    // In this example it is the current directory but it can be configured to anything that the jvm
    // has access to.
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(PropertiesUtil.getWebBaseDir());

    log.debug(PropertiesUtil.getWebBaseDir());

    // Add a single handler on context "/hello"
    ContextHandler context = new ContextHandler();
    context.setContextPath("/LoadT");
    context.setHandler(new LoadTHandler());

    // Add the ResourceHandler to the server.
    GzipHandler gzip = new GzipHandler();
    server.setHandler(gzip);

    // make handler chain
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, context, new DefaultHandler()});
    gzip.setHandler(handlers);

    try {
      server.start();
    } catch (Exception e) {
      log.error("embedded jetty server start error.", e);
    }

    server.dumpStdErr();

    /*
    try {
        server.join();
    } catch (InterruptedException e) {
        log.info("jetty server interrupted", e);
    }*/
  }
コード例 #13
0
  public void staticResources(String resourceBase) {
    ResourceHandler extResourceHandler = new ResourceHandler();
    extResourceHandler.setResourceBase(resourceBase);
    extResourceHandler.setWelcomeFiles(new String[] {"index.html"});
    extResourceHandler.setDirectoriesListed(true);

    ContextHandler contextHandler = new ContextHandler(rootContext);
    contextHandler.setHandler(extResourceHandler);

    handlerList.add(contextHandler);
  }
コード例 #14
0
  private void run() throws Exception {

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase("web");

    Server server = new Server(8080);

    server.setHandler(resourceHandler);

    server.start();
    server.join();
  }
コード例 #15
0
  /*
   * 启动Jetty的Web服务器功能
   */
  private static void startJettyWebServer() throws Exception {
    Server server = new Server(8080);

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase("/home");

    server.setHandler(resourceHandler);
    resourceHandler.setDirectoriesListed(true);

    server.start();

    log.info("Jetty Start Up Successfully :D");
  }
コード例 #16
0
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpServletRequestWrapper modifiedRequest =
        new HttpServletRequestWrapper(request) { // Prevent NOT_MODIFIED_SINCE 304 response
          private static final long WAS_MODIFIED = -1;

          @Override
          public long getDateHeader(String name) {
            HttpServletRequest request = (HttpServletRequest) getRequest();

            if (HttpHeaders.IF_MODIFIED_SINCE.equals(name)) {
              return WAS_MODIFIED;
            }
            return request.getDateHeader(name);
          };
        };

    HttpServletResponseWrapper modifiedResponce =
        new HttpServletResponseWrapper(response) { // Prevent "if-modified-since" headers handling

          @Override
          public void setDateHeader(String name, long date) {}
        };

    super.handle(target, baseRequest, modifiedRequest, modifiedResponce);
  }
コード例 #17
0
ファイル: SplitFileServer.java プロジェクト: Nextzero/Jetty
  public static void main(String[] args) throws Exception {
    // Create the Server object and a corresponding ServerConnector and then set the port for the
    // connector. In
    // this example the server will listen on port 8090. If you set this to port 0 then when the
    // server has been
    // started you can called connector.getLocalPort() to programmatically get the port the server
    // started on.
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8090);
    server.setConnectors(new Connector[] {connector});

    // Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path
    // but this could
    // be anything you like for builing out your url. Note how we are setting the ResourceBase using
    // our jetty
    // maven testing utilities to get the proper resource directory, you needn't use these,
    // you simply need to supply the paths you are looking to serve content from.
    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/");
    ResourceHandler rh0 = new ResourceHandler();
    rh0.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0")));
    context0.setHandler(rh0);

    // Rinse and repeat the previous item, only specifying a different resource base.
    ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    ResourceHandler rh1 = new ResourceHandler();
    rh1.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1")));
    context1.setHandler(rh1);

    // Create a ContextHandlerCollection and set the context handlers to it. This will let jetty
    // process urls
    // against the declared contexts in order to match up content.
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {context0, context1});

    server.setHandler(contexts);

    // Start things up! By using the server.join() the server thread will join with the current
    // thread.
    // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more
    // details.
    server.start();
    System.err.println(server.dump());
    server.join();
  }
コード例 #18
0
ファイル: StaticHttpServer.java プロジェクト: Cloudname/copkg
  /**
   * Populate the server with handlers and start it.
   *
   * @throws Exception if unable to set up and start Jetty server.
   */
  public void start() throws Exception {
    final SocketConnector connector = new SocketConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    // Configure a basic resource handler.
    ResourceHandler rh = new ResourceHandler();
    rh.setDirectoriesListed(true);
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(staticResourcePath);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {rh, new DefaultHandler()});
    server.setHandler(handlers);

    server.start();
  }
コード例 #19
0
  @Before
  public void startHttp() throws Exception {
    server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8778);
    server.addConnector(connector);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(false);
    resource_handler.setWelcomeFiles(new String[] {});

    resource_handler.setResourceBase("target/test-classes/repo2");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, new DefaultHandler()});
    server.setHandler(handlers);

    server.start();
  }
コード例 #20
0
  @BeforeClass
  public static void setUpFakeMavenRepo() throws Exception {
    repo = TestDataHelper.getTestDataDirectory(new ResolverIntegrationTest());
    // If we're running this test in IJ, then this path doesn't exist. Fall back to one that does
    if (!Files.exists(repo)) {
      repo = Paths.get("test/com/facebook/buck/maven/testdata");
    }

    httpd = new HttpdForTests();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase(repo.toAbsolutePath().toString());

    ContextHandler contextHandler = new ContextHandler("/");
    contextHandler.setHandler(resourceHandler);
    contextHandler.setLogger(new StdErrLog());

    httpd.addHandler(contextHandler);
    httpd.start();
  }
コード例 #21
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    int options = ServletContextHandler.NO_SECURITY;
    ServletContextHandler context = new ServletContextHandler(server, "/", options);

    FilterHolder filter = new FilterHolder(LoggerFilter.class);
    FilterHolder filter2 = new FilterHolder(PreParseFilter.class);
    context.addFilter(filter, "/*", null);
    context.addFilter(filter2, "/*", null);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});

    resource_handler.setResourceBase(".");

    context.addServlet("DummyServlet", "/*");

    server.start();
    server.join();
  }
コード例 #22
0
  private void addResourceHandler(String contextPath, String filePath) throws Exception {
    if (handlerCollection != null) {
      logger.log(Level.INFO, "Adding resource : " + contextPath + "=>" + filePath);

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

      logger.log(Level.INFO, "serving: " + resourceHandler.getBaseResource());

      ContextHandler contextHandler = new ContextHandler(contextPath);
      contextHandler.setHandler(resourceHandler);

      handlerCollection.addHandler(contextHandler);

      try {
        resourceHandler.start();
        contextHandler.start();
      } catch (Exception e) {
        logger.log(Level.INFO, "Could not start resource context", e);
      }
    }
  }
コード例 #23
0
ファイル: Main.java プロジェクト: Atarki/Web-Service
  public static void main(String[] args) throws Exception {
    AccountService accountService = new AccountService();

    accountService.addNewUser(new UserProfile("admin"));
    accountService.addNewUser(new UserProfile("Test"));

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new UsersServlet(accountService)), "/users");
    context.addServlet(new ServletHolder(new SessionsServlet(accountService)), "/sessions");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setResourceBase("templates/lab2/public");

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

    Server server = new Server(8080);
    server.setHandler(handlers);

    server.start();
    server.join();
  }
コード例 #24
0
ファイル: Registry.java プロジェクト: Gastmeier/justweb
  public Server jettyServer() {
    if (jettyServer == null) {
      jettyServer = new Server();
      ServerConnector connector = new ServerConnector(jettyServer);
      connector.setHost(settings.serverHost());
      connector.setPort(settings.serverPort());
      connector.setIdleTimeout(settings.serverIdleTimeout());
      jettyServer.addConnector(connector);

      JettyHandler appHandler = jettyHandler();

      ResourceHandler resourceHandler = new ResourceHandler();
      resourceHandler.setResourceBase(settings.assetsPath());

      HandlerList handlers = new HandlerList();
      handlers.setHandlers(new Handler[] {appHandler, resourceHandler});

      jettyServer.setHandler(handlers);
    }

    return jettyServer;
  }
コード例 #25
0
ファイル: Main.java プロジェクト: mioxin/w03j
  public static void main(String[] args) {
    DBService dbService = new DBService();
    dbService.printConnectInfo();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    //        context.setContextPath("/");
    //        context.addServlet(new ServletHolder(new MainServlet()), "/");
    context.addServlet(new ServletHolder(new SignUpServlet(dbService)), "/signup");
    context.addServlet(new ServletHolder(new SignInServlet(dbService)), "/signin");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setResourceBase("./public_html");

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

    Server server = new Server(8080);
    server.setHandler(handlers);

    try {
      long userId = dbService.addUser("test1", "test1");
      System.out.println("Added user id: " + userId);

      UsersDataSet dataSet = dbService.getUser(userId);
      System.out.println("User data set: " + dataSet);

      //            dbService.cleanUp();
    } catch (DBException e) {
      e.printStackTrace();
    }
    try {
      server.start();
      System.out.println("Server started");
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #26
0
ファイル: WebServer.java プロジェクト: DMDirc/Plugins
  public void start() {
    server = new Server(port);

    // Override the context classloader, so that Jetty uses the plugin classloader not the main
    // DMDirc loader.
    final Thread currentThread = Thread.currentThread();
    final ClassLoader classLoader = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(getClass().getClassLoader());

    try {
      final ResourceHandler resourceHandler = new ResourceHandler();
      resourceHandler.setWelcomeFiles(new String[] {"index.html"});
      resourceHandler.setBaseResource(Resource.newClassPathResource("/www"));

      final ResourceHandler clientResourceHandler = new ResourceHandler();
      clientResourceHandler.setBaseResource(Resource.newClassPathResource("/com/dmdirc/res/"));
      final ContextHandler clientResourceContext = new ContextHandler("/res");
      clientResourceContext.setHandler(clientResourceHandler);

      final ServletContextHandler wsHandler = new ServletContextHandler();
      wsHandler.setContextPath("/");
      wsHandler.addServlet(WebUiWebSocketServlet.class, "/ws");

      HandlerList handlers = new HandlerList();
      handlers.setHandlers(
          new Handler[] {resourceHandler, clientResourceContext, wsHandler, new DefaultHandler()});
      server.setHandler(handlers);

      server.start();
    } catch (Exception ex) {
      LOG.error(LogUtils.USER_ERROR, "Unable to start web server", ex);
      server = null;
    } finally {
      // Restore the usual context class loader.
      currentThread.setContextClassLoader(classLoader);
    }
  }
コード例 #27
0
 @Override
 public void handle(
     String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   final String suffix = RequestPath.suffix(target);
   final String path = path(suffix);
   if (!paths.contains(path)) {
     if (!whitelist.contains(suffix)) return;
     if (!"GET".equals(baseRequest.getMethod()))
       baseRequest.setMethod(HttpMethod.GET, HttpMethod.GET.toString());
     super.handle(target, baseRequest, request, allowCrossOrigin(response));
   } else {
     baseRequest
         .getContext()
         .getContext(path)
         .getRequestDispatcher(target)
         .forward(request, allowCrossOrigin(response));
   }
 }
コード例 #28
0
ファイル: BaseTest.java プロジェクト: jasonobrien/antlr4
 @Override
 public void run() {
   try {
     Server server = new Server(httpPort);
     ResourceHandler rh1 = new ResourceHandler();
     rh1.setDirectoriesListed(false);
     rh1.setResourceBase(httpdir);
     rh1.setWelcomeFiles(new String[] {fileName});
     ResourceHandler rh2 = new ResourceHandler();
     rh2.setDirectoriesListed(false);
     rh2.setResourceBase(runtimePath);
     HandlerList handlers = new HandlerList();
     handlers.setHandlers(new Handler[] {rh1, rh2, new DefaultHandler()});
     server.setHandler(handlers);
     server.start();
     this.server = server;
     this.server.join();
   } catch (BindException e) {
     httpPort++;
     run();
   } catch (Exception e) {
     ex = e;
   }
 }
コード例 #29
0
ファイル: Jetty.java プロジェクト: LiuQ1ang/jrds
  public void start(String args[]) {
    Logger.getRootLogger().setLevel(Level.ERROR);

    PropertiesManager pm = new PropertiesManager();
    File propFile = new File(propFileName);
    if (propFile.isFile()) pm.join(propFile);
    pm.importSystemProps();
    try {
      pm.update();
    } catch (IllegalArgumentException e) {
      System.err.println("invalid configuration, can't start: " + e.getMessage());
      System.exit(1);
    }

    if (pm.withjmx) {
      doJmx(pm);
    }

    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");

    final Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    if (host != null) {
      connector.setHost(host);
    }
    connector.setPort(port);

    // Let's try to start the connector before the application
    try {
      connector.open();
    } catch (IOException e) {
      connector.close();
      throw new RuntimeException("Jetty server failed to start", e);
    }
    server.setConnectors(new Connector[] {connector});

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setResourceBase(webRoot);
    webapp.setClassLoader(getClass().getClassLoader());
    webapp.setInitParameter("propertiesFile", propFileName);

    ResourceHandler staticFiles = new ResourceHandler();
    staticFiles.setWelcomeFiles(new String[] {"index.html"});
    staticFiles.setResourceBase(webRoot);

    if (pm.security) {
      LoginService loginService = new HashLoginService("jrds", pm.userfile);
      server.addBean(loginService);

      Authenticator auth = new BasicAuthenticator();
      Constraint constraint = new Constraint();
      constraint.setName("jrds");
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});
      constraint.setAuthenticate(true);
      constraint.setDataConstraint(Constraint.DC_NONE);

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

      ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
      sh.setConstraintMappings(Collections.singletonList(cm));
      sh.setAuthenticator(auth);
      webapp.setSecurityHandler(sh);
    }

    HandlerCollection handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {staticFiles, webapp});
    server.setHandler(handlers);

    if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) {
      MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer();
      server.addBean(new MBeanContainer(mbs));
      handlers.addHandler(new StatisticsHandler());
    }

    // Properties are not needed any more
    pm = null;

    Thread finish =
        new Thread() {
          public void run() {
            try {
              server.stop();
            } catch (Exception e) {
              throw new RuntimeException("Jetty server failed to stop", e);
            }
          }
        };
    Runtime.getRuntime().addShutdownHook(finish);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      throw new RuntimeException("Jetty server failed to start", e);
    }
  }
コード例 #30
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }