Exemplo n.º 1
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.º 2
0
 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;
 }
  @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.º 4
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);
  }
Exemplo n.º 5
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.º 6
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.º 7
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;
 }
Exemplo n.º 8
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);
    }*/
  }
  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);
  }
Exemplo n.º 10
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();
  }
  @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.º 12
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();
  }
Exemplo n.º 13
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.º 14
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;
   }
 }
Exemplo n.º 15
0
  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);
    }
  }
Exemplo n.º 16
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();
  }
Exemplo n.º 17
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");
    }
  }
Exemplo n.º 18
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);
  }