private static void initServer(Properties properties) throws Exception { Integer port = Integer.valueOf(properties.getProperty("server.port")); String host = properties.getProperty("server.host"); Integer clientId = Integer.valueOf(properties.getProperty("client.id")); String clientSecret = properties.getProperty("client.secret"); HandlerCollection handlers = new HandlerCollection(); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setWelcomeFiles(new String[]{"index.html"}); resourceHandler.setResourceBase(Application.class.getResource("/static").getPath()); VkApiClient vk = new VkApiClient(new HttpTransportClient()); handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)}); Server server = new Server(port); server.setHandler(handlers); server.start(); server.join(); }
public static void startServer(String[] args) throws Exception { Server server = new Server(8080); WebAppContext ctx = new WebAppContext(); ctx.setContextPath("/"); ctx.setWar("src/main/webapp/"); HandlerCollection hc = new HandlerCollection(); hc.setHandlers(new Handler[] {ctx}); server.setHandler(hc); server.setStopAtShutdown(true); server.start(); server.join(); // server.removeBean(o); // server.addBean(o); }
/** * To test that the CF client is able to go through a proxy, we point the CC client to a broken url that can only be resolved by going * through an inJVM proxy which rewrites the URI. This method starts this inJvm proxy. * * @throws Exception */ private static void startInJvmProxy() throws Exception { inJvmProxyPort = getNextAvailablePort(8080); inJvmProxyServer = new Server(new InetSocketAddress("127.0.0.1", inJvmProxyPort)); // forcing use of loopback // that will be used both for Httpclient proxy and SocketDestHelper QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMinThreads(1); inJvmProxyServer.setThreadPool(threadPool); HandlerCollection handlers = new HandlerCollection(); inJvmProxyServer.setHandler(handlers); ServletHandler servletHandler = new ServletHandler(); handlers.addHandler(servletHandler); nbInJvmProxyRcvReqs = new AtomicInteger(); ChainedProxyServlet chainedProxyServlet = new ChainedProxyServlet(httpProxyConfiguration, nbInJvmProxyRcvReqs); servletHandler.addServletWithMapping(new ServletHolder(chainedProxyServlet), "/*"); // Setup proxy handler to handle CONNECT methods ConnectHandler proxyHandler; proxyHandler = new ChainedProxyConnectHandler(httpProxyConfiguration, nbInJvmProxyRcvReqs); handlers.addHandler(proxyHandler); inJvmProxyServer.start(); }
/** * @param registry Prometheus CollectorRegistry to register the default exporters. * @param httpPort The port the Server runs on. * @return a Jetty Server with Prometheus' default exporters registered. */ public static Server serverWithStatisticsCollection(CollectorRegistry registry, int httpPort) { Server server = new Server(httpPort); new StandardExports().register(registry); new MemoryPoolsExports().register(registry); new GarbageCollectorExports().register(registry); new ThreadExports().register(registry); new ClassLoadingExports().register(registry); new VersionInfoExports().register(registry); HandlerCollection handlers = new HandlerCollection(); StatisticsHandler statisticsHandler = new StatisticsHandler(); statisticsHandler.setServer(server); handlers.addHandler(statisticsHandler); new JettyStatisticsCollector(statisticsHandler).register(); server.setHandler(handlers); return server; }
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; }
@Bean public EmbeddedServletContainerFactory jettyConfigBean() { DynamicPropertyFactory propertyFactory = DynamicPropertyFactory.getInstance(); String accessLogFilePath = propertyFactory.getStringProperty("server.accessLog.config.file", ACCESS_LOG_FILE_PATH).getValue(); JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory = new JettyEmbeddedServletContainerFactory(); jettyEmbeddedServletContainerFactory.addServerCustomizers(new org.springframework.boot.context.embedded.jetty.JettyServerCustomizer() { public void customize(Server server) { HandlerCollection handlers = new HandlerCollection(); for (Handler handler : server.getHandlers()) { handlers.addHandler(handler); } RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLogImpl = new RequestLogImpl(); requestLogImpl.setFileName(accessLogFilePath); requestLogHandler.setRequestLog(requestLogImpl); handlers.addHandler(requestLogHandler); server.setHandler(handlers); LOGGER.info("Jetty Server Customized. Access Log Configuration File - {}", accessLogFilePath); } }); return jettyEmbeddedServletContainerFactory; }
protected void addJettyHandlers(Server server, List<Handler> handlers) { if (handlers != null && !handlers.isEmpty()) { for (Handler handler : handlers) { if (handler instanceof HandlerWrapper) { // avoid setting the security handler more than once if (!handler.equals(server.getHandler())) { ((HandlerWrapper) handler).setHandler(server.getHandler()); server.setHandler(handler); } } else { HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(server.getHandler()); handlerCollection.addHandler(handler); server.setHandler(handlerCollection); } } } }
public static Server initJetty(final String bindAddress, final int port, final LogWriterI18n log) throws Exception { final Server jettyServer = new Server(); // Add a handler collection here, so that each new context adds itself // to this collection. jettyServer.setHandler(new HandlerCollection()); // bind on address and port setAddressAndPort(jettyServer, bindAddress, port); if (bindAddress != null && !bindAddress.isEmpty()) { JettyHelper.bindAddress = bindAddress; } JettyHelper.port = port; return jettyServer; }
public void start() throws Exception { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); log.info("Server started at end point {}", getServiceUri()); }
public void start() throws PulsarServerException { log.info("Starting web socket proxy at port {}", conf.getWebServicePort()); try { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); } catch (Exception e) { throw new PulsarServerException(e); } }
public void start() throws PulsarServerException { try { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); log.info("Web Service started at {}", pulsar.getWebServiceAddress()); } catch (Exception e) { throw new PulsarServerException(e); } }
@Test public void wrappedHandlers() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() { @Override public void customize(Server server) { Handler handler = server.getHandler(); HandlerWrapper wrapper = new HandlerWrapper(); wrapper.setHandler(handler); HandlerCollection collection = new HandlerCollection(); collection.addHandler(wrapper); server.setHandler(collection); } })); this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); }
@Override public void configure( final Settings settings ) { final EngineConfigurator engineConfigurator = new EngineConfigurator(); engineConfigurator.configure( settings ); final ServletConfigurator servletConfigurator = new ServletConfigurator(); servletConfigurator.setEngine( engineConfigurator.getEngine() ); servletConfigurator.setDevSourceDirs( engineConfigurator.getEngine().getDevSourceDirs() ); servletConfigurator.configure( settings ); this.handlers = new HandlerCollection(); this.handlers.addHandler( servletConfigurator.getHandler() ); configureServer( settings.getAsSettings( "server" ) ); }
public static void main( String[] args ) throws Exception { Server server = new Server( 8080 ); WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" ); ContextHandlerCollection servlet_contexts = new ContextHandlerCollection(); webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() ); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } ); server.setHandler( handlers ); server.start(); server.join(); }
/** * * @param port * @param resourcePath */ public Olingo2SampleServer(int port, String resourcePath) { this.port = port; server = new org.eclipse.jetty.server.Server(port); WebAppContext webappcontext = new WebAppContext(); String contextPath = null; try { contextPath = Olingo2SampleServer.class.getResource(resourcePath).toURI().getPath(); } catch (URISyntaxException e) { LOG.error("Unable to read the resource at {}", resourcePath, e); } webappcontext.setContextPath("/"); webappcontext.setWar(contextPath); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()}); server.setHandler(handlers); }
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; }
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 wrappedHandlers() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() { @Override public void customize(Server server) { Handler handler = server.getHandler(); HandlerWrapper wrapper = new HandlerWrapper(); wrapper.setHandler(handler); HandlerCollection collection = new HandlerCollection(); collection.addHandler(wrapper); server.setHandler(collection); } })); this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); }
@Override public void customizeServer(Server server) { if(logFile != null) { HandlerCollection rootHandler = (HandlerCollection) server.getHandler(); List<Handler> handlers = new ArrayList<Handler>(); handlers.addAll(Arrays.asList(rootHandler.getHandlers())); RequestLogHandler requestLogHandler = new RequestLogHandler(); NCSARequestLog requestLog = new NCSARequestLog(logFile.getAbsolutePath()); requestLog.setRetainDays(0); requestLog.setAppend(true); requestLog.setExtended(extended); requestLog.setLogTimeZone("GMT"); requestLogHandler.setRequestLog(requestLog); handlers.add(requestLogHandler); rootHandler.setHandlers(handlers.toArray(new Handler[handlers.size()])); } }
/** * Add all the servlets to the server * including resource handler serving static files */ private void servletInit() { mainLog.info("Initializing servlets"); HandlerCollection handlers = new HandlerCollection(); Iterable<Handler> servletHandler = Iterables.transform(Configuration.getInstance().getServlets(), new Function<ServletConfig, Handler>() { @Override public Handler apply(ServletConfig servletConfig) { return buildServletHandler(servletConfig); } }); servletHandler.forEach((handler) -> { handlers.addHandler(handler); }); handlers.addHandler(buildResourceHandler()); server.setHandler(handlers); }
public static void main(String[] args) throws Exception { URI baseUri = UriBuilder.fromUri("http://localhost").port(SERVER_PORT) .build(); ResourceConfig config = new ResourceConfig(Calculator.class); Server server = JettyHttpContainerFactory.createServer(baseUri, config, false); ContextHandler contextHandler = new ContextHandler("/rest"); contextHandler.setHandler(server.getHandler()); ProtectionDomain protectionDomain = EmbeddedServer.class .getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setWelcomeFiles(new String[] { "index.html" }); resourceHandler.setResourceBase(location.toExternalForm()); System.out.println(location.toExternalForm()); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { resourceHandler, contextHandler, new DefaultHandler() }); server.setHandler(handlerCollection); server.start(); server.join(); }
private static HandlerCollection createHandlers( final GatewayConfig config, final GatewayServices services, final ContextHandlerCollection contexts) { HandlerCollection handlers = new HandlerCollection(); RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(new AccessHandler()); TraceHandler traceHandler = new TraceHandler(); traceHandler.setHandler(contexts); traceHandler.setTracedBodyFilter(System.getProperty("org.apache.knox.gateway.trace.body.status.filter")); CorrelationHandler correlationHandler = new CorrelationHandler(); correlationHandler.setHandler(traceHandler); DefaultTopologyHandler defaultTopoHandler = new DefaultTopologyHandler(config, services, contexts); handlers.setHandlers(new Handler[]{correlationHandler, defaultTopoHandler, logHandler}); return handlers; }
/** * Hook up Jetty handlers. Do this before start() is called. */ public void registerHandlers(HandlerWrapper s) { GateHandler gh = new GateHandler(); AddCommonResponseHeadersHandler rhh = new AddCommonResponseHeadersHandler(); ExtensionHandler1 eh1 = new ExtensionHandler1(); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS ); context.setContextPath("/"); context.addServlet(H2oNpsBinServlet.class, "/3/NodePersistentStorage.bin/*"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile.bin"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset.bin"); context.addServlet(H2oDefaultServlet.class, "/"); Handler[] handlers = {gh, rhh, eh1, context}; HandlerCollection hc = new HandlerCollection(); hc.setHandlers(handlers); s.setHandler(hc); }
private Handler configureRedirectionRules(Handler appHandler) { RewriteHandler handler = new RewriteHandler(); handler.setRewriteRequestURI(false); handler.setRewritePathInfo(false); handler.setOriginalPathAttribute("requestedPath"); RewriteRegexRule uiRewriteRule = new RewriteRegexRule(); uiRewriteRule.setRegex("^/collector/.*"); uiRewriteRule.setReplacement("/"); handler.addRule(uiRewriteRule); handler.setHandler(appHandler); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] {handler, appHandler}); return handlerCollection; }
public static void main(String[] args) throws Exception { Server server = new Server(15000); HandlerCollection hc = new HandlerCollection(); ResourceHandler rh = new ResourceHandler(); rh.setBaseResource(Resource.newClassPathResource("/com/frinika/web/content/")); rh.setDirectoriesListed(true); hc.addHandler(rh); server.setHandler(hc); server.start(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initAndShowGUI(); } }); }
protected static void findWarsOnClassPath(Server server, HandlerCollection handlers, ClassLoader classLoader, Set<String> foundURLs, Integer port) { try { Enumeration<URL> resources = classLoader.getResources("WEB-INF/web.xml"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); String text = url.toString(); if (text.startsWith("jar:")) { text = text.substring(4); } createWebapp(handlers, foundURLs, port, text); } } catch (Exception e) { System.out.println("Failed to find web.xml on classpath: " + e); e.printStackTrace(); } }
public static void main(String[] args) throws Exception { Server server = new Server(8080); // add web applications HandlerCollection handlers = new HandlerCollection(); Preconditions.checkArgument(args != null && args.length > 0, "Missing args: web project. Please pass a list of web projects, e.g.: JettyServer helloworld"); for (String arg : args) { Iterator<String> it = Splitter.on(":").split(arg).iterator(); String domain = it.next(); String projectName = it.hasNext() ? it.next() : domain; WebAppContext webappContext = createContext(domain, projectName); handlers.addHandler(webappContext); } server.setHandler(handlers); // enable web 3.0 annotations Configuration.ClassList classList = Configuration.ClassList.setServerDefault(server); classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName()); server.start(); server.join(); }
@Override protected void registerHandlers(HandlerWrapper handlerWrapper, ServletContextHandler context) { // setup authenticating proxy servlet (each request is forwarded with BASIC AUTH) ServletHolder proxyServlet = new ServletHolder(Transparent.class); proxyServlet.setInitParameter("ProxyTo", _proxyTo); proxyServlet.setInitParameter("Prefix", "/"); proxyServlet.setInitParameter("BasicAuth", _credentials.toBasicAuth()); context.addServlet(proxyServlet, "/*"); // authHandlers assume the user is already authenticated HandlerCollection authHandlers = new HandlerCollection(); authHandlers.setHandlers(new Handler[]{ new AuthenticationHandler(), context, }); // handles requests of login form and delegates the rest to the authHandlers LoginHandler loginHandler = new LoginHandler("/login", "/loginError"); loginHandler.setHandler(authHandlers); // login handler is the root handler handlerWrapper.setHandler(loginHandler); }
/** * To test that the CF client is able to go through a proxy, we point the CC client to a broken url * that can only be resolved by going through an inJVM proxy which rewrites the URI. * This method starts this inJvm proxy. * @throws Exception */ private static void startInJvmProxy() throws Exception { inJvmProxyPort = getNextAvailablePort(8080); inJvmProxyServer = new Server(new InetSocketAddress("127.0.0.1", inJvmProxyPort)); //forcing use of loopback that will be used both for Httpclient proxy and SocketDestHelper QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMinThreads(1); inJvmProxyServer.setThreadPool(threadPool); HandlerCollection handlers = new HandlerCollection(); inJvmProxyServer.setHandler(handlers); ServletHandler servletHandler = new ServletHandler(); handlers.addHandler(servletHandler); nbInJvmProxyRcvReqs = new AtomicInteger(); // ChainedProxyServlet chainedProxyServlet = new ChainedProxyServlet(httpProxyConfiguration, nbInJvmProxyRcvReqs); // servletHandler.addServletWithMapping(new ServletHolder(chainedProxyServlet), "/*"); // Setup proxy handler to handle CONNECT methods ConnectHandler proxyHandler; // proxyHandler = new ChainedProxyConnectHandler(httpProxyConfiguration, nbInJvmProxyRcvReqs); // handlers.addHandler(proxyHandler); inJvmProxyServer.start(); }