private static void registerContextHanlder(
     ContextHandlerCollection contextHandlers, String path, AbstractHandler handler) {
   ContextHandler contextHandler = new ContextHandler();
   contextHandler.setContextPath(path);
   contextHandler.setHandler(handler);
   contextHandlers.addHandler(contextHandler);
 }
Пример #2
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    ContextHandler context = new ContextHandler("/");
    context.setContextPath("/");
    context.setHandler(new HelloHandler("Root Hello"));

    ContextHandler contextFR = new ContextHandler("/fr");
    contextFR.setHandler(new HelloHandler("Bonjoir"));

    ContextHandler contextIT = new ContextHandler("/it");
    contextIT.setHandler(new HelloHandler("Bongiorno"));

    ContextHandler contextV = new ContextHandler("/");
    contextV.setVirtualHosts(new String[] {"127.0.0.2"});
    contextV.setHandler(new HelloHandler("Virtual Hello"));

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {context, contextFR, contextIT, contextV});

    server.setHandler(contexts);

    server.start();
    server.join();
  }
Пример #3
0
  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();
  }
Пример #4
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);
    }*/
  }
Пример #5
0
  @BeforeClass
  public static void startServer() {
    _server = new Server();
    _connector = new LocalConnector(_server);
    _server.setConnectors(new Connector[] {_connector});

    ContextHandler _context = new ContextHandler();
    _session = new SessionHandler();

    HashLoginService _loginService = new HashLoginService(TEST_REALM);
    _loginService.putUser("fred", new Password("password"));
    _loginService.putUser("harry", new Password("password"), new String[] {"HOMEOWNER"});
    _loginService.putUser("chris", new Password("password"), new String[] {"CONTRACTOR"});
    _loginService.putUser("steven", new Password("password"), new String[] {"SALESCLERK"});

    _context.setContextPath("/ctx");
    _server.setHandler(_context);
    _context.setHandler(_session);

    _server.addBean(_loginService);
  }
Пример #6
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();
  }
Пример #7
0
 private ContextHandler systemRestart() {
   AbstractHandler system =
       new AbstractHandler() {
         @Override
         public void handle(
             String target,
             Request baseRequest,
             HttpServletRequest request,
             HttpServletResponse response)
             throws IOException, ServletException {
           restartContexts();
           response.setContentType("text/html;charset=utf-8");
           response.setStatus(HttpServletResponse.SC_OK);
           baseRequest.setHandled(true);
           response.getWriter().println("<h1>Done</h1>");
         }
       };
   ContextHandler context = new ContextHandler();
   context.setContextPath("/vraptor/restart");
   context.setResourceBase(".");
   context.setClassLoader(Thread.currentThread().getContextClassLoader());
   context.setHandler(system);
   return context;
 }
    public void configureContextHandler() throws Exception {
      if (_configured) return;

      _configured = true;

      // Override for bundle root may have been set
      String bundleOverrideLocation =
          (String) _properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE);
      if (bundleOverrideLocation == null)
        bundleOverrideLocation =
            (String)
                _properties.get(OSGiWebappConstants.SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE);

      // Location on filesystem of bundle or the bundle override location
      File bundleLocation =
          BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle);
      File root =
          (bundleOverrideLocation == null ? bundleLocation : new File(bundleOverrideLocation));
      Resource rootResource =
          Resource.newResource(
              BundleFileLocatorHelperFactory.getFactory()
                  .getHelper()
                  .getLocalURL(root.toURI().toURL()));

      // try and make sure the rootResource is useable - if its a jar then make it a jar file url
      if (rootResource.exists()
          && !rootResource.isDirectory()
          && !rootResource.toString().startsWith("jar:")) {
        Resource jarResource = JarResource.newJarResource(rootResource);
        if (jarResource.exists() && jarResource.isDirectory()) rootResource = jarResource;
      }

      // Set the base resource of the ContextHandler, if not already set, can also be overridden by
      // the context xml file
      if (_contextHandler != null && _contextHandler.getBaseResource() == null) {
        _contextHandler.setBaseResource(rootResource);
      }

      // Use a classloader that knows about the common jetty parent loader, and also the bundle
      OSGiClassLoader classLoader =
          new OSGiClassLoader(getServerInstanceWrapper().getParentClassLoaderForWebapps(), _bundle);

      // if there is a context file, find it and apply it
      if (_contextFile == null && _contextHandler == null)
        throw new IllegalStateException("No context file or ContextHandler");

      if (_contextFile != null) {
        // apply the contextFile, creating the ContextHandler, the DeploymentManager will register
        // it in the ContextHandlerCollection
        Resource res = null;

        // try to find the context file in the filesystem
        if (_contextFile.startsWith("/")) res = getFileAsResource(_contextFile);

        // try to find it relative to jetty home
        if (res == null) {
          // See if the specific server we are related to has jetty.home set
          String jettyHome =
              (String)
                  getServerInstanceWrapper()
                      .getServer()
                      .getAttribute(OSGiServerConstants.JETTY_HOME);
          if (jettyHome != null) res = getFileAsResource(jettyHome, _contextFile);

          // try to see if a SystemProperty for jetty.home is set
          if (res == null) {
            jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME);

            if (jettyHome != null) {
              if (jettyHome.startsWith("\"") || jettyHome.startsWith("'"))
                jettyHome = jettyHome.substring(1);
              if (jettyHome.endsWith("\"") || (jettyHome.endsWith("'")))
                jettyHome = jettyHome.substring(0, jettyHome.length() - 1);

              res = getFileAsResource(jettyHome, _contextFile);
              if (LOG.isDebugEnabled()) LOG.debug("jetty home context file:" + res);
            }
          }
        }

        // try to find it relative to an override location that has been specified
        if (res == null) {
          if (bundleOverrideLocation != null) {
            res =
                getFileAsResource(
                    Resource.newResource(bundleOverrideLocation).getFile(), _contextFile);
            if (LOG.isDebugEnabled()) LOG.debug("Bundle override location context file:" + res);
          }
        }

        // try to find it relative to the bundle in which it is being deployed
        if (res == null) {
          if (_contextFile.startsWith("./")) _contextFile = _contextFile.substring(1);

          if (!_contextFile.startsWith("/")) _contextFile = "/" + _contextFile;

          URL contextURL = _bundle.getEntry(_contextFile);
          if (contextURL != null) res = Resource.newResource(contextURL);
        }

        // apply the context xml file, either to an existing ContextHandler, or letting the
        // it create the ContextHandler as necessary
        if (res != null) {
          ClassLoader cl = Thread.currentThread().getContextClassLoader();

          LOG.debug("Context classloader = " + cl);
          try {
            Thread.currentThread().setContextClassLoader(classLoader);

            XmlConfiguration xmlConfiguration = new XmlConfiguration(res.getInputStream());
            HashMap properties = new HashMap();
            // put the server instance in
            properties.put("Server", getServerInstanceWrapper().getServer());
            // put in the location of the bundle root
            properties.put("bundle.root", rootResource.toString());

            // insert the bundle's location as a property.
            xmlConfiguration.getProperties().putAll(properties);

            if (_contextHandler == null)
              _contextHandler = (ContextHandler) xmlConfiguration.configure();
            else xmlConfiguration.configure(_contextHandler);
          } finally {
            Thread.currentThread().setContextClassLoader(cl);
          }
        }
      }

      // Set up the class loader we created
      _contextHandler.setClassLoader(classLoader);

      // If a bundle/service property specifies context path, let it override the context xml
      String contextPath = (String) _properties.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
      if (contextPath == null)
        contextPath = (String) _properties.get(OSGiWebappConstants.SERVICE_PROP_CONTEXT_PATH);
      if (contextPath != null) _contextHandler.setContextPath(contextPath);

      // osgi Enterprise Spec r4 p.427
      _contextHandler.setAttribute(
          OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext());

      // make sure we protect also the osgi dirs specified by OSGi Enterprise spec
      String[] targets = _contextHandler.getProtectedTargets();
      int length = (targets == null ? 0 : targets.length);

      String[] updatedTargets = null;
      if (targets != null) {
        updatedTargets =
            new String[length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length];
        System.arraycopy(targets, 0, updatedTargets, 0, length);

      } else updatedTargets = new String[OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length];
      System.arraycopy(
          OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS,
          0,
          updatedTargets,
          length,
          OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length);
      _contextHandler.setProtectedTargets(updatedTargets);
    }
Пример #9
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);
  }
Пример #10
0
  /**
   * Configure a jetty instance and deploy the webapps presented as args
   *
   * @param args the command line arguments
   * @throws Exception if unable to configure
   */
  public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
      if ("--lib".equals(args[i])) {
        try (Resource lib = Resource.newResource(args[++i])) {
          if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib);
          _classpath.addJars(lib);
        }
      } else if ("--jar".equals(args[i])) {
        try (Resource jar = Resource.newResource(args[++i])) {
          if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar);
          _classpath.addPath(jar);
        }
      } else if ("--classes".equals(args[i])) {
        try (Resource classes = Resource.newResource(args[++i])) {
          if (!classes.exists() || !classes.isDirectory())
            usage("No such classes directory " + classes);
          _classpath.addPath(classes);
        }
      } else if (args[i].startsWith("--")) i++;
    }

    initClassLoader();

    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);

    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;

    boolean runnerServerInitialized = false;

    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--port":
          port = Integer.parseInt(args[++i]);
          break;
        case "--host":
          host = args[++i];
          break;
        case "--stop-port":
          stopPort = Integer.parseInt(args[++i]);
          break;
        case "--stop-key":
          stopKey = args[++i];
          break;
        case "--log":
          _logFile = args[++i];
          break;
        case "--out":
          String outFile = args[++i];
          PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
          LOG.info("Redirecting stderr/stdout to " + outFile);
          System.setErr(out);
          System.setOut(out);
          break;
        case "--path":
          contextPath = args[++i];
          contextPathSet = true;
          break;
        case "--config":
          if (_configFiles == null) _configFiles = new ArrayList<>();
          _configFiles.add(args[++i]);
          break;
        case "--lib":
          ++i; // skip

          break;
        case "--jar":
          ++i; // skip

          break;
        case "--classes":
          ++i; // skip

          break;
        case "--stats":
          _enableStats = true;
          _statsPropFile = args[++i];
          _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
          break;
        default:
          // process contexts

          if (!runnerServerInitialized) // log handlers not registered, server maybe not created,
                                        // etc
          {
            if (_server == null) // server not initialized yet
            {
              // build the server
              _server = new Server();
            }

            // apply jetty config files if there are any
            if (_configFiles != null) {
              for (String cfg : _configFiles) {
                try (Resource resource = Resource.newResource(cfg)) {
                  XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                  xmlConfiguration.configure(_server);
                }
              }
            }

            // check that everything got configured, and if not, make the handlers
            HandlerCollection handlers =
                (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
            if (handlers == null) {
              handlers = new HandlerCollection();
              _server.setHandler(handlers);
            }

            // check if contexts already configured
            _contexts =
                (ContextHandlerCollection)
                    handlers.getChildHandlerByClass(ContextHandlerCollection.class);
            if (_contexts == null) {
              _contexts = new ContextHandlerCollection();
              prependHandler(_contexts, handlers);
            }

            if (_enableStats) {
              // if no stats handler already configured
              if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                StatisticsHandler statsHandler = new StatisticsHandler();

                Handler oldHandler = _server.getHandler();
                statsHandler.setHandler(oldHandler);
                _server.setHandler(statsHandler);

                ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                statsContext.setSessionHandler(new SessionHandler());
                if (_statsPropFile != null) {
                  HashLoginService loginService =
                      new HashLoginService("StatsRealm", _statsPropFile);
                  Constraint constraint = new Constraint();
                  constraint.setName("Admin Only");
                  constraint.setRoles(new String[] {"admin"});
                  constraint.setAuthenticate(true);

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

                  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                  securityHandler.setLoginService(loginService);
                  securityHandler.setConstraintMappings(Collections.singletonList(cm));
                  securityHandler.setAuthenticator(new BasicAuthenticator());
                  statsContext.setSecurityHandler(securityHandler);
                }
              }
            }

            // ensure a DefaultHandler is present
            if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
              handlers.addHandler(new DefaultHandler());
            }

            // ensure a log handler is present
            _logHandler =
                (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
            if (_logHandler == null) {
              _logHandler = new RequestLogHandler();
              handlers.addHandler(_logHandler);
            }

            // check a connector is configured to listen on
            Connector[] connectors = _server.getConnectors();
            if (connectors == null || connectors.length == 0) {
              ServerConnector connector = new ServerConnector(_server);
              connector.setPort(port);
              if (host != null) connector.setHost(host);
              _server.addConnector(connector);
              if (_enableStats) connector.addBean(new ConnectorStatistics());
            } else {
              if (_enableStats) {
                for (Connector connector : connectors) {
                  ((AbstractConnector) connector).addBean(new ConnectorStatistics());
                }
              }
            }

            runnerServerInitialized = true;
          }

          // Create a context
          try (Resource ctx = Resource.newResource(args[i])) {
            if (!ctx.exists()) usage("Context '" + ctx + "' does not exist");

            if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath;

            // Configure the context
            if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) {
              // It is a context config file
              XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
              xmlConfiguration.getIdMap().put("Server", _server);
              ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
              if (contextPathSet) handler.setContextPath(contextPath);
              _contexts.addHandler(handler);
              handler.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            } else {
              // assume it is a WAR file
              WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
              webapp.setConfigurationClasses(__plusConfigurationClasses);
              webapp.setAttribute(
                  "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                  __containerIncludeJarPattern);
            }
          }
          // reset
          contextPathSet = false;
          contextPath = __defaultContextPath;
          break;
      }
    }

    if (_server == null) usage("No Contexts defined");
    _server.setStopAtShutdown(true);

    switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
      case 1:
        usage("Must specify --stop-key when --stop-port is specified");
        break;

      case 2:
        usage("Must specify --stop-port when --stop-key is specified");
        break;

      case 3:
        ShutdownMonitor monitor = ShutdownMonitor.getInstance();
        monitor.setPort(stopPort);
        monitor.setKey(stopKey);
        monitor.setExitVm(true);
        break;
    }

    if (_logFile != null) {
      NCSARequestLog requestLog = new NCSARequestLog(_logFile);
      requestLog.setExtended(false);
      _logHandler.setRequestLog(requestLog);
    }
  }
Пример #11
0
  public WebServer(final int port, String uiPath, String tasksPath, final Simulator simulator)
      throws Exception {
    this.server = new Server();
    final ServerConnector connector = new ServerConnector(server);

    connector.setPort(port);
    this.server.addConnector(connector);
    this.uiPath = uiPath;
    this.tasksPath = tasksPath;

    this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    // serve UI webpage (after dynamically setting server ip)
    HttpServlet ui_servlet = new IPTokenHTTPServlet(port, UI_PATH);
    this.context.addServlet(new ServletHolder(ui_servlet), "/");

    // serve UI Process webpage (after dynamically setting server ip)
    HttpServlet ui_process_servlet = new IPTokenHTTPServlet(port, UI_PROCESS_PATH);
    this.context.addServlet(new ServletHolder(ui_process_servlet), "/uiprocess");

    // related static resources
    ContextHandler resourcesContext = new ContextHandler();
    resourcesContext.setContextPath("/resources");
    ResourceHandler rh = new ResourceHandler();
    rh.setBaseResource(Resource.newClassPathResource(STATIC_RESOURCES_PATH));
    resourcesContext.setHandler(rh);

    ContextHandler webjarsContext = new ContextHandler();
    webjarsContext.setContextPath("/webjars/");
    rh =
        new ResourceHandler() {
          @Override
          public Resource getResource(String path) throws MalformedURLException {
            Resource resource = Resource.newClassPathResource(path);
            if (resource == null || !resource.exists()) {
              resource = Resource.newClassPathResource(WEBJARS_RESOURCES_PATH + path);
            }
            return resource;
          }
        };
    webjarsContext.setHandler(rh);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {webjarsContext, resourcesContext, context});
    server.setHandler(contexts);

    context.setContextPath("/");

    // add REST bridge servlet
    String apiBasePath = eu.learnpad.sim.BridgeInterface.class.getAnnotation(Path.class).value();
    context.addServlet(
        new SimulatorBridgeServletHolder(simulator, context, apiBasePath), apiBasePath + "*");

    // start server
    this.server.start();

    // set chat servlet
    ServletHolder holder = new ServletHolder(new DummyChatServlet());
    String fullPath = "/chat/*";

    this.context.addServlet(holder, fullPath);

    System.out.println(
        "chat servlet launched at "
            + server.getURI().toString().substring(0, server.getURI().toString().length() - 1)
            + fullPath);
  }