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 void start(int listenPort, String dbname) throws Exception { if (Objects.nonNull(server) && server.isRunning()) { LOG.info("ineternal webui already running at port [" + listenPort + "]."); throw new Exception("already running at port[" + listenPort + "]"); } // remove old connectors Connector[] oldConnectors = server.getConnectors(); if (Objects.nonNull(oldConnectors)) { for (Connector oldc : oldConnectors) { server.removeConnector(oldc); } } // add new connector ServerConnector connector = new ServerConnector(server); connector.setPort(listenPort); server.setConnectors(new Connector[] { connector }); // set dbname ServletContextHandler contextHandler = (ServletContextHandler) server.getHandler(); contextHandler.setAttribute("dbname", dbname); server.start(); LOG.info("internal webui server started with listening port [" + listenPort + "]."); }
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(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(); }
public void run(final int port) { try { final Server server = createServer(); final ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); for (final MinijaxApplication application : applications) { addApplication(context, application); } final ServerConnector connector = createConnector(server); connector.setPort(port); server.setConnectors(new Connector[] { connector }); server.start(); server.join(); } catch (final Exception ex) { throw new MinijaxException(ex); } }
public void prepare() { try { Tools.verifyLocalPort("DBServer ", port()); server = new Server(); DefaultHandler webHandler = new DefaultHandler(); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{getResourceHandler(), getUIWSHandler(), webHandler}); ServerConnector connector = new ServerConnector(server); connector.setPort(port()); server.setConnectors(new Connector[]{connector}); server.setHandler(handlers); LOG.log(Level.INFO, "DB Server on : http://{0}:{1}", new Object[]{Tools.IP(), port() + ""}); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } }
/** * Create a REST server for this herder using the specified configs. */ public RestServer(WorkerConfig config) { this.config = config; // To make the advertised port available immediately, we need to do some configuration here String hostname = config.getString(WorkerConfig.REST_HOST_NAME_CONFIG); Integer port = config.getInt(WorkerConfig.REST_PORT_CONFIG); jettyServer = new Server(); ServerConnector connector = new ServerConnector(jettyServer); if (hostname != null && !hostname.isEmpty()) connector.setHost(hostname); connector.setPort(port); jettyServer.setConnectors(new Connector[]{connector}); }
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 void start() throws Exception { URL keystoreUrl = IntegrationTestServer.class.getClassLoader().getResource("keystore.jks"); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(keystoreUrl.getPath()); sslContextFactory.setKeyStorePassword("keystore"); SecureRequestCustomizer src = new SecureRequestCustomizer(); HttpConfiguration httpsConfiguration = new HttpConfiguration(); httpsConfiguration.setSecureScheme("https"); httpsConfiguration.addCustomizer(src); ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfiguration)); https.setPort(this.httpsPort); this.server.setConnectors(new Connector[] { https }); ResourceConfig resourceConfig = new ResourceConfig(this.resourceClass); ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/*"); servletContextHandler.addServlet(servletHolder, "/*"); this.server.start(); }
private static void installListeners(Server server, Collection<? extends InetSocketAddress> addresses) { final List<Connector> connectors = new ArrayList<>(addresses.size()); for (InetSocketAddress address : addresses) { final ServerConnector server_connector = new ServerConnector(server); server_connector.setReuseAddress(true); if (address.getAddress() != null) { if (!address.getAddress().isAnyLocalAddress()) { LOG.log(Level.INFO, "Binding API server address: {0}", address.getAddress().getHostAddress()); server_connector.setHost(address.getAddress().getHostAddress()); } } else if (address.getHostString() != null) { LOG.log(Level.INFO, "Binding API server address name: {0}", address.getHostString()); server_connector.setHost(address.getHostString()); } LOG.log(Level.INFO, "Binding API server port: {0}", address.getPort()); server_connector.setPort(address.getPort()); connectors.add(server_connector); } server.setConnectors(connectors.toArray(new Connector[connectors.size()])); }
@Override public void lifeCycleStarted(LifeCycle bean) { if (bean instanceof Server) { Server server = (Server)bean; Connector[] connectors = server.getConnectors(); if (connectors == null || connectors.length == 0) { server.dumpStdErr(); throw new IllegalStateException("No Connector"); } else if (!Arrays.stream(connectors).allMatch(Connector::isStarted)) { server.dumpStdErr(); throw new IllegalStateException("Connector not started"); } ContextHandler context = server.getChildHandlerByClass(ContextHandler.class); if (context == null || !context.isAvailable()) { server.dumpStdErr(); throw new IllegalStateException("No Available Context"); } } }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { JettyEmbeddedWebAppContext context = new JettyEmbeddedWebAppContext(); int port = (getPort() >= 0 ? getPort() : 0); InetSocketAddress address = new InetSocketAddress(getAddress(), port); Server server = createServer(address); configureWebAppContext(context, initializers); server.setHandler(addHandlerWrappers(context)); this.logger.info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { SslContextFactory sslContextFactory = new SslContextFactory(); configureSsl(sslContextFactory, getSsl()); AbstractConnector connector = getSslServerConnectorFactory() .getConnector(server, sslContextFactory, port); server.setConnectors(new Connector[] { connector }); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return getJettyEmbeddedServletContainer(server); }
public void removeFromServer(Server server) { for (Connector connector : server.getConnectors()) { if (connector instanceof NetworkTrafficServerConnector) { NetworkTrafficServerConnector serverConnector = (NetworkTrafficServerConnector)connector; if (serverConnector.getPort() == port && serverConnector.getHost().equals(host)) { server.removeConnector(serverConnector); if (server.isStarted()) { try { serverConnector.stop(); } catch (Exception e) { throw new RuntimeException(e); } } } } } }
/** * 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */ public static Server createServerInSource(int port, String contextPath) { Server server = new Server(); // 设置在JVM退出时关闭Jetty的钩子。 server.setStopAtShutdown(true); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); // 解决Windows下重复启动Jetty居然不报告端口冲突的问题. connector.setReuseAddress(false); server.setConnectors(new Connector[] { connector }); WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath); // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题. webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH); server.setHandler(webContext); return server; }
/** * Creates and starts the server with the current state (credentials, port). After startup, the method will return * and not block. * * @throws IllegalStateException if the server has already been started * @throws Exception if creation of the server fails */ public void start() throws Exception { if (jettyServer != null) { throw new IllegalStateException("Server already started"); } jettyServer = new Server(0); connector = new ServerConnector(jettyServer); // NOSONAR connector.setPort(getPort()); jettyServer.setConnectors(new Connector[]{connector}); HttpManagerBuilder builder = new HttpManagerBuilder(); builder.setResourceFactory(new MiltonWebDAVResourceFactory(this.rootFolder, userCredentials)); builder.setEnableBasicAuth(userCredentials != null && !userCredentials.isEmpty()); HttpManager mgr = builder.buildHttpManager(); jettyServer.setHandler(new MiltonHandler(mgr)); jettyServer.start(); while (!jettyServer.isStarted()) { Thread.sleep(50); } }
@Test public void testHttpConnectorsHttpsOnly() { System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH, "file:///tmp/keystore"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PATH, "file:///tmp/truststore"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_TYPE, "PKCS12"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYMANAGER_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_IDLE_TIMEOUT, "10001"); AthenzJettyContainer container = new AthenzJettyContainer(); container.createServer(100); HttpConfiguration httpConfig = container.newHttpConfiguration(); container.addHTTPConnectors(httpConfig, 0, 8082, 0); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 1); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertTrue(connectors[0].getProtocols().contains("ssl")); }
@Test public void testHttpConnectorsHttpOnly() { System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH, "file:///tmp/keystore"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PATH, "file:///tmp/truststore"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_TYPE, "PKCS12"); System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_KEYMANAGER_PASSWORD, "pass123"); System.setProperty(AthenzConsts.ATHENZ_PROP_IDLE_TIMEOUT, "10001"); AthenzJettyContainer container = new AthenzJettyContainer(); container.createServer(100); HttpConfiguration httpConfig = container.newHttpConfiguration(); container.addHTTPConnectors(httpConfig, 8081, 0, 0); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 1); assertEquals(connectors[0].getIdleTimeout(), 10001); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertFalse(connectors[0].getProtocols().contains("ssl")); }
@Test public void initContainerValidPorts() { System.setProperty(AthenzConsts.ATHENZ_PROP_HOME, "/tmp/ATHENZ_server"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "4080"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "4443"); AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer(); assertNotNull(container); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 2); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("ssl")); }
@Test public void initContainerOnlyHTTPSPort() { System.setProperty(AthenzConsts.ATHENZ_PROP_HOME, "/tmp/ATHENZ_server"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "0"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "4443"); System.setProperty("yahoo.zms.debug.user_authority", "true"); AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer(); assertNotNull(container); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 1); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertTrue(connectors[0].getProtocols().contains("ssl")); }
@Test public void initContainerOnlyHTTPPort() { System.setProperty(AthenzConsts.ATHENZ_PROP_HOME, "/tmp/ATHENZ_server"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "4080"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "0"); AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer(); assertNotNull(container); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 1); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertFalse(connectors[0].getProtocols().contains("ssl")); }
@Test public void initContainerInvalidHTTPPort() { System.setProperty(AthenzConsts.ATHENZ_PROP_HOME, "/tmp/ATHENZ_server"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "-10"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "4443"); AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer(); assertNotNull(container); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 2); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("ssl")); }
@Test public void initContainerInvalidHTTPSPort() { System.setProperty(AthenzConsts.ATHENZ_PROP_HOME, "/tmp/ATHENZ_server"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "4080"); System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "-10"); AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer(); assertNotNull(container); Server server = container.getServer(); Connector[] connectors = server.getConnectors(); assertEquals(connectors.length, 2); assertTrue(connectors[0].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("http/1.1")); assertTrue(connectors[1].getProtocols().contains("ssl")); }
@Before @Override public void setUp() throws Exception { server = new Server(9000); ServerConnector connector0 = new ServerConnector(server); connector0.setReuseAddress(true); server.setConnectors(new Connector[]{connector0}); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/service"); server.setHandler(context); context.addServlet(new ServletHolder(new EchoService()), "/EchoService"); server.start(); payload = readPayload(); super.setUp(); }
protected CamelServlet createServletForConnector(Server server, Connector connector, List<Handler> handlers, JettyHttpEndpoint endpoint) throws Exception { ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS); if (Server.getVersion().startsWith("8")) { context.getClass().getMethod("setConnectorNames", new Class[] {String[].class}) .invoke(context, new Object[] {new String[] {connector.getName()}}); } addJettyHandlers(server, handlers); CamelServlet camelServlet = new CamelContinuationServlet(); ServletHolder holder = new ServletHolder(); holder.setServlet(camelServlet); holder.setAsyncSupported(true); holder.setInitParameter(CamelServlet.ASYNC_PARAM, Boolean.toString(endpoint.isAsync())); context.addServlet(holder, "/*"); // use rest enabled resolver in case we use rest camelServlet.setServletResolveConsumerStrategy(new HttpRestServletResolveConsumerStrategy()); return camelServlet; }
protected ServletContextHandler createContext(Server server, Connector connector, List<Handler> handlers) throws Exception { ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS); server.addConnector(connector); if (handlers != null && !handlers.isEmpty()) { for (Handler handler : handlers) { if (handler instanceof HandlerWrapper) { ((HandlerWrapper) handler).setHandler(server.getHandler()); server.setHandler(handler); } else { HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(server.getHandler()); handlerCollection.addHandler(handler); server.setHandler(handlerCollection); } } } return context; }
protected Connector getSslSocketConnector(Server server, JettyHttpEndpoint endpoint) { Connector answer = null; /* if (sslSocketConnectors != null) { SslContextFactory con = sslSocketConnectors.get(endpoint.getPort()); if (con != null) { SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(con, null); @SuppressWarnings("resource") ServerConnector sc = new ServerConnector(server, sslConnectionFactory); sc.setPort(endpoint.getPort()); sc.setHost(endpoint.getHttpUri().getHost()); answer = sc; } } */ if (answer == null) { answer = createConnector(server, endpoint); } return answer; }
private Connector createSslSocketConnector(CamelContext context, int port) throws Exception { KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(this.getClass().getClassLoader().getResource("jsse/localhost.ks").toString()); ksp.setPassword(pwd); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyPassword(pwd); kmp.setKeyStore(ksp); SSLContextParameters sslContextParameters = new SSLContextParameters(); sslContextParameters.setKeyManagers(kmp); // From Camel 2.5.0 Camel-Jetty is using SslSelectChannelConnector instead of SslSocketConnector //SslSelectChannelConnector sslSocketConnector = new SslSelectChannelConnector(); //sslSocketConnector.getSslContextFactory().setSslContext(sslContextParameters.createSSLContext()); //sslSocketConnector.setPort(port); //return sslSocketConnector; return null; }
private Server initJettyServer(ComponentRepository repo) { SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(getPort()); connector.setConfidentialPort(getSecurePort()); connector.setRequestHeaderSize(16384); Server jettyServer = new Server(); jettyServer.setConnectors(new Connector[] {connector}); ContextHandlerCollection contexts = new ContextHandlerCollection(); HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(contexts); addHandlers(repo, jettyServer, contexts); jettyServer.setHandler(handlers); jettyServer.setStopAtShutdown(true); jettyServer.setGracefulShutdown(2000); jettyServer.setSendDateHeader(true); jettyServer.setSendServerVersion(true); ComponentInfo info = new ComponentInfo(Server.class, "jetty"); repo.registerComponent(info, jettyServer); repo.registerLifecycle(new ServerLifecycle(jettyServer)); return jettyServer; }
@BeforeClass public void startServer() throws Exception { int port = 49152 + RandomUtils.nextInt(65535 - 49152); String serverUrl = "http://localhost:" + port + "/jax"; SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); _jettyServer = new Server(); _jettyServer.setConnectors(new Connector[]{connector}); ContextHandlerCollection contexts = new ContextHandlerCollection(); HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(contexts); WebAppContext ogWebAppContext = new WebAppContext("RemoteViewRunnerTest", "/"); org.springframework.core.io.Resource resource = new ClassPathResource("web-engine"); ogWebAppContext.setBaseResource(Resource.newResource(resource.getFile())); DataViewRunnerResource viewRunnerResource = new DataViewRunnerResource(new TestViewRunner()); ComponentRepository repo = new ComponentRepository(ComponentLogger.Console.VERBOSE); repo.getRestComponents().publishResource(viewRunnerResource); repo.getRestComponents().publishHelper(new FudgeObjectBinaryConsumer()); repo.getRestComponents().publishHelper(new FudgeObjectBinaryProducer()); ogWebAppContext.setEventListeners(new EventListener[]{new ComponentRepositoryServletContextListener(repo)}); handlers.addHandler(ogWebAppContext); _jettyServer.setHandler(handlers); _jettyServer.start(); _remoteViewRunner = new RemoteViewRunner(URI.create(serverUrl)); }
@Test public void testMultipleConnectors() { BQRuntime runtime = testFactory.app("-s", "-c", "classpath:io/bootique/jetty/server/connectors.yml") .module(new UnitModule()) .createRuntime(); runtime.run(); // deprecated default connector must NOT be started Connector[] connectors = runtime.getInstance(Server.class).getConnectors(); assertEquals(2, connectors.length); Response r1NormalConnector = client.target("http://localhost:14001/").request().get(); assertEquals(Response.Status.OK.getStatusCode(), r1NormalConnector.getStatus()); assertEquals(OUT_CONTENT, r1NormalConnector.readEntity(String.class)); Response r2NormalConnector = client.target("http://localhost:14002/").request().get(); assertEquals(Response.Status.OK.getStatusCode(), r2NormalConnector.getStatus()); assertEquals(OUT_CONTENT, r2NormalConnector.readEntity(String.class)); }
@Test public void testAcceptorSelectorThreads() { BQRuntime runtime = testFactory.app("-s", "-c", "classpath:io/bootique/jetty/server/threads.yml") .autoLoadModules() .createRuntime(); runtime.run(); Connector[] connectors = runtime.getInstance(Server.class).getConnectors(); ServerConnector c1 = (ServerConnector) connectors[0]; assertEquals(3, c1.getAcceptors()); assertEquals(4, c1.getSelectorManager().getSelectorCount()); ServerConnector c2 = (ServerConnector) connectors[1]; // default counts are CPU count-sensitive, so do a sanity check instead of an exact match assertTrue(c2.getAcceptors() > 0); assertTrue(c2.getSelectorManager().getSelectorCount() > 0); }
@Test public void testApplication() throws Exception { Configuration conf = new Configuration(false); conf.addResource("dt-site-monitoring.xml"); Server server = new Server(0); Servlet servlet = new SamplePubSubWebSocketServlet(); ServletHolder sh = new ServletHolder(servlet); ServletContextHandler contextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); contextHandler.addServlet(sh, "/pubsub"); contextHandler.addServlet(sh, "/*"); server.start(); Connector[] connector = server.getConnectors(); conf.set("dt.attr.GATEWAY_CONNECT_ADDRESS", "localhost:" + connector[0].getLocalPort()); MRMonitoringApplication application = new MRMonitoringApplication(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(application, conf); LocalMode.Controller lc = lma.getController(); lc.run(10000); server.stop(); }
public static void newInstance(String host, int port, int maxThreads, int minThreads, int threadTimeoutMillis) { TinyHandler tinyHandler = TinyHandler.get(); JettyHandler jettyHandler = new JettyHandler(tinyHandler); QueuedThreadPool queuedThreadPool = new QueuedThreadPool(minThreads, maxThreads, threadTimeoutMillis); queuedThreadPool.setDetailedDump(false); Server server = new Server(queuedThreadPool); ServerConnector connector = getConnector(server, host, port); connector.setAcceptQueueSize(1000); server = connector.getServer(); server.setConnectors(new Connector[]{connector}); server.setHandler(jettyHandler); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
public static void newExecutorInstance(String host, int port) { TinyHandler tinyHandler = TinyHandler.get(); JettyHandler jettyHandler = new JettyHandler(tinyHandler); Server server = new Server(new ExecutorThreadPool(Executors.newWorkStealingPool())); ServerConnector connector = getConnector(server, host, port); server = connector.getServer(); server.setConnectors(new Connector[]{connector}); server.setHandler(jettyHandler); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
/** * 启动jetty */ private static void start() throws Exception { long bg = System.currentTimeMillis(); Server server = new Server(); Connector connector = new SelectChannelConnector(); connector.setPort(PORT); server.setConnectors(new Connector[] {connector}); WebAppContext webAppContext = new WebAppContext("src/main/webapp", "/"); webAppContext.setDescriptor("src/main/webapp/WEB-INF/web.xml"); webAppContext.setDisplayName("multilanguage"); WebAppClassLoader classLoader = new WebAppClassLoader(webAppContext); webAppContext.setClassLoader(classLoader); webAppContext.setParentLoaderPriority(true); server.setHandler(webAppContext); System.out.println("ContextPath: " + webAppContext.getContextPath() + "; Descriptor: " + webAppContext.getDescriptor()); server.start(); long time = System.currentTimeMillis() - bg; System.out.println("Jetty started in " + time + "ms"); }
public void start() throws Exception { server = new Server(); Connector connector = new SelectChannelConnector(); connector.setPort(port); server.setConnectors(new Connector[]{connector}); RequestLogHandler requestLogHandler = new RequestLogHandler(); configureRequestLogImpl(); requestLogHandler.setRequestLog(requestLogImpl); HandlerList handlers = new HandlerList(); handlers.addHandler(requestLogHandler); handlers.addHandler(getRequestHandler()); server.setHandler(handlers); server.start(); }
public void start() { try { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); connector.setIdleTimeout(idleTimeout); server.setConnectors(new Connector[] { connector }); HandlerList handlers = new HandlerList(); handlers.addHandler(handler); server.setHandler(handlers); server.start(); server.join(); } catch (Exception e) { // TODO : log here System.exit(1); } }
synchronized public void removeConnector(String host, int port) { Connector[] connectors = server.getConnectors(); if (connectors == null) return; for (Connector connector : connectors) { //Fix getPort() if (connector.getHost().equals(host) && connector.getLocalPort() == port) { if (connector.isStarted() || connector.isStarting()) { try { connector.stop(); } catch (Exception ex) { log.severe("Couldn't stop connector: " + connector + " " + ex); throw new RuntimeException(ex); } } server.removeConnector(connector); if (connectors.length == 1) { log.info("No more connectors, stopping Jetty server"); stopIfRunning(); } break; } } }
private ServerConnector findServerConnector(Server server) { final Connector[] connectors = server.getConnectors(); if (connectors.length == 0) { throw new IllegalStateException("server has no connectors"); } for (final Connector c : connectors) { if (!(c instanceof ServerConnector)) { continue; } return (ServerConnector) c; } throw new IllegalStateException("Server has no associated ServerConnector"); }