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; }
public static void main(String[] args) { try { Server server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(8080); server.addConnector(connector); WebAppContext context = new WebAppContext(); context.setContextPath("/"); context.setWar("src/test/webapp"); context.setInitParameter( SessionManager.__CheckRemoteSessionEncoding, "true"); // Stops Jetty from adding 'jsessionid' URL rewriting into non-local URLs (e.g. // Google OpenId redirects) server.setHandler(context); server.addLifeCycleListener( new AbstractLifeCycle.AbstractLifeCycleListener() { @Override public void lifeCycleStarted(LifeCycle event) { log.warn("Jetty ready to accept requests..."); } }); server.start(); server.join(); } catch (Exception e) { throw new RuntimeException("Error launching Jetty", e); } }
public static void main(String[] args) { Server server = JettyUtil.getServer(); // JettyUtil.setAppContextPath(JettyUtil.MY_APP, ProjectPathUtil.getWebRootPath()); JettyUtil.setAppContextPath("/", ProjectPathUtil.getWebRootPath()); WebAppContext webAppContext = JettyUtil.getWebAppContext(); webAppContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "true"); webAppContext.addVirtualHosts(new String[] {"www.xxx.com"}); JettyUtil.getWebAppContext().addServlet(CookieInfoServlet.class, JettyUtil.HELLO); JettyUtil.startServer(); // HttpClientUtil.visitUrlWithPostMethod(JettyUtil.WHOLE_URL, "utf8",null); // JettyUtil.stopServer(); }
private WebAppContext buildWebAppContext(String[] args, Enviroment env) { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.register(WebContext.class); WebAppContext handler = new WebAppContext(); handler.setContextPath(CONTEXT_NAME); handler.setDisplayName(DISPLAY_NAME); String[] resources = null; resources = new String[] {"./WebContent"}; handler.setWelcomeFiles(new String[] {"index.html"}); handler.setInitParameter("useFileMappedBuffer", "false"); handler.setBaseResource(new ResourceCollection(resources)); handler.setResourceAlias("/WEB-INF/classes/", "/classes/"); this.appendListeners(applicationContext, handler); this.appendSpringDispatcherServlet(applicationContext, handler); applicationContext.close(); return handler; }
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); } }
@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(); }