public static void main(String[] args) throws Exception { ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(PUBLIC_HTML); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); //page reloaded by the timer context.addServlet(TimerServlet.class, "/timer"); //part of a page reloaded by the timer context.addServlet(AjaxTimerServlet.class, "/server-time"); //long-polling waits till a message context.addServlet(new ServletHolder(new MessengerServlet()), "/messenger"); //web chat context.addServlet(WebSocketChatServlet.class, "/chat"); Server server = new Server(PORT); server.setHandler(new HandlerList(resourceHandler, context)); server.start(); server.join(); }
public static void main(String[] args) { int port = Configuration.INSTANCE.getInt("port", 8080); Server server = new Server(port); ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.setContextPath("/"); ServletHolder sh = new ServletHolder(new VaadinServlet()); contextHandler.addServlet(sh, "/*"); contextHandler.setInitParameter("ui", CrawlerAdminUI.class.getCanonicalName()); contextHandler.setInitParameter("productionMode", String.valueOf(PRODUCTION_MODE)); server.setHandler(contextHandler); try { server.start(); server.join(); } catch (Exception e) { LOG.error("Failed to start application", e); } }
public @NotNull CollectorServer init(@NotNull InetSocketAddress address, @NotNull ExpositionFormat format) { try { Log.setLog(new Slf4jLog()); final Server serverInstance = new Server(address); format.handler(serverInstance); serverInstance.start(); server = serverInstance; Logger.instance.info("Prometheus server with JMX metrics started at " + address); } catch (Exception e) { Logger.instance.error("Failed to start server at " + address, e); } return this; }
private static void reverseProxy() throws Exception{ Server server = new Server(); SocketConnector connector = new SocketConnector(); connector.setHost("127.0.0.1"); connector.setPort(8888); server.setConnectors(new Connector[]{connector}); // Setup proxy handler to handle CONNECT methods ConnectHandler proxy = new ConnectHandler(); server.setHandler(proxy); // Setup proxy servlet ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS); ServletHolder proxyServlet = new ServletHolder(ProxyServlet.Transparent.class); proxyServlet.setInitParameter("ProxyTo", "https://localhost:54321/"); proxyServlet.setInitParameter("Prefix", "/"); context.addServlet(proxyServlet, "/*"); server.start(); }
public static void main(String[] args) { try { MergedLogSource src = new MergedLogSource(args); System.out.println(src); Server server = new Server(8182); server.setHandler(new LogServer(src)); server.start(); server.join(); } catch (Exception e) { // Something is wrong. e.printStackTrace(); } }
public static Server addWebApplication(final Server jetty, final String webAppContext, final String warFilePath) { WebAppContext webapp = new WebAppContext(); webapp.setContextPath(webAppContext); webapp.setWar(warFilePath); webapp.setParentLoaderPriority(false); webapp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); File tmpPath = new File(getWebAppBaseDirectory(webAppContext)); tmpPath.mkdirs(); webapp.setTempDirectory(tmpPath); ((HandlerCollection) jetty.getHandler()).addHandler(webapp); return jetty; }
/** * Configures the <code>connector</code> given the <code>config</code> for using SPNEGO. * * @param connector The connector to configure * @param config The configuration */ protected ConstraintSecurityHandler configureSpnego(Server server, ServerConnector connector, AvaticaServerConfiguration config) { final String realm = Objects.requireNonNull(config.getKerberosRealm()); final String principal = Objects.requireNonNull(config.getKerberosPrincipal()); // A customization of SpnegoLoginService to explicitly set the server's principal, otherwise // we would have to require a custom file to set the server's principal. PropertyBasedSpnegoLoginService spnegoLoginService = new PropertyBasedSpnegoLoginService(realm, principal); // Roles are "realms" for Kerberos/SPNEGO final String[] allowedRealms = getAllowedRealms(realm, config); return configureCommonAuthentication(server, connector, config, Constraint.__SPNEGO_AUTH, allowedRealms, new AvaticaSpnegoAuthenticator(), realm, spnegoLoginService); }
@Override public boolean isRunning(final int port) { if (!isValidPort(port)) { return false; } final Server server = serverCache.getIfPresent(port); if (null == server) { return false; } if (!server.isStarted()) { return false; } return isPortInUse(port); }
/** * startUAVServer */ public void startServer(Object... args) { Server server = (Server) args[0]; // integrate Tomcat log UAVServer.instance().setLog(new JettyLog("MonitorServer")); // start Monitor Server when server starts UAVServer.instance().start(new Object[] { UAVServer.ServerVendor.JETTY }); // get server port if (UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT) == null) { // set port ServerConnector sc = (ServerConnector) server.getConnectors()[0]; String protocol = sc.getDefaultProtocol(); if (protocol.toLowerCase().indexOf("http") >= 0) { UAVServer.instance().putServerInfo(CaptureConstants.INFO_APPSERVER_LISTEN_PORT, sc.getPort()); } } }
public static void main(final String... args) throws Exception { if (args.length > 1) { System.out.printf("Temporary Directory @ ($1%s)%n", USER_DIR); final Server jetty = JettyHelper.initJetty(null, 8090, new SSLConfig()); for (int index = 0; index < args.length; index += 2) { final String webAppContext = args[index]; final String webAppArchivePath = args[index + 1]; JettyHelper.addWebApplication(jetty, normalizeWebAppContext(webAppContext), normalizeWebAppArchivePath(webAppArchivePath)); } JettyHelper.startJetty(jetty); latch.await(); } else { System.out.printf( "usage:%n>java org.apache.geode.management.internal.TomcatHelper <web-app-context> <war-file-path> [<web-app-context> <war-file-path>]*"); } }
public static void main(String[] args) throws Exception { ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(PUBLIC_HTML); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new LoginServlet("anonymous")), "/login"); context.addServlet(AdminServlet.class, "/admin"); context.addServlet(TimerServlet.class, "/timer"); Server server = new Server(PORT); server.setHandler(new HandlerList(resourceHandler, context)); server.start(); server.join(); }
public static Server createDevServer(int port, String contextPath) { Server server = new Server(); server.setStopAtShutdown(true); ServerConnector connector = new ServerConnector(server); // 设置服务端口 connector.setPort(port); connector.setReuseAddress(false); server.setConnectors(new Connector[] {connector}); // 设置web资源根路径以及访问web的根路径 WebAppContext webAppCtx = new WebAppContext(DEFAULT_APP_CONTEXT_PATH, contextPath); webAppCtx.setDescriptor(DEFAULT_APP_CONTEXT_PATH + "/WEB-INF/web.xml"); webAppCtx.setResourceBase(DEFAULT_APP_CONTEXT_PATH); webAppCtx.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(webAppCtx); return server; }
public JettyAdminServer(String address, int port, int timeout, String commandUrl) { this.port = port; this.idleTimeout = timeout; this.commandUrl = commandUrl; this.address = address; server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setHost(address); connector.setPort(port); connector.setIdleTimeout(idleTimeout); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/*"); server.setHandler(context); context.addServlet(new ServletHolder(new CommandServlet()), commandUrl + "/*"); }
/** * 启动jetty服务,加载server.war */ public static void startJettyServer(String path) throws Exception{ String configPath=path+ File.separator+"conf"+File.separator+"conf.properties"; InputStream is = new FileInputStream(configPath);; Properties properties =new Properties(); properties.load(is); is.close(); int serverPort = Integer.parseInt(properties.getProperty("server.port")); Server server = new Server(serverPort); WebAppContext context = new WebAppContext(); context.setContextPath("/"); context.setWar(path+"/bin/service.war"); server.setHandler(context); server.start(); server.join(); }
public static void main(String[] args) { long beginTime = System.currentTimeMillis(); Server server = createServer(); try { server.start(); System.err.println(); System.out.println("*****************************************************************"); System.err.print("[INFO] Server running in " + (System.currentTimeMillis() - beginTime) + "ms "); System.err.println("at http://127.0.0.1" + (80==port?"":":"+port) + contextPath); System.out.println("*****************************************************************"); } catch (Exception e) { System.err.println("Jetty启动失败,堆栈轨迹如下"); e.printStackTrace(); System.exit(-1); } }
public static Server createJettyServer(int port, String contextPath) { Server server = new Server(port); server.setStopAtShutdown(true); ProtectionDomain protectionDomain = Launcher.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); String warFile = location.toExternalForm(); WebAppContext context = new WebAppContext(warFile, contextPath); context.setServer(server); // 设置work dir,war包将解压到该目录,jsp编译后的文件也将放入其中。 String currentDir = new File(location.getPath()).getParent(); File workDir = new File(currentDir, "work"); context.setTempDirectory(workDir); server.setHandler(context); return server; }
public static void main(String[] args) throws Exception { NettyServerBuilder.forAddress(LocalAddress.ANY).forPort(19876) .maxConcurrentCallsPerConnection(12).maxMessageSize(16777216) .addService(new MockApplicationRegisterService()) .addService(new MockInstanceDiscoveryService()) .addService(new MockJVMMetricsService()) .addService(new MockServiceNameDiscoveryService()) .addService(new MockTraceSegmentService()).build().start(); Server jettyServer = new Server(new InetSocketAddress("0.0.0.0", Integer.valueOf(12800))); String contextPath = "/"; ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); servletContextHandler.setContextPath(contextPath); servletContextHandler.addServlet(GrpcAddressHttpService.class, GrpcAddressHttpService.SERVLET_PATH); servletContextHandler.addServlet(ReceiveDataService.class, ReceiveDataService.SERVLET_PATH); servletContextHandler.addServlet(ClearReceiveDataService.class, ClearReceiveDataService.SERVLET_PATH); jettyServer.setHandler(servletContextHandler); jettyServer.start(); }
@Override public void startComponent() { // Initialize servlet using RESTEasy and it's Guice bridge. // The listener must be injected by the same Guice module which also binds the REST endpoints. ServletContextHandler servletHandler = new ServletContextHandler(); servletHandler.addEventListener(listener); servletHandler.addServlet(HttpServletDispatcher.class, "/*"); // Starting up Jetty to serve the REST API. server = new Server(port); server.setHandler(servletHandler); try { server.start(); } catch (Exception e) { throw new RuntimeException(e); } }
public void afterPropertiesSet() throws Exception { Resource configXml = Resource.newSystemResource(config); XmlConfiguration configuration = new XmlConfiguration(configXml.getInputStream()); server = (Server) configuration.configure(); Integer port = getPort(); if (port != null && port > 0) { Connector[] connectors = server.getConnectors(); for (Connector connector : connectors) { connector.setPort(port); } } Handler handler = server.getHandler(); if (handler != null && handler instanceof ServletContextHandler) { ServletContextHandler servletHandler = (ServletContextHandler) handler; servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", htdocsDir); } server.start(); if (logger.isInfoEnabled()) { logger.info("##Jetty Embed Server is startup!"); } }
public static void main(@NotNull @NonNls String[] args) throws Exception { PropertyConfigurator.configure(System.getProperty("user.dir") + "/log4j.properties"); logger.warn("StrictFP | Back-end"); logger.info("StrictFP Back-end is now running..."); Server server = new Server(Constant.SERVER.SERVER_PORT); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/api/v0"); server.setHandler(context); server.setStopAtShutdown(true); // 像下面这行一样 context.addServlet(new ServletHolder(new GetQuiz()), "/misc/getquiz"); context.addServlet(new ServletHolder(new TimeLine()), "/timeline"); context.addServlet(new ServletHolder(new Counter()), "/misc/counter"); context.addServlet(new ServletHolder(new User()), "/user"); context.addServlet(new ServletHolder(new Heartbeat()), "/misc/heartbeat"); context.addServlet(new ServletHolder(new SafeCheck()), "/misc/safecheck"); context.addServlet(new ServletHolder(new CheckCert()), "/auth/check_cert"); // server.start(); server.join(); }
private static void restartWebServer(final Server server, final WebAppContext webApp) throws Exception { //TODO reconsider restart function /* restart doesnt help much regarding heap configuration, everything else can be configured at runtime. So better approach for convenient restart would be an orderly shutdown and start. */ server.stop(); LOG.info("Sent stop"); server.join(); LOG.info("Server joined"); LOG.info("Starting web server"); server.setHandler(webApp); server.start(); LOG.info("Server restarted"); }
public PrometheusExporter(int port, String path) { QueuedThreadPool threadPool = new QueuedThreadPool(25); server = new Server(threadPool); ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); CollectorRegistry collectorRegistry = new CollectorRegistry(); collectorRegistry.register(new PrometheusExports(CassandraMetricsRegistry.Metrics)); MetricsServlet metricsServlet = new MetricsServlet(collectorRegistry); context.addServlet(new ServletHolder(metricsServlet), "/" + path); try { server.start(); } catch (Exception e) { System.err.println("cannot start metrics http server " + e.getMessage()); } }
private void start() throws Exception { resourcesExample(); ResourceHandler resourceHandler = new ResourceHandler(); Resource resource = Resource.newClassPathResource(PUBLIC_HTML); resourceHandler.setBaseResource(resource); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new TimerServlet()), "/timer"); Server server = new Server(PORT); server.setHandler(new HandlerList(resourceHandler, context)); server.start(); server.join(); }
public static void main(String args[]) throws Exception { Resource jetty_xml = Resource.newSystemResource("jetty/jetty.xml"); XmlConfiguration configuration = new XmlConfiguration(jetty_xml.getInputStream()); Server server = (Server) configuration.configure(); int port = 8081; Connector[] connectors = server.getConnectors(); for (Connector connector : connectors) { connector.setPort(port); } Handler handler = server.getHandler(); if (handler != null && handler instanceof ServletContextHandler) { ServletContextHandler servletHandler = (ServletContextHandler) handler; servletHandler.getInitParams().put("org.eclipse.jetty.servlet.Default.resourceBase", "/tmp/"); } server.start(); server.join(); }
private LegacyHttpServer(int port, int threads) { this.server = new Server(new QueuedThreadPool(threads)); server.setHandler( new AbstractHandler() { @Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { final String method = baseRequest.getParameter("method"); if ("helloworld.Greeter/SayHello".equals(method)) { baseRequest.setHandled(true); sayHello(baseRequest, response); } } }); final ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.addConnector(connector); }
private void initHttpServer(final CoreConfigure cfg) { // 如果IP:PORT已经被占用,则无法继续被绑定 // 这里说明下为什么要这么无聊加个这个判断,让Jetty的Server.bind()抛出异常不是更好么? // 比较郁闷的是,如果这个端口的绑定是"SO_REUSEADDR"端口可重用的模式,那么这个server是能正常启动,但无法正常工作的 // 所以这里必须先主动检查一次端口占用情况,当然了,这里也会存在一定的并发问题,BUT,我认为这种概率事件我可以选择暂时忽略 if (NetworkUtils.isPortInUsing(cfg.getServerIp(), cfg.getServerPort())) { throw new IllegalStateException(String.format("server[ip=%s;port=%s;] already in using, server bind failed.", cfg.getServerIp(), cfg.getServerPort())); } httpServer = new Server(new InetSocketAddress(cfg.getServerIp(), cfg.getServerPort())); if (httpServer.getThreadPool() instanceof QueuedThreadPool) { final QueuedThreadPool qtp = (QueuedThreadPool) httpServer.getThreadPool(); qtp.setName("sandbox-jetty-qtp" + qtp.hashCode()); } }
@BeforeClass public static void initialize() throws Exception { injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(BookResource.class); } @DefaultConnector @Provides Configurator configurator() { return () -> 0; // port } }, new WebServerModule(), new HTTPConnectorModule()); client = ClientBuilder.newClient(); server = injector.getInstance(Server.class); server.start(); }
/** {@inheritDoc} */ @Override public void run() { try { this.server = new Server(this.serverPort); ServletHandler servletHandler = new ServletHandler(); servletHandler.addServletWithMapping(TaskTrackerServlet.class, "/tracker"); this.server.setHandler(servletHandler); this.server.start(); this.server.join(); } catch (Exception ex) { // suppress } }
@BeforeClass public static void setUp() throws Exception { System.out.println("Jetty [Configuring]"); ServletContextHandler servletContext = new ServletContextHandler(); servletContext.setContextPath("/"); servletContext.addServlet(PingPongServlet.class, PingPongServlet.PATH); servletContext.addServlet(ExceptionServlet.class, ExceptionServlet.PATH); ServletHolder servletHolder = servletContext.addServlet(AsyncServlet.class, AsyncServlet.PATH); servletHolder.setAsyncSupported(true); jetty = new Server(0); jetty.setHandler(servletContext); System.out.println("Jetty [Starting]"); jetty.start(); System.out.println("Jetty [Started]"); serverPort = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort(); }
public void start() throws Exception { String relativelyPath = System.getProperty("user.dir"); server = new Server(port); WebAppContext webAppContext = new WebAppContext(); webAppContext.setContextPath("/"); webAppContext.setWar(relativelyPath + "\\rainbow-web\\target\\rainbow-web.war"); webAppContext.setParentLoaderPriority(true); webAppContext.setServer(server); webAppContext.setClassLoader(ClassLoader.getSystemClassLoader()); webAppContext.getSessionHandler().getSessionManager() .setMaxInactiveInterval(10); server.setHandler(webAppContext); server.start(); }
private void run(){ long beginTime = System.currentTimeMillis(); Server server = createServer(this.port, this.context_path, this.webapp_path); //setTldJarNames(server, new String[]{"sitemesh", "spring-webmvc", "shiro-web"}); try { //启动Jetty server.start(); this.log(System.currentTimeMillis() - beginTime); // //等待用户键入回车重载应用 // while(true){ // char c = (char)System.in.read(); // if(c == '\n'){ // reloadContext(server, JettyBootStrap.class.getResource("/").getPath()); // } // } } catch (Exception e) { System.err.println("Jetty启动失败,堆栈轨迹如下"); e.printStackTrace(); System.exit(-1); } }
private void startServer() { HttpAPIConfig cfg = getSettings(); server = new Server(cfg.getPort()); HandlerList lst = new HandlerList(); LinkController ctr = new JDLinkController(LinkCollector.getInstance()); if(cfg.getUsePassword() && cfg.getPassword() != null && !cfg.getPassword().equals("")) { lst.addHandler(new AuthorizationHandler(cfg.getPassword())); } lst.addHandler(new AjaxHandler(cfg.getAllowGet())); if(cfg.getAllowGet()) { lst.addHandler(new JDServerGETHandler(ctr)); } lst.addHandler(new JDServerPOSTHandler(ctr)); server.setHandler(lst); try { server.start(); } catch(Exception e) { logger.log(new LogRecord(Level.SEVERE, e.getMessage())); } }
protected ConstraintSecurityHandler configureBasicAuthentication(Server server, ServerConnector connector, AvaticaServerConfiguration config) { final String[] allowedRoles = config.getAllowedRoles(); final String realm = config.getHashLoginServiceRealm(); final String loginServiceProperties = config.getHashLoginServiceProperties(); HashLoginService loginService = new HashLoginService(realm, loginServiceProperties); server.addBean(loginService); return configureCommonAuthentication(server, connector, config, Constraint.__BASIC_AUTH, allowedRoles, new BasicAuthenticator(), null, loginService); }
/** * Start the controller as a RESTful server. * Use the setters of this class to change the default * port and host. * <br> * This method is blocking until the server is initialized. */ public final boolean startTheControllerServer() { //Jersey ResourceConfig config = new ResourceConfig(); config.register(JacksonFeature.class); config.register(new EMController(this)); config.register(LoggingFeature.class); //Jetty controllerServer = new Server(InetSocketAddress.createUnresolved( getControllerHost(), getControllerPort())); ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setShowStacks(true); controllerServer.setErrorHandler(errorHandler); ServletHolder servlet = new ServletHolder(new ServletContainer(config)); ServletContextHandler context = new ServletContextHandler(controllerServer, ControllerConstants.BASE_PATH + "/*"); context.addServlet(servlet, "/*"); try { controllerServer.start(); } catch (Exception e) { SimpleLogger.error("Failed to start Jetty: " + e.getMessage()); controllerServer.destroy(); } //just make sure we start from a clean state newSearch(); SimpleLogger.info("Started controller server on: " + controllerServer.getURI()); return true; }
public void run() { try { System.out.println("Listening on Reqs..."); Server server = new Server(Config.PORT); // Handler for the voting API ContextHandler votingContext = new ContextHandler(); votingContext.setContextPath("/vote"); votingContext.setHandler(new VoteHandler()); // Handler for the stats API ContextHandler statContext = new ContextHandler(); statContext.setContextPath("/stats"); statContext.setHandler(new StatsHandler()); // summing all the Handlers up to one ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] { votingContext, statContext}); server.setHandler(contexts); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } }
@Test public void testSetPortWithBindAddress() throws Exception { try { final Server jetty = JettyHelper.initJetty("10.123.50.1", 10480, SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.WEB)); assertNotNull(jetty); assertNotNull(jetty.getConnectors()[0]); assertEquals(10480, ((ServerConnector) jetty.getConnectors()[0]).getPort()); } catch (GemFireConfigException e) { fail(e.getMessage()); } }