public EmbeddedJettyServer(int port, boolean useRestSession) throws Exception {
    server = new Server();
    connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

    root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(".");
    if (useRestSession) {
      RestSessionIdManager idManager = new RestSessionIdManager();
      RestSessionManager sessionManager = new RestSessionManager();
      server.setSessionIdManager(idManager);
      sessionManager.setSessionIdManager(idManager);
      SessionHandler sessionHandler = new SessionHandler();
      sessionHandler.setSessionManager(sessionManager);
      root.setSessionHandler(sessionHandler);
      root.setClassLoader(getContextClassLoader());
    }

    server.setHandler(root);
    server.start();
    while (!server.isStarted()) {
      Thread.sleep(100);
    }
  }
Ejemplo n.º 2
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);
  }
Ejemplo n.º 3
0
 private Handler createResourceHandler(String context, String resourceBase) {
   WebAppContext ctx = new WebAppContext();
   ctx.setContextPath(context);
   ctx.setResourceBase(resourceBase);
   ctx.setParentLoaderPriority(true);
   return ctx;
 }
Ejemplo n.º 4
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    SslContextFactory factory = new SslContextFactory();
    factory.setKeyStorePath("src/test/keystore.jks");
    factory.setKeyStorePassword("storepass");
    factory.setKeyManagerPassword("keypass");
    SslSocketConnector connector = new SslSocketConnector(factory);
    connector.setPort(8443);
    server.addConnector(connector);
    InheritedChannelConnector inheritedChannelConnector = new InheritedChannelConnector();
    inheritedChannelConnector.setPort(8080);
    server.addConnector(inheritedChannelConnector);

    WebAppContext context = new WebAppContext();
    context.setConfigurationClasses(
        new String[] {WebInfConfiguration.class.getName(), WebXmlConfiguration.class.getName()});
    context.setResourceBase("src/main/webapp");
    context.setContextPath(CONTEXT_PATH);
    context.setParentLoaderPriority(true);
    server.setHandler(context);

    try {
      server.start();
      if (!context.isAvailable()) throw new IllegalStateException("context deployed failed");
      server.join();
    } catch (Exception e) {
      server.stop();
      throw new IllegalStateException("jetty failed to start: " + e.getMessage(), e);
    }
  }
Ejemplo n.º 5
0
 public static void main(String[] args) throws Exception {
   Server server = new Server(80);
   WebAppContext webapp = new WebAppContext();
   webapp.setResourceBase("/");
   webapp.setContextPath("/*");
   webapp.setConfigurations(
       new Configuration[] {
         new WebXmlConfiguration(),
         new AnnotationConfiguration() {
           @Override
           public void preConfigure(WebAppContext context) throws Exception {
             ClassInheritanceMap map = new ClassInheritanceMap();
             map.put(
                 WebApplicationInitializer.class.getName(),
                 new ConcurrentHashSet<String>() {
                   {
                     add(Initializer.class.getName());
                     add(SpringSecurityInitializer.class.getName());
                   }
                 });
             context.setAttribute(CLASS_INHERITANCE_MAP, map);
             _classInheritanceHandler = new ClassInheritanceHandler(map);
           }
         }
       });
   server.setHandler(webapp);
   server.start();
   System.out.println("Application started!");
   server.join();
 }
Ejemplo n.º 6
0
 private static WebAppContext loadContext(String webappDirLocation, String webXmlLocation) {
   WebAppContext context = new WebAppContext();
   context.setContextPath(getContext());
   context.setDescriptor(webXmlLocation);
   context.setResourceBase(webappDirLocation);
   context.setParentLoaderPriority(true);
   return context;
 }
Ejemplo n.º 7
0
  private void doStart() {
    if (!available(port)) throw new IllegalStateException("port: " + port + " already in use!");

    deleteSessionData();

    System.out.println("Starting JFinal " + Const.JFINAL_VERSION);
    server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);
    webApp = new WebAppContext();
    webApp.setThrowUnavailableOnStartupException(true); // 在启动过程中允许抛出异常终止启动并退出 JVM
    webApp.setContextPath(context);
    webApp.setResourceBase(webAppDir); // webApp.setWar(webAppDir);
    webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    webApp.setInitParameter(
        "org.eclipse.jetty.servlet.Default.useFileMappedBuffer",
        "false"); // webApp.setInitParams(Collections.singletonMap("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"));
    persistSession(webApp);

    server.setHandler(webApp);
    changeClassLoader(webApp);

    // configureScanner
    if (scanIntervalSeconds > 0) {
      Scanner scanner =
          new Scanner(PathKit.getRootClassPath(), scanIntervalSeconds) {
            public void onChange() {
              try {
                System.err.println("\nLoading changes ......");
                webApp.stop();
                JFinalClassLoader loader = new JFinalClassLoader(webApp, getClassPath());
                webApp.setClassLoader(loader);
                webApp.start();
                System.err.println("Loading complete.");
              } catch (Exception e) {
                System.err.println(
                    "Error reconfiguring/restarting webapp after change in watched files");
                LogKit.error(e.getMessage(), e);
              }
            }
          };
      System.out.println("Starting scanner at interval of " + scanIntervalSeconds + " seconds.");
      scanner.start();
    }

    try {
      System.out.println("Starting web server on port: " + port);
      server.start();
      System.out.println("Starting Complete. Welcome To The JFinal World :)");
      server.join();
    } catch (Exception e) {
      LogKit.error(e.getMessage(), e);
      System.exit(100);
    }
    return;
  }
Ejemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    WebAppContext context = new WebAppContext();
    context.setDescriptor("src/main/webapp/WEB-INF/web.xml");
    context.setResourceBase("src/main/webapp/");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);
    server.setHandler(context);
    server.start();
  }
Ejemplo n.º 9
0
  public void buildHTTP() {
    // build server which has servlet
    Configuration c = _config.subset(CLIENT_CONFIG_PREFIX);
    BrokerClientConf clientConfig = new BrokerClientConf(c);

    _server = new Server(clientConfig.getQueryPort());

    WebAppContext context = new WebAppContext();
    context.addServlet(PinotClientRequestServlet.class, "/query");
    context.addServlet(PinotBrokerDebugServlet.class, "/debug");

    if (clientConfig.enableConsole()) {
      context.setResourceBase(clientConfig.getConsoleWebappPath());
    } else {
      context.setResourceBase("");
    }

    context.addEventListener(
        new PinotBrokerServletContextChangeListener(_requestHandler, _brokerMetrics));

    _server.setHandler(context);
  }
Ejemplo n.º 10
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setResourceBase("webapp");
    webAppContext.setDescriptor("webapp/WEB-INF/web.xml");
    webAppContext.setContextPath("/");
    // server.setHandler(webAppContext);
    server.setHandler(new HelloWorld());

    server.start();
    server.join();
  }
Ejemplo n.º 11
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(ConsoleFilter.DATABASE_ATTRIBUTE, databaseInfo);
   setupRequestLimits(root, REQUEST_TIME_LIMIT, MAX_OPS_LIMIT);
   server.setHandler(root);
   server.start();
 }
  public static void main(String[] args) throws Exception {
    System.out.println("Starting Frontend...");
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/");
    webAppContext.setResourceBase("webapp");
    webAppContext.setDescriptor("webapp/WEB-INF/web.xml");

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

    server.start();
    System.out.println("Started Frontend.");
    server.join();
  }
Ejemplo n.º 13
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();
 }
  public static void main(String[] args) throws Exception {

    Server server = new Server(8080);
    String dir =
        "/home/gpt/Desarrollo/freedomotic/framework/freedomotic/plugins/devices/es.gpulido.webserver/data/webapps/gwt_client";
    WebAppContext context = new WebAppContext();

    context.setDescriptor(dir + "/WEB-INF/web.xml");
    context.setResourceBase(
        "/home/gpt/Desarrollo/freedomotic/framework/freedomotic/plugins/devices/es.gpulido.webserver/data/webapps/gwt_client");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);

    server.setHandler(context);
    server.start();
  }
Ejemplo n.º 15
0
  public void start() {
    Server server = new Server(port);

    WebAppContext context = new WebAppContext();
    context.setResourceBase("src/main/webapp");
    context.setWar("src/main/webapp");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);
    server.setHandler(context);
    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 16
0
 public EmbeddedWebServer(BimServer bimServer, boolean localDev) {
   server = new Server();
   //		Disabled 26-04-2015, I am pretty sure we don't use session anymore at all
   //		HashSessionIdManager hashSessionIdManager = new HashSessionIdManager(new Random()); //
   // Should be SecureRandom, but this makes startup slow on certain systems
   //		server.setSessionIdManager(hashSessionIdManager);
   ServerConnector socketConnector = new ServerConnector(server);
   socketConnector.setPort(bimServer.getConfig().getPort());
   server.addConnector(socketConnector);
   context = new WebAppContext(server, "", "/");
   context.setTempDirectory(bimServer.getHomeDir().resolve("jettytmp").toFile());
   if (localDev) {
     // TODO document why
     context.setDefaultsDescriptor("www/WEB-INF/webdefault.xml");
   }
   context.getServletContext().setAttribute("bimserver", bimServer);
   if (context.getResourceBase() == null) {
     context.setResourceBase("../BimServer/www");
   }
 }
Ejemplo n.º 17
0
  public static void main(String[] args) throws Exception {
    String webappDirLocation = "src/main/webapp/";

    String webPort = System.getenv("PORT");
    if (webPort == null || webPort.isEmpty()) {
      webPort = "8080";
    }

    Server server = new Server(Integer.valueOf(webPort));
    WebAppContext root = new WebAppContext();

    root.setContextPath("/");
    root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
    root.setResourceBase(webappDirLocation);
    root.setParentLoaderPriority(true);

    server.setHandler(root);
    server.start();
    server.join();
  }
Ejemplo n.º 18
0
  /** Starts the server at this base directory and port */
  public RealVRaptor(File base, int port) {
    this.server = new Server(port);
    WebAppContext context = new WebAppContext();

    context.setDescriptor(base.getAbsolutePath() + "/WEB-INF/web.xml");
    context.setResourceBase(base.getAbsolutePath());
    context.setContextPath("/");
    context.setParentLoaderPriority(true);
    LOG.info("Loading port " + port + " with vraptor context at " + base.getAbsolutePath());

    server.setHandler(context);

    try {
      server.start();
      this.port = port;
      LOG.info("VRaptor context started");
    } catch (Exception e) {
      throw new VRaptorException("Unable to start vraptor", e);
    }
  }
Ejemplo n.º 19
0
  private WebAppContext buildWebappContext() {

    WebAppContext webappContext = new WebAppContext();
    webappContext.setResourceBase("/");

    //        // Add Wicket filter
    //        WicketFilter filter = new WicketFilter(app);
    //        FilterHolder filterHolder = new FilterHolder(filter);
    //        filterHolder.setInitParameter(
    //                WicketFilter.FILTER_MAPPING_PARAM, ANALYTICS_MAPPING);
    //        webappContext.addFilter(
    //                filterHolder,
    //                ANALYTICS_MAPPING,
    //                EnumSet.of(DispatcherType.REQUEST));

    // Add test serlet
    ServletHolder servletHolder = new ServletHolder(new TestServlet());
    webappContext.addServlet(servletHolder, "/test/*");

    // Add custom error message
    webappContext.setErrorHandler(
        new ErrorHandler() {
          protected void writeErrorPageBody(
              HttpServletRequest request,
              Writer writer,
              int code,
              String message,
              boolean showStacks)
              throws IOException {
            String uri = request.getRequestURI();
            writeErrorPageMessage(request, writer, code, message, uri);
            if (showStacks) writeErrorPageStacks(request, writer);
            writer.write(
                "<hr><i><small>Norconex HTTP Collector Test " + "Server</small></i><hr/>\n");
          }
        });

    return webappContext;
  }
Ejemplo n.º 20
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);
    }
  }
  @Test
  public void testCluster() throws Exception {

    String projectBaseDirectory = System.getProperty("user.dir");

    //
    // Create master node
    //
    Server masterServer = new Server(8080);

    WebAppContext masterContext = new WebAppContext();
    masterContext.setDescriptor(projectBaseDirectory + "/target/vaporware/WEB-INF/web.xml");
    masterContext.setResourceBase(projectBaseDirectory + "/target/vaporware");
    masterContext.setContextPath("/");
    masterContext.setConfigurations(
        new Configuration[] {
          new WebInfConfiguration(),
          new WebXmlConfiguration(),
          new MetaInfConfiguration(),
          new FragmentConfiguration(),
          new EnvConfiguration(),
          new PlusConfiguration(),
          new AnnotationConfiguration(),
          new JettyWebXmlConfiguration(),
          new TagLibConfiguration()
        });
    masterContext.setParentLoaderPriority(true);

    masterServer.setHandler(masterContext);
    masterServer.start();
    // masterServer.join();

    //
    // Create slave node
    //
    Server slaveServer = new Server(8181);

    WebAppContext slaveContext = new WebAppContext();
    slaveContext.setDescriptor(projectBaseDirectory + "/target/vaporware/WEB-INF/web-slave.xml");
    slaveContext.setResourceBase(projectBaseDirectory + "/target/vaporware");
    slaveContext.setContextPath("/");
    slaveContext.setConfigurations(
        new Configuration[] {
          new WebInfConfiguration(),
          new WebXmlConfiguration(),
          new MetaInfConfiguration(),
          new FragmentConfiguration(),
          new EnvConfiguration(),
          new PlusConfiguration(),
          new AnnotationConfiguration(),
          new JettyWebXmlConfiguration(),
          new TagLibConfiguration()
        });
    slaveContext.setParentLoaderPriority(true);

    slaveServer.setHandler(slaveContext);
    slaveServer.start();
    // slaveServer.join();

    // Try to let the user terminate the Jetty server instances gracefully.  This won't work in an
    // environment like Eclipse, if
    // console input can't be received.  However, even in that that case you will be able to kill
    // the Maven process without
    // a Java process lingering around (as would be the case if you used "Sever.join()" to pause
    // execution of this thread).
    System.out.println("PRESS <ENTER> TO HALT SERVERS (or kill the Maven process)...");
    Scanner scanner = new Scanner(System.in);
    String line = scanner.nextLine();
    System.out.println(line);
    scanner.close();
    masterServer.stop();
    slaveServer.stop();
    System.out.println("Servers halted");
  }