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();
  }
  @Override
  public void run() {
    Server server = new Server(new QueuedThreadPool(maxThreads, 8, (int) idleTimeout, queue));
    ServerConnector connector = new ServerConnector(server, acceptors, selectors);
    connector.setIdleTimeout(idleTimeout);
    connector.setPort(port);
    connector.setHost(host);
    connector.setName("Continuum Ingress");

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

    HandlerList handlers = new HandlerList();

    Handler cors = new CORSHandler();
    handlers.addHandler(cors);

    handlers.addHandler(new InfluxDBHandler(url, token));

    server.setHandler(handlers);

    JettyUtil.setSendServerVersion(server, false);

    try {
      server.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 3
0
  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);
  }
Exemplo n.º 4
0
  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);
  }
Exemplo n.º 5
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();
  }
Exemplo n.º 6
0
  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();
  }
Exemplo n.º 7
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

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

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

    webApiContext.addServlet(new ServletHolder(AppTokenServer.class), "/sts/*");
    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/callback/*");
    webApiContext.addServlet(new ServletHolder(PostObjectPolicy.class), "/get-post-policy/*");

    //    webApiContext.addServlet(new ServletHolder(STSToken.class), "/2/*");
    //    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/3/*");
    //    webApiContext.addServlet(new ServletHolder(DownloadApi.class), "/download/*");
    webApiContext.setSessionHandler(new SessionHandler());

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

    server.setHandler(handlers);
    server.start();
    server.join();
  }
  @Test
  public void testFallThrough() throws Exception {
    HandlerList list = new HandlerList();
    _server.setHandler(list);

    ServletContextHandler root =
        new ServletContextHandler(list, "/", ServletContextHandler.SESSIONS);

    ServletHandler servlet = root.getServletHandler();
    servlet.setEnsureDefaultServlet(false);
    servlet.addServletWithMapping(HelloServlet.class, "/hello/*");

    list.addHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.sendError(404, "Fell Through");
          }
        });

    _server.start();

    String response = _connector.getResponses("GET /hello HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("200 OK"));

    response = _connector.getResponses("GET /other HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("404 Fell Through"));
  }
  @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;
    }
  }
Exemplo n.º 10
0
  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);
    }*/
  }
Exemplo n.º 11
0
  private Handler handlers() {
    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[] {webAppHandler()});

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.addHandler(handlerList);

    return handlerCollection;
  }
Exemplo n.º 12
0
  /** Constructor. */
  public TestWebServer() {

    // initRuntimeConfiguration();

    WebAppContext webappContext = buildWebappContext();
    ResourceHandler staticHandler = buildStaticResourcesHandler();

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

    initHttpConnector();
  }
  public static void createServlets(DBService dbService) throws Exception {

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new SignUpServlet(dbService)), "/signup");
    context.addServlet(new ServletHolder(new SignInServlet(dbService)), "/signin");

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

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

    server.start();
    System.out.println("Server started");
    server.join();
  }
Exemplo n.º 14
0
 public void start(int port) throws Exception {
   LOG.warn("Port used: " + port + " location " + WEBAPP_LOCATION + " " + databaseInfo.toString());
   server = new Server(port);
   WebAppContext root = new WebAppContext();
   root.setContextPath("/");
   root.setDescriptor(WEBAPP_LOCATION + "/WEB-INF/web.xml");
   root.setResourceBase(WEBAPP_LOCATION);
   root.setParentLoaderPriority(true);
   root.setAttribute(BackendFilter.DATABASE_ATTRIBUTE, databaseInfo);
   //        setupRequestLimits(root, REQUEST_TIME_LIMIT, MAX_OPS_LIMIT);
   final HandlerList handlers = new HandlerList();
   final Handler resourceHandler = createResourceHandler("/console_assets", WEBAPP_LOCATION);
   handlers.setHandlers(new Handler[] {resourceHandler, root});
   server.setHandler(handlers);
   server.start();
 }
Exemplo n.º 15
0
  /**
   * 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();
  }
Exemplo n.º 16
0
  public void start() throws Exception {
    server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    configureRequestLogImpl();
    requestLogHandler.setRequestLog(requestLogImpl);

    HandlerList handlers = new HandlerList();
    handlers.addHandler(requestLogHandler);
    handlers.addHandler(getRequestHandler());

    server.setHandler(handlers);
    server.start();
  }
Exemplo n.º 17
0
  private Server createNewServer(String[] args) {
    int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT;

    Enviroment env = args.length > 0 ? Enviroment.valueOf(args[1]) : Enviroment.desa;

    WebAppContext webHandler = this.buildWebAppContext(args, env);

    HandlerList handlers = new HandlerList();
    handlers.addHandler(webHandler);

    Server server = new Server(port);
    server.setHandler(handlers);
    server.setStopAtShutdown(true);

    TimeZone.setDefault(TimeZone.getTimeZone("GMT"));

    return server;
  }
  @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();
  }
Exemplo n.º 19
0
  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;
  }
Exemplo n.º 20
0
  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();
  }
Exemplo n.º 21
0
  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);
    }
  }
Exemplo n.º 22
0
  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();
    }
  }
Exemplo n.º 23
0
 @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;
   }
 }
  public static void setupProxy() throws Exception {
    proxy = new Server();
    ServerConnector proxyConnector = new ServerConnector(proxy);
    proxyConnector.setPort(0);
    proxy.setConnectors(new Connector[] {proxyConnector});

    ServletHandler proxyHandler = new ServletHandler();

    RequestHandler proxyCountingHandler =
        new RequestHandler() {

          @Override
          public void handle(Request request, HttpServletResponse response) {
            proxyHitCount.incrementAndGet();
            String auth = request.getHeader("Proxy-Authorization");
            auth = auth.substring(auth.indexOf(' ') + 1);
            auth = B64Code.decode(auth, CHARSET_UTF8);
            int colon = auth.indexOf(':');
            proxyUser.set(auth.substring(0, colon));
            proxyPassword.set(auth.substring(colon + 1));
            request.setHandled(false);
          }
        };

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(proxyCountingHandler);
    handlerList.addHandler(proxyHandler);
    proxy.setHandler(handlerList);

    ServletHolder proxyHolder =
        proxyHandler.addServletWithMapping("org.eclipse.jetty.proxy.ProxyServlet", "/");
    proxyHolder.setAsyncSupported(true);

    proxy.start();
    proxyPort = proxyConnector.getLocalPort();
  }
Exemplo n.º 25
0
  public static void main(String[] args) throws Exception {

    // When run from app-runner, you must use the port set in the environment variable web.port
    int port = Integer.parseInt(firstNonNull(System.getenv("web.port"), "8080"));
    InetSocketAddress addr = new InetSocketAddress("localhost", port);
    Server jettyServer = new Server(addr);
    jettyServer.setStopAtShutdown(true);

    HandlerList handlers = new HandlerList();
    // TODO: set your own handlers
    handlers.addHandler(resourceHandler());

    // you must serve everything from a directory named after your app
    ContextHandler ch = new ContextHandler();
    ch.setContextPath("/maven");
    ch.setHandler(handlers);
    jettyServer.setHandler(ch);

    jettyServer.start();

    log.info("Started app at http://localhost:" + port + ch.getContextPath());

    jettyServer.join();
  }
Exemplo n.º 26
0
  public static void main(String[] args) throws Exception {

    // load main configuration
    String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT);
    System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc);
    Properties configProps = new Properties();
    try {
      configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc)));
      logger.info("Successfully loaded main configuration.");
    } catch (Exception ex) {
      logger.error("Fail to start in early part", ex);
      throw ex;
    }
    Config config = new Config(configProps);

    // load log4j configuration
    // @todo review the effect and final configuration when -Dlog4j.properties is specified with
    // command line
    String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION);
    if (log4jConfigLoc != null) {
      Properties log4jConfig = new Properties();

      try {
        log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc)));
        org.apache.log4j.LogManager.resetConfiguration();
        org.apache.log4j.PropertyConfigurator.configure(log4jConfig);
        logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc);
      } catch (Exception ex) {
        logger.error("Faile to load specified log4j configuration", ex);
        throw ex;
      }
    }

    ServletContextHandler sch =
        new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS);

    sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH));
    sch.getSessionHandler()
        .getSessionManager()
        .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID));

    ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/");
    dsh.setInitOrder(1);

    ServletHolder jsh = new ServletHolder(JerseySpringServlet.class);
    jsh.setInitParameter(
        JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION,
        config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION));
    // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html
    jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true");
    // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");

    sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN));
    jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER));

    // For more, refer
    // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html
    FilterHolder fh = new FilterHolder(CrossOriginFilter.class);
    fh.setName("crossOriginFilter");
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_METHODS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_HEADERS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS));
    sch.addFilter(fh, "/*", FilterMapping.DEFAULT);

    Server jetty = new Server();
    HandlerList hl = new HandlerList();
    hl.addHandler(sch);
    jetty.setHandler(hl);
    jetty.setThreadPool(
        new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE)));

    SelectChannelConnector conn = new SelectChannelConnector();
    conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT));
    conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME));

    MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty");
    jetty.getContainer().addEventListener(mbc);
    jetty.addBean(mbc);

    jetty.addConnector(conn);
    jetty.setStopAtShutdown(true);

    try {
      jetty.start();
      logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1");
    } catch (Exception ex) {
      logger.error("Fail to start Jetty.", ex);
      System.exit(-1);
    }
  }
  public ServerMain(String configDir) throws Exception {

    config = Util.getConfig(configDir);
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("Freeboard starting....");

    // do we have a USB drive connected?
    logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();

    // enable hangup support which mean we detect when the JVM terminates, and stop Camel graceful
    main.enableHangupSupport();

    NavDataWebSocketRoute route = new NavDataWebSocketRoute(config);
    // must do this early!
    CamelContextFactory.setContext(route);
    // web socket on port 9090
    logger.info("  Websocket port:" + config.getProperty(Constants.WEBSOCKET_PORT));
    route.setPort(Integer.valueOf(config.getProperty(Constants.WEBSOCKET_PORT)));

    // are we running demo?
    logger.info("  Serial url:" + config.getProperty(Constants.SERIAL_URL));
    route.setSerialUrl(config.getProperty(Constants.SERIAL_URL));

    // add our routes to Camel
    main.addRouteBuilder(route);

    Connector connector = new SelectChannelConnector();
    logger.info("  Webserver http port:" + config.getProperty(Constants.HTTP_PORT));
    connector.setPort(Integer.valueOf(config.getProperty(Constants.HTTP_PORT)));

    // virtual hosts
    String virtualHosts = config.getProperty(Constants.VIRTUAL_URL);
    server = new Server();
    server.addConnector(connector);

    // serve mapcache
    ServletContextHandler mapContext = new ServletContextHandler();
    logger.info("  Mapcache url:" + config.getProperty(Constants.MAPCACHE));
    mapContext.setContextPath(config.getProperty(Constants.MAPCACHE));
    logger.info("  Mapcache resource:" + config.getProperty(Constants.MAPCACHE_RESOURCE));
    mapContext.setResourceBase(config.getProperty(Constants.MAPCACHE_RESOURCE));
    ServletHolder mapHolder = mapContext.addServlet(DefaultServlet.class, "/*");
    mapHolder.setInitParameter("cacheControl", "max-age=3600,public");

    // serve tracks
    ServletContextHandler trackContext = new ServletContextHandler();
    logger.info("  Tracks url:" + config.getProperty(Constants.TRACKS));
    trackContext.setContextPath(config.getProperty(Constants.TRACKS));
    logger.info("  Tracks resource:" + config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.setResourceBase(config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.addServlet(DefaultServlet.class, "/*");

    if (StringUtils.isNotBlank(virtualHosts)) {
      mapContext.setVirtualHosts(virtualHosts.split(","));
      trackContext.setVirtualHosts(virtualHosts.split(","));
    }
    HandlerList handlers = new HandlerList();
    handlers.addHandler(mapContext);
    handlers.addHandler(trackContext);

    // serve freeboard
    WebAppContext wac = new WebAppContext();
    logger.info("  Freeboard resource:" + config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setWar(config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setDefaultsDescriptor(
        config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/webdefault.xml");

    wac.setDescriptor(config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/web.xml");
    logger.info("  Freeboard url:" + config.getProperty(Constants.FREEBOARD_URL));
    wac.setContextPath(config.getProperty(Constants.FREEBOARD_URL));
    wac.setServer(server);
    wac.setParentLoaderPriority(true);
    wac.setVirtualHosts(null);
    if (StringUtils.isNotBlank(virtualHosts)) {
      wac.setVirtualHosts(virtualHosts.split(","));
    }
    handlers.addHandler(wac);

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

    // and run, which keeps blocking until we terminate the JVM (or stop CamelContext)
    main.run();

    // so now shutdown serial reader and server

    route.stopSerial();
    server.stop();
    System.exit(0);
  }
Exemplo n.º 28
0
  /** @param args Not used */
  public static void main(final String[] args) {
    LOG.info("Starting service");

    final Properties velocityConfig = new Properties();
    try {
      velocityConfig.load(Start.class.getResourceAsStream("/velocity.properties"));
    } catch (final IOException e1) {
      LOG.error("Cannot read velocity config", e1);
      error("Internal error. Check the logs!");
    }
    Velocity.init(velocityConfig);

    FileReader r;
    try {
      r = new FileReader(new File("config.properties"));
    } catch (final FileNotFoundException e1) {
      error("Missing config file (./config.properties) See config.sample.properties!");
      throw new RuntimeException(e1);
    }

    //
    // Read configuration
    //
    final Properties config = new Properties();
    try {
      config.load(r);
    } catch (final IOException e1) {
      error("Error reading config file (./config.properties)");
      throw new RuntimeException(e1);
    }

    /* *****************************************************
     *
     * HTTP Client
     */

    // httpclient.host
    // Active Collab API host
    String apiHost = config.getProperty("httpclient.apihost");
    if (null == apiHost || apiHost.isEmpty()) {
      error("Missing parameter: 'apihost'");
    }
    if (apiHost.endsWith("/")) {
      apiHost = apiHost.substring(0, apiHost.length() - 1);
    }

    // create client
    final ACHttpClient client =
        new ACHttpClient(
            apiHost,
            getIntValue(config, "httpclient.maxConnections", "20"),
            getIntValue(config, "httpclient.threadPoolSize", "100"),
            true);

    /* *****************************************************
     *
     * Task cache
     */

    // init caches
    TaskCache.init(client);
    CompanyCache.init(
        client,
        getLongValue(config, "cache.company.timeout", "1800000"),
        getLongValue(config, "cache.company.size", "5000"));
    ProjectCache.init(client);

    // creating handlers
    final HandlerList hc = new HandlerList();

    // cookie handling
    hc.addHandler(new FileServerHandler());

    // cookie handling
    hc.addHandler(new ApiKeyCheckerHandler(client));

    // handler for project list
    hc.addHandler(new ProjectListHandler(client));

    // handler for project home
    hc.addHandler(new ProjectHomeHandler());

    // creating the server
    final Server server = new Server(getIntValue(config, "server.port", "8080"));
    server.setHandler(hc);

    try {
      server.start();
    } catch (final Exception e) {
      LOG.error("Cannot start web server", e);
      System.exit(1);
    }
    try {
      server.join();
    } catch (final InterruptedException e) {
      LOG.error("Cannot join web server", e);
      System.exit(2);
    }

    LOG.info("Service stopped");
  }
Exemplo n.º 29
0
  protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
      server = new Server();
      final SslContextFactory factory = new SslContextFactory(config.keystore());
      factory.setKeyStorePath(config.keystore());
      factory.setKeyStorePassword(config.keystorePassword());
      factory.setKeyManagerPassword(config.keyPassword());
      factory.setTrustStore(config.keystore());
      factory.setTrustStorePassword(config.keystorePassword());

      final SslSocketConnector connector = new SslSocketConnector(factory);
      connector.setPort(config.port());
      server.setConnectors(new Connector[] {connector});
    } else {
      server = new Server(config.port());
    }
    m_server = server;
    final ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    context1.setWelcomeFiles(new String[] {"index.html"});
    context1.setResourceBase(config.resource());
    context1.setClassLoader(Thread.currentThread().getContextClassLoader());
    context1.setVirtualHosts(config.vhosts());

    final ContextHandler context = context1;

    Handler topLevelHandler = null;
    final HandlerList handlers = new HandlerList();

    if (config.basicAuth()) {
      // check for basic auth if we're configured to do so
      LOG.debug("configuring basic auth");

      final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
      loginService.setRefreshInterval(300000);
      m_server.addBean(loginService);

      final ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      final Set<String> knownRoles = new HashSet<String>();
      knownRoles.add("user");
      knownRoles.add("admin");
      knownRoles.add("moderator");

      final Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);
      constraint.setRoles(knownRoles.toArray(new String[0]));

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

      security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);
      security.setStrict(false);
      security.setRealmName("MyRealm");

      security.setHandler(context);
      topLevelHandler = security;
    } else {
      topLevelHandler = context;
    }

    final Webapp[] webapps = config.webapps();
    if (webapps != null) {
      for (final Webapp webapp : webapps) {
        final WebAppContext wac = new WebAppContext();
        String path = null;
        if (!"".equals(webapp.pathSystemProperty())
            && System.getProperty(webapp.pathSystemProperty()) != null) {
          path = System.getProperty(webapp.pathSystemProperty());
        } else {
          path = webapp.path();
        }
        if (path == null || "".equals(path)) {
          throw new IllegalArgumentException(
              "path or pathSystemProperty of @Webapp points to a null or blank value");
        }
        wac.setWar(path);
        wac.setContextPath(webapp.context());
        handlers.addHandler(wac);
      }
    }

    final ResourceHandler rh = new ResourceHandler();
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(config.resource());
    handlers.addHandler(rh);

    // fall through to default
    handlers.addHandler(new DefaultHandler());

    context.setHandler(handlers);
    m_server.setHandler(topLevelHandler);
  }
Exemplo n.º 30
0
  static {
    List<String> allowedUserHostsList = Nxt.getStringListProperty("nxt.allowedUserHosts");
    if (!allowedUserHostsList.contains("*")) {
      allowedUserHosts = Collections.unmodifiableSet(new HashSet<>(allowedUserHostsList));
    } else {
      allowedUserHosts = null;
    }

    boolean enableUIServer = Nxt.getBooleanProperty("nxt.enableUIServer");
    if (enableUIServer) {
      final int port =
          Constants.isTestnet ? TESTNET_UI_PORT : Nxt.getIntProperty("nxt.uiServerPort");
      final String host = Nxt.getStringProperty("nxt.uiServerHost");
      userServer = new Server();
      ServerConnector connector;

      boolean enableSSL = Nxt.getBooleanProperty("nxt.uiSSL");
      if (enableSSL) {
        Logger.logMessage("Using SSL (https) for the user interface server");
        HttpConfiguration https_config = new HttpConfiguration();
        https_config.setSecureScheme("https");
        https_config.setSecurePort(port);
        https_config.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(Nxt.getStringProperty("nxt.keyStorePath"));
        sslContextFactory.setKeyStorePassword(
            Nxt.getStringProperty("nxt.keyStorePassword", null, true));
        sslContextFactory.setExcludeCipherSuites(
            "SSL_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_DSS_WITH_DES_CBC_SHA",
            "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
        sslContextFactory.setExcludeProtocols("SSLv3");
        connector =
            new ServerConnector(
                userServer,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(https_config));
      } else {
        connector = new ServerConnector(userServer);
      }

      connector.setPort(port);
      connector.setHost(host);
      connector.setIdleTimeout(Nxt.getIntProperty("nxt.uiServerIdleTimeout"));
      connector.setReuseAddress(true);
      userServer.addConnector(connector);

      HandlerList userHandlers = new HandlerList();

      ResourceHandler userFileHandler = new ResourceHandler();
      userFileHandler.setDirectoriesListed(false);
      userFileHandler.setWelcomeFiles(new String[] {"index.html"});
      userFileHandler.setResourceBase(Nxt.getStringProperty("nxt.uiResourceBase"));

      userHandlers.addHandler(userFileHandler);

      String javadocResourceBase = Nxt.getStringProperty("nxt.javadocResourceBase");
      if (javadocResourceBase != null) {
        ContextHandler contextHandler = new ContextHandler("/doc");
        ResourceHandler docFileHandler = new ResourceHandler();
        docFileHandler.setDirectoriesListed(false);
        docFileHandler.setWelcomeFiles(new String[] {"index.html"});
        docFileHandler.setResourceBase(javadocResourceBase);
        contextHandler.setHandler(docFileHandler);
        userHandlers.addHandler(contextHandler);
      }

      ServletHandler userHandler = new ServletHandler();
      ServletHolder userHolder = userHandler.addServletWithMapping(UserServlet.class, "/nxt");
      userHolder.setAsyncSupported(true);

      if (Nxt.getBooleanProperty("nxt.uiServerCORS")) {
        FilterHolder filterHolder =
            userHandler.addFilterWithMapping(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT);
        filterHolder.setInitParameter("allowedHeaders", "*");
        filterHolder.setAsyncSupported(true);
      }

      userHandlers.addHandler(userHandler);

      userHandlers.addHandler(new DefaultHandler());

      userServer.setHandler(userHandlers);
      userServer.setStopAtShutdown(true);

      ThreadPool.runBeforeStart(
          () -> {
            try {
              userServer.start();
              Logger.logMessage("Started user interface server at " + host + ":" + port);
            } catch (Exception e) {
              Logger.logErrorMessage("Failed to start user interface server", e);
              throw new RuntimeException(e.toString(), e);
            }
          },
          true);

    } else {
      userServer = null;
      Logger.logMessage("User interface server not enabled");
    }
  }