private static void registerContextHanlder( ContextHandlerCollection contextHandlers, String path, AbstractHandler handler) { ContextHandler contextHandler = new ContextHandler(); contextHandler.setContextPath(path); contextHandler.setHandler(handler); contextHandlers.addHandler(contextHandler); }
public static void main(String args[]) throws Exception { Server server = new Server(8080); // Specify the Session ID Manager HashSessionIdManager idmanager = new HashSessionIdManager(); server.setSessionIdManager(idmanager); // Sessions are bound to a context. ContextHandler context = new ContextHandler("/"); server.setHandler(context); // Create the SessionHandler (wrapper) to handle the sessions HashSessionManager manager = new HashSessionManager(); SessionHandler sessions = new SessionHandler(manager); context.setHandler(sessions); // ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); // ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); // context.setContextPath("/"); // server.setHandler(h); // server.setSessionIdManager(sessionIdManager); /* context.addServlet(new ServletHolder(new HelloServlet()),"/*"); context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*"); context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*"); */ Canvas c = new Canvas(800, 900); context.setAttribute("myCanvas", c); sessions.setHandler(new HttpHandler()); server.start(); server.join(); }
public static void main(String[] args) throws Exception { Server server = new Server(8080); ContextHandler context = new ContextHandler("/"); context.setContextPath("/"); context.setHandler(new HelloHandler("Root Hello")); ContextHandler contextFR = new ContextHandler("/fr"); contextFR.setHandler(new HelloHandler("Bonjoir")); ContextHandler contextIT = new ContextHandler("/it"); contextIT.setHandler(new HelloHandler("Bongiorno")); ContextHandler contextV = new ContextHandler("/"); contextV.setVirtualHosts(new String[] {"127.0.0.2"}); contextV.setHandler(new HelloHandler("Virtual Hello")); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] {context, contextFR, contextIT, contextV}); server.setHandler(contexts); server.start(); server.join(); }
@Override protected void doStart() throws Exception { // copy security init parameters ContextHandler.Context context = ContextHandler.getCurrentContext(); if (context != null) { Enumeration<String> names = context.getInitParameterNames(); while (names != null && names.hasMoreElements()) { String name = names.nextElement(); if (name.startsWith("org.eclipse.jetty.security.") && getInitParameter(name) == null) setInitParameter(name, context.getInitParameter(name)); } } // complicated resolution of login and identity service to handle // many different ways these can be constructed and injected. if (_loginService == null) { setLoginService(findLoginService()); if (_loginService != null) unmanage(_loginService); } if (_identityService == null) { if (_loginService != null) setIdentityService(_loginService.getIdentityService()); if (_identityService == null) setIdentityService(findIdentityService()); if (_identityService == null) { if (_realmName != null) { setIdentityService(new DefaultIdentityService()); manage(_identityService); } } else unmanage(_identityService); } if (_loginService != null) { if (_loginService.getIdentityService() == null) _loginService.setIdentityService(_identityService); else if (_loginService.getIdentityService() != _identityService) throw new IllegalStateException("LoginService has different IdentityService to " + this); } Authenticator.Factory authenticatorFactory = getAuthenticatorFactory(); if (_authenticator == null && authenticatorFactory != null && _identityService != null) setAuthenticator( authenticatorFactory.getAuthenticator( getServer(), ContextHandler.getCurrentContext(), this, _identityService, _loginService)); if (_authenticator != null) _authenticator.setConfiguration(this); else if (_realmName != null) { LOG.warn("No Authenticator for " + this); throw new IllegalStateException("No Authenticator"); } super.doStart(); }
public void run() { Properties jettyProperties = new Properties(); String pFileName = PropertiesUtil.getJettyPropertiesFile(); try { jettyProperties.load(new FileInputStream(pFileName)); } catch (IOException e) { log.error("load properties from {} error.", pFileName); return; } // crate server server = new Server(Integer.parseInt(jettyProperties.getProperty(PropList.HTTP_PORT))); // Create the ResourceHandler. It is the object that will actually handle the request for a // given file. It is // a Jetty Handler object so it is suitable for chaining with other handlers as you will see in // other examples. ResourceHandler resource_handler = new ResourceHandler(); // Configure the ResourceHandler. Setting the resource base indicates where the files should be // served out of. // In this example it is the current directory but it can be configured to anything that the jvm // has access to. resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] {"index.html"}); resource_handler.setResourceBase(PropertiesUtil.getWebBaseDir()); log.debug(PropertiesUtil.getWebBaseDir()); // Add a single handler on context "/hello" ContextHandler context = new ContextHandler(); context.setContextPath("/LoadT"); context.setHandler(new LoadTHandler()); // Add the ResourceHandler to the server. GzipHandler gzip = new GzipHandler(); server.setHandler(gzip); // make handler chain HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] {resource_handler, context, new DefaultHandler()}); gzip.setHandler(handlers); try { server.start(); } catch (Exception e) { log.error("embedded jetty server start error.", e); } server.dumpStdErr(); /* try { server.join(); } catch (InterruptedException e) { log.info("jetty server interrupted", e); }*/ }
@Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { ContextHandler contextHandler = state().getContextHandler(); if (contextHandler != null) return contextHandler.getServletContext().createListener(clazz); try { return clazz.newInstance(); } catch (Exception e) { throw new ServletException(e); } }
public void staticResources(String resourceBase) { ResourceHandler extResourceHandler = new ResourceHandler(); extResourceHandler.setResourceBase(resourceBase); extResourceHandler.setWelcomeFiles(new String[] {"index.html"}); extResourceHandler.setDirectoriesListed(true); ContextHandler contextHandler = new ContextHandler(rootContext); contextHandler.setHandler(extResourceHandler); handlerList.add(contextHandler); }
public static void main(String[] args) throws Exception { Server server = new Server(); SocketConnector sc = new SocketConnector(); sc.setPort(8080); Connector[] connectors = new Connector[1]; connectors[0] = sc; server.setConnectors(connectors); ContextHandlerCollection cc = new ContextHandlerCollection(); ContextHandler ch = cc.addContext("/", "."); PseudoStreamingHandler pseudoStreamingHandler = new PseudoStreamingHandler(); ch.setHandler(pseudoStreamingHandler); ch.setAllowNullPathInfo(true); server.setHandler(cc); server.start(); }
@Override public void handle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (!isStarted()) { return; } final ContextModel matched = serverModel.matchPathToContext(target); if (matched != null) { // check for nulls and start complaining NullArgumentException.validateNotNull( matched.getHttpContext(), "The http Context of " + matched.getContextName() + " is null"); NullArgumentException.validateNotNull(getServer(), "The server is null!"); final ContextHandler context = ((JettyServerWrapper) getServer()).getContext(matched.getHttpContext()); try { NullArgumentException.validateNotNull(context, "Found context is Null"); context.handle(target, baseRequest, request, response); // CHECKSTYLE:OFF } catch (EofException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ServletException(e); } // CHECKSTYLE:ON } // now handle all other handlers for (Handler handler : getHandlers()) { if (matched != null && matchedContextEqualsHandler(matched, handler)) { continue; } handler.handle(target, baseRequest, request, response); } }
private void checkIfContextIsFree(String path) { Handler serverHandler = _server.getHandler(); if (serverHandler instanceof ContextHandler) { ContextHandler ctx = (ContextHandler) serverHandler; if (ctx.getContextPath().equals(path)) throw new RuntimeException("another context already bound to path " + path); } Handler[] handlers = _server.getHandlers(); if (handlers == null) return; for (Handler handler : handlers) { if (handler instanceof ContextHandler) { ContextHandler ctx = (ContextHandler) handler; if (ctx.getContextPath().equals(path)) throw new RuntimeException("another context already bound to path " + path); } } }
@BeforeClass public static void startServer() { _server = new Server(); _connector = new LocalConnector(_server); _server.setConnectors(new Connector[] {_connector}); ContextHandler _context = new ContextHandler(); _session = new SessionHandler(); HashLoginService _loginService = new HashLoginService(TEST_REALM); _loginService.putUser("fred", new Password("password")); _loginService.putUser("harry", new Password("password"), new String[] {"HOMEOWNER"}); _loginService.putUser("chris", new Password("password"), new String[] {"CONTRACTOR"}); _loginService.putUser("steven", new Password("password"), new String[] {"SALESCLERK"}); _context.setContextPath("/ctx"); _server.setHandler(_context); _context.setHandler(_session); _server.addBean(_loginService); }
@BeforeClass public static void setUpFakeMavenRepo() throws Exception { repo = TestDataHelper.getTestDataDirectory(new ResolverIntegrationTest()); // If we're running this test in IJ, then this path doesn't exist. Fall back to one that does if (!Files.exists(repo)) { repo = Paths.get("test/com/facebook/buck/maven/testdata"); } httpd = new HttpdForTests(); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setResourceBase(repo.toAbsolutePath().toString()); ContextHandler contextHandler = new ContextHandler("/"); contextHandler.setHandler(resourceHandler); contextHandler.setLogger(new StdErrLog()); httpd.addHandler(contextHandler); httpd.start(); }
@Override public void callContextInitialized(ServletContextListener l, ServletContextEvent e) { try { // toggle state of the dynamic API so that the listener cannot use it if (isProgrammaticListener(l)) this.getServletContext().setEnabled(false); super.callContextInitialized(l, e); } finally { // untoggle the state of the dynamic API this.getServletContext().setEnabled(true); } }
private void addResourceHandler(String contextPath, String filePath) throws Exception { if (handlerCollection != null) { logger.log(Level.INFO, "Adding resource : " + contextPath + "=>" + filePath); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(filePath); logger.log(Level.INFO, "serving: " + resourceHandler.getBaseResource()); ContextHandler contextHandler = new ContextHandler(contextPath); contextHandler.setHandler(resourceHandler); handlerCollection.addHandler(contextHandler); try { resourceHandler.start(); contextHandler.start(); } catch (Exception e) { logger.log(Level.INFO, "Could not start resource context", e); } } }
public void start() { server = new Server(port); // Override the context classloader, so that Jetty uses the plugin classloader not the main // DMDirc loader. final Thread currentThread = Thread.currentThread(); final ClassLoader classLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(getClass().getClassLoader()); try { final ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setWelcomeFiles(new String[] {"index.html"}); resourceHandler.setBaseResource(Resource.newClassPathResource("/www")); final ResourceHandler clientResourceHandler = new ResourceHandler(); clientResourceHandler.setBaseResource(Resource.newClassPathResource("/com/dmdirc/res/")); final ContextHandler clientResourceContext = new ContextHandler("/res"); clientResourceContext.setHandler(clientResourceHandler); final ServletContextHandler wsHandler = new ServletContextHandler(); wsHandler.setContextPath("/"); wsHandler.addServlet(WebUiWebSocketServlet.class, "/ws"); HandlerList handlers = new HandlerList(); handlers.setHandlers( new Handler[] {resourceHandler, clientResourceContext, wsHandler, new DefaultHandler()}); server.setHandler(handlers); server.start(); } catch (Exception ex) { LOG.error(LogUtils.USER_ERROR, "Unable to start web server", ex); server = null; } finally { // Restore the usual context class loader. currentThread.setContextClassLoader(classLoader); } }
private ContextHandler systemRestart() { AbstractHandler system = new AbstractHandler() { @Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { restartContexts(); response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("<h1>Done</h1>"); } }; ContextHandler context = new ContextHandler(); context.setContextPath("/vraptor/restart"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); context.setHandler(system); return context; }
public static void main(String[] args) throws Exception { // When run from app-runner, you must use the port set in the environment variable web.port int port = Integer.parseInt(firstNonNull(System.getenv("web.port"), "8080")); InetSocketAddress addr = new InetSocketAddress("localhost", port); Server jettyServer = new Server(addr); jettyServer.setStopAtShutdown(true); HandlerList handlers = new HandlerList(); // TODO: set your own handlers handlers.addHandler(resourceHandler()); // you must serve everything from a directory named after your app ContextHandler ch = new ContextHandler(); ch.setContextPath("/maven"); ch.setHandler(handlers); jettyServer.setHandler(ch); jettyServer.start(); log.info("Started app at http://localhost:" + port + ch.getContextPath()); jettyServer.join(); }
/** * Finish constructing handlers and link them together. * * @see org.eclipse.jetty.server.handler.ContextHandler#startContext() */ @Override protected void startContext() throws Exception { ServletContainerInitializerCaller sciBean = getBean(ServletContainerInitializerCaller.class); if (sciBean != null) sciBean.start(); if (_servletHandler != null) { // Call decorators on all holders, and also on any EventListeners before // decorators are called on any other classes (like servlets and filters) if (_servletHandler.getListeners() != null) { for (ListenerHolder holder : _servletHandler.getListeners()) { _objFactory.decorate(holder.getListener()); } } } super.startContext(); // OK to Initialize servlet handler now that all relevant object trees have been started if (_servletHandler != null) _servletHandler.initialize(); }
public static void main(String[] args) throws Exception { // Create the Server object and a corresponding ServerConnector and then set the port for the // connector. In // this example the server will listen on port 8090. If you set this to port 0 then when the // server has been // started you can called connector.getLocalPort() to programmatically get the port the server // started on. Server server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(8090); server.setConnectors(new Connector[] {connector}); // Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path // but this could // be anything you like for builing out your url. Note how we are setting the ResourceBase using // our jetty // maven testing utilities to get the proper resource directory, you needn't use these, // you simply need to supply the paths you are looking to serve content from. ContextHandler context0 = new ContextHandler(); context0.setContextPath("/"); ResourceHandler rh0 = new ResourceHandler(); rh0.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0"))); context0.setHandler(rh0); // Rinse and repeat the previous item, only specifying a different resource base. ContextHandler context1 = new ContextHandler(); context1.setContextPath("/"); ResourceHandler rh1 = new ResourceHandler(); rh1.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1"))); context1.setHandler(rh1); // Create a ContextHandlerCollection and set the context handlers to it. This will let jetty // process urls // against the declared contexts in order to match up content. ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] {context0, context1}); server.setHandler(contexts); // Start things up! By using the server.join() the server thread will join with the current // thread. // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more // details. server.start(); System.err.println(server.dump()); server.join(); }
/* * @see javax.servlet.RequestDispatcher#forward(javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ protected void forward(ServletRequest request, ServletResponse response, DispatcherType dispatch) throws ServletException, IOException { Request baseRequest = (request instanceof Request) ? ((Request) request) : HttpChannel.getCurrentHttpChannel().getRequest(); Response base_response = baseRequest.getResponse(); base_response.resetForForward(); if (!(request instanceof HttpServletRequest)) request = new ServletRequestHttpWrapper(request); if (!(response instanceof HttpServletResponse)) response = new ServletResponseHttpWrapper(response); final boolean old_handled = baseRequest.isHandled(); final String old_uri = baseRequest.getRequestURI(); final String old_context_path = baseRequest.getContextPath(); final String old_servlet_path = baseRequest.getServletPath(); final String old_path_info = baseRequest.getPathInfo(); final String old_query = baseRequest.getQueryString(); final Attributes old_attr = baseRequest.getAttributes(); final DispatcherType old_type = baseRequest.getDispatcherType(); MultiMap<String> old_params = baseRequest.getParameters(); try { baseRequest.setHandled(false); baseRequest.setDispatcherType(dispatch); if (_named != null) _contextHandler.handle( _named, baseRequest, (HttpServletRequest) request, (HttpServletResponse) response); else { // process any query string from the dispatch URL String query = _dQuery; if (query != null) { // force parameter extraction if (old_params == null) { baseRequest.extractParameters(); old_params = baseRequest.getParameters(); } baseRequest.mergeQueryString(query); } ForwardAttributes attr = new ForwardAttributes(old_attr); // If we have already been forwarded previously, then keep using the established // original value. Otherwise, this is the first forward and we need to establish the values. // Note: the established value on the original request for pathInfo and // for queryString is allowed to be null, but cannot be null for the other values. if (old_attr.getAttribute(FORWARD_REQUEST_URI) != null) { attr._pathInfo = (String) old_attr.getAttribute(FORWARD_PATH_INFO); attr._query = (String) old_attr.getAttribute(FORWARD_QUERY_STRING); attr._requestURI = (String) old_attr.getAttribute(FORWARD_REQUEST_URI); attr._contextPath = (String) old_attr.getAttribute(FORWARD_CONTEXT_PATH); attr._servletPath = (String) old_attr.getAttribute(FORWARD_SERVLET_PATH); } else { attr._pathInfo = old_path_info; attr._query = old_query; attr._requestURI = old_uri; attr._contextPath = old_context_path; attr._servletPath = old_servlet_path; } baseRequest.setRequestURI(_uri); baseRequest.setContextPath(_contextHandler.getContextPath()); baseRequest.setServletPath(null); baseRequest.setPathInfo(_uri); baseRequest.setAttributes(attr); _contextHandler.handle( _path, baseRequest, (HttpServletRequest) request, (HttpServletResponse) response); if (!baseRequest.getHttpChannelState().isAsync()) commitResponse(response, baseRequest); } } finally { baseRequest.setHandled(old_handled); baseRequest.setRequestURI(old_uri); baseRequest.setContextPath(old_context_path); baseRequest.setServletPath(old_servlet_path); baseRequest.setPathInfo(old_path_info); baseRequest.setAttributes(old_attr); baseRequest.setParameters(old_params); baseRequest.setQueryString(old_query); baseRequest.setDispatcherType(old_type); } }
public void configureContextHandler() throws Exception { if (_configured) return; _configured = true; // Override for bundle root may have been set String bundleOverrideLocation = (String) _properties.get(OSGiWebappConstants.JETTY_BUNDLE_INSTALL_LOCATION_OVERRIDE); if (bundleOverrideLocation == null) bundleOverrideLocation = (String) _properties.get(OSGiWebappConstants.SERVICE_PROP_BUNDLE_INSTALL_LOCATION_OVERRIDE); // Location on filesystem of bundle or the bundle override location File bundleLocation = BundleFileLocatorHelperFactory.getFactory().getHelper().getBundleInstallLocation(_bundle); File root = (bundleOverrideLocation == null ? bundleLocation : new File(bundleOverrideLocation)); Resource rootResource = Resource.newResource( BundleFileLocatorHelperFactory.getFactory() .getHelper() .getLocalURL(root.toURI().toURL())); // try and make sure the rootResource is useable - if its a jar then make it a jar file url if (rootResource.exists() && !rootResource.isDirectory() && !rootResource.toString().startsWith("jar:")) { Resource jarResource = JarResource.newJarResource(rootResource); if (jarResource.exists() && jarResource.isDirectory()) rootResource = jarResource; } // Set the base resource of the ContextHandler, if not already set, can also be overridden by // the context xml file if (_contextHandler != null && _contextHandler.getBaseResource() == null) { _contextHandler.setBaseResource(rootResource); } // Use a classloader that knows about the common jetty parent loader, and also the bundle OSGiClassLoader classLoader = new OSGiClassLoader(getServerInstanceWrapper().getParentClassLoaderForWebapps(), _bundle); // if there is a context file, find it and apply it if (_contextFile == null && _contextHandler == null) throw new IllegalStateException("No context file or ContextHandler"); if (_contextFile != null) { // apply the contextFile, creating the ContextHandler, the DeploymentManager will register // it in the ContextHandlerCollection Resource res = null; // try to find the context file in the filesystem if (_contextFile.startsWith("/")) res = getFileAsResource(_contextFile); // try to find it relative to jetty home if (res == null) { // See if the specific server we are related to has jetty.home set String jettyHome = (String) getServerInstanceWrapper() .getServer() .getAttribute(OSGiServerConstants.JETTY_HOME); if (jettyHome != null) res = getFileAsResource(jettyHome, _contextFile); // try to see if a SystemProperty for jetty.home is set if (res == null) { jettyHome = System.getProperty(OSGiServerConstants.JETTY_HOME); if (jettyHome != null) { if (jettyHome.startsWith("\"") || jettyHome.startsWith("'")) jettyHome = jettyHome.substring(1); if (jettyHome.endsWith("\"") || (jettyHome.endsWith("'"))) jettyHome = jettyHome.substring(0, jettyHome.length() - 1); res = getFileAsResource(jettyHome, _contextFile); if (LOG.isDebugEnabled()) LOG.debug("jetty home context file:" + res); } } } // try to find it relative to an override location that has been specified if (res == null) { if (bundleOverrideLocation != null) { res = getFileAsResource( Resource.newResource(bundleOverrideLocation).getFile(), _contextFile); if (LOG.isDebugEnabled()) LOG.debug("Bundle override location context file:" + res); } } // try to find it relative to the bundle in which it is being deployed if (res == null) { if (_contextFile.startsWith("./")) _contextFile = _contextFile.substring(1); if (!_contextFile.startsWith("/")) _contextFile = "/" + _contextFile; URL contextURL = _bundle.getEntry(_contextFile); if (contextURL != null) res = Resource.newResource(contextURL); } // apply the context xml file, either to an existing ContextHandler, or letting the // it create the ContextHandler as necessary if (res != null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); LOG.debug("Context classloader = " + cl); try { Thread.currentThread().setContextClassLoader(classLoader); XmlConfiguration xmlConfiguration = new XmlConfiguration(res.getInputStream()); HashMap properties = new HashMap(); // put the server instance in properties.put("Server", getServerInstanceWrapper().getServer()); // put in the location of the bundle root properties.put("bundle.root", rootResource.toString()); // insert the bundle's location as a property. xmlConfiguration.getProperties().putAll(properties); if (_contextHandler == null) _contextHandler = (ContextHandler) xmlConfiguration.configure(); else xmlConfiguration.configure(_contextHandler); } finally { Thread.currentThread().setContextClassLoader(cl); } } } // Set up the class loader we created _contextHandler.setClassLoader(classLoader); // If a bundle/service property specifies context path, let it override the context xml String contextPath = (String) _properties.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH); if (contextPath == null) contextPath = (String) _properties.get(OSGiWebappConstants.SERVICE_PROP_CONTEXT_PATH); if (contextPath != null) _contextHandler.setContextPath(contextPath); // osgi Enterprise Spec r4 p.427 _contextHandler.setAttribute( OSGiWebappConstants.OSGI_BUNDLECONTEXT, _bundle.getBundleContext()); // make sure we protect also the osgi dirs specified by OSGi Enterprise spec String[] targets = _contextHandler.getProtectedTargets(); int length = (targets == null ? 0 : targets.length); String[] updatedTargets = null; if (targets != null) { updatedTargets = new String[length + OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy(targets, 0, updatedTargets, 0, length); } else updatedTargets = new String[OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length]; System.arraycopy( OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS, 0, updatedTargets, length, OSGiWebappConstants.DEFAULT_PROTECTED_OSGI_TARGETS.length); _contextHandler.setProtectedTargets(updatedTargets); }
@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(); }
protected void initializeServerWithConfig(final JUnitHttpServer config) { Server server = null; if (config.https()) { server = new Server(); final SslContextFactory factory = new SslContextFactory(config.keystore()); factory.setKeyStorePath(config.keystore()); factory.setKeyStorePassword(config.keystorePassword()); factory.setKeyManagerPassword(config.keyPassword()); factory.setTrustStore(config.keystore()); factory.setTrustStorePassword(config.keystorePassword()); final SslSocketConnector connector = new SslSocketConnector(factory); connector.setPort(config.port()); server.setConnectors(new Connector[] {connector}); } else { server = new Server(config.port()); } m_server = server; final ContextHandler context1 = new ContextHandler(); context1.setContextPath("/"); context1.setWelcomeFiles(new String[] {"index.html"}); context1.setResourceBase(config.resource()); context1.setClassLoader(Thread.currentThread().getContextClassLoader()); context1.setVirtualHosts(config.vhosts()); final ContextHandler context = context1; Handler topLevelHandler = null; final HandlerList handlers = new HandlerList(); if (config.basicAuth()) { // check for basic auth if we're configured to do so LOG.debug("configuring basic auth"); final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile()); loginService.setRefreshInterval(300000); m_server.addBean(loginService); final ConstraintSecurityHandler security = new ConstraintSecurityHandler(); final Set<String> knownRoles = new HashSet<String>(); knownRoles.add("user"); knownRoles.add("admin"); knownRoles.add("moderator"); final Constraint constraint = new Constraint(); constraint.setName("auth"); constraint.setAuthenticate(true); constraint.setRoles(knownRoles.toArray(new String[0])); final ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); mapping.setConstraint(constraint); security.setConstraintMappings(Collections.singletonList(mapping), knownRoles); security.setAuthenticator(new BasicAuthenticator()); security.setLoginService(loginService); security.setStrict(false); security.setRealmName("MyRealm"); security.setHandler(context); topLevelHandler = security; } else { topLevelHandler = context; } final Webapp[] webapps = config.webapps(); if (webapps != null) { for (final Webapp webapp : webapps) { final WebAppContext wac = new WebAppContext(); String path = null; if (!"".equals(webapp.pathSystemProperty()) && System.getProperty(webapp.pathSystemProperty()) != null) { path = System.getProperty(webapp.pathSystemProperty()); } else { path = webapp.path(); } if (path == null || "".equals(path)) { throw new IllegalArgumentException( "path or pathSystemProperty of @Webapp points to a null or blank value"); } wac.setWar(path); wac.setContextPath(webapp.context()); handlers.addHandler(wac); } } final ResourceHandler rh = new ResourceHandler(); rh.setWelcomeFiles(new String[] {"index.html"}); rh.setResourceBase(config.resource()); handlers.addHandler(rh); // fall through to default handlers.addHandler(new DefaultHandler()); context.setHandler(handlers); m_server.setHandler(topLevelHandler); }
/* ------------------------------------------------------------ */ private void relinkHandlers() { HandlerWrapper handler = this; // link session handler if (getSessionHandler() != null) { while (!(handler.getHandler() instanceof SessionHandler) && !(handler.getHandler() instanceof SecurityHandler) && !(handler.getHandler() instanceof GzipHandler) && !(handler.getHandler() instanceof ServletHandler) && handler.getHandler() instanceof HandlerWrapper) handler = (HandlerWrapper) handler.getHandler(); if (handler.getHandler() != _sessionHandler) { if (handler == this) super.setHandler(_sessionHandler); else handler.setHandler(_sessionHandler); } handler = _sessionHandler; } // link security handler if (getSecurityHandler() != null) { while (!(handler.getHandler() instanceof SecurityHandler) && !(handler.getHandler() instanceof GzipHandler) && !(handler.getHandler() instanceof ServletHandler) && handler.getHandler() instanceof HandlerWrapper) handler = (HandlerWrapper) handler.getHandler(); if (handler.getHandler() != _securityHandler) { if (handler == this) super.setHandler(_securityHandler); else handler.setHandler(_securityHandler); } handler = _securityHandler; } // link gzip handler if (getGzipHandler() != null) { while (!(handler.getHandler() instanceof GzipHandler) && !(handler.getHandler() instanceof ServletHandler) && handler.getHandler() instanceof HandlerWrapper) handler = (HandlerWrapper) handler.getHandler(); if (handler.getHandler() != _gzipHandler) { if (handler == this) super.setHandler(_gzipHandler); else handler.setHandler(_gzipHandler); } handler = _gzipHandler; } // link servlet handler if (getServletHandler() != null) { while (!(handler.getHandler() instanceof ServletHandler) && handler.getHandler() instanceof HandlerWrapper) handler = (HandlerWrapper) handler.getHandler(); if (handler.getHandler() != _servletHandler) { if (handler == this) super.setHandler(_servletHandler); else handler.setHandler(_servletHandler); } handler = _servletHandler; } }
/* ------------------------------------------------------------ */ @Override protected void doStart() throws Exception { getServletContext().setAttribute(DecoratedObjectFactory.ATTR, _objFactory); super.doStart(); }
static { List<String> allowedUserHostsList = Nxt.getStringListProperty("nxt.allowedUserHosts"); if (!allowedUserHostsList.contains("*")) { allowedUserHosts = Collections.unmodifiableSet(new HashSet<>(allowedUserHostsList)); } else { allowedUserHosts = null; } boolean enableUIServer = Nxt.getBooleanProperty("nxt.enableUIServer"); if (enableUIServer) { final int port = Constants.isTestnet ? TESTNET_UI_PORT : Nxt.getIntProperty("nxt.uiServerPort"); final String host = Nxt.getStringProperty("nxt.uiServerHost"); userServer = new Server(); ServerConnector connector; boolean enableSSL = Nxt.getBooleanProperty("nxt.uiSSL"); if (enableSSL) { Logger.logMessage("Using SSL (https) for the user interface server"); HttpConfiguration https_config = new HttpConfiguration(); https_config.setSecureScheme("https"); https_config.setSecurePort(port); https_config.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(Nxt.getStringProperty("nxt.keyStorePath")); sslContextFactory.setKeyStorePassword( Nxt.getStringProperty("nxt.keyStorePassword", null, true)); sslContextFactory.setExcludeCipherSuites( "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); sslContextFactory.setExcludeProtocols("SSLv3"); connector = new ServerConnector( userServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); } else { connector = new ServerConnector(userServer); } connector.setPort(port); connector.setHost(host); connector.setIdleTimeout(Nxt.getIntProperty("nxt.uiServerIdleTimeout")); connector.setReuseAddress(true); userServer.addConnector(connector); HandlerList userHandlers = new HandlerList(); ResourceHandler userFileHandler = new ResourceHandler(); userFileHandler.setDirectoriesListed(false); userFileHandler.setWelcomeFiles(new String[] {"index.html"}); userFileHandler.setResourceBase(Nxt.getStringProperty("nxt.uiResourceBase")); userHandlers.addHandler(userFileHandler); String javadocResourceBase = Nxt.getStringProperty("nxt.javadocResourceBase"); if (javadocResourceBase != null) { ContextHandler contextHandler = new ContextHandler("/doc"); ResourceHandler docFileHandler = new ResourceHandler(); docFileHandler.setDirectoriesListed(false); docFileHandler.setWelcomeFiles(new String[] {"index.html"}); docFileHandler.setResourceBase(javadocResourceBase); contextHandler.setHandler(docFileHandler); userHandlers.addHandler(contextHandler); } ServletHandler userHandler = new ServletHandler(); ServletHolder userHolder = userHandler.addServletWithMapping(UserServlet.class, "/nxt"); userHolder.setAsyncSupported(true); if (Nxt.getBooleanProperty("nxt.uiServerCORS")) { FilterHolder filterHolder = userHandler.addFilterWithMapping(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT); filterHolder.setInitParameter("allowedHeaders", "*"); filterHolder.setAsyncSupported(true); } userHandlers.addHandler(userHandler); userHandlers.addHandler(new DefaultHandler()); userServer.setHandler(userHandlers); userServer.setStopAtShutdown(true); ThreadPool.runBeforeStart( () -> { try { userServer.start(); Logger.logMessage("Started user interface server at " + host + ":" + port); } catch (Exception e) { Logger.logErrorMessage("Failed to start user interface server", e); throw new RuntimeException(e.toString(), e); } }, true); } else { userServer = null; Logger.logMessage("User interface server not enabled"); } }
@Override public void callContextDestroyed(ServletContextListener l, ServletContextEvent e) { super.callContextDestroyed(l, e); }
/** * Configure a jetty instance and deploy the webapps presented as args * * @param args the command line arguments * @throws Exception if unable to configure */ public void configure(String[] args) throws Exception { // handle classpath bits first so we can initialize the log mechanism. for (int i = 0; i < args.length; i++) { if ("--lib".equals(args[i])) { try (Resource lib = Resource.newResource(args[++i])) { if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib); _classpath.addJars(lib); } } else if ("--jar".equals(args[i])) { try (Resource jar = Resource.newResource(args[++i])) { if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar); _classpath.addPath(jar); } } else if ("--classes".equals(args[i])) { try (Resource classes = Resource.newResource(args[++i])) { if (!classes.exists() || !classes.isDirectory()) usage("No such classes directory " + classes); _classpath.addPath(classes); } } else if (args[i].startsWith("--")) i++; } initClassLoader(); LOG.info("Runner"); LOG.debug("Runner classpath {}", _classpath); String contextPath = __defaultContextPath; boolean contextPathSet = false; int port = __defaultPort; String host = null; int stopPort = 0; String stopKey = null; boolean runnerServerInitialized = false; for (int i = 0; i < args.length; i++) { switch (args[i]) { case "--port": port = Integer.parseInt(args[++i]); break; case "--host": host = args[++i]; break; case "--stop-port": stopPort = Integer.parseInt(args[++i]); break; case "--stop-key": stopKey = args[++i]; break; case "--log": _logFile = args[++i]; break; case "--out": String outFile = args[++i]; PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1)); LOG.info("Redirecting stderr/stdout to " + outFile); System.setErr(out); System.setOut(out); break; case "--path": contextPath = args[++i]; contextPathSet = true; break; case "--config": if (_configFiles == null) _configFiles = new ArrayList<>(); _configFiles.add(args[++i]); break; case "--lib": ++i; // skip break; case "--jar": ++i; // skip break; case "--classes": ++i; // skip break; case "--stats": _enableStats = true; _statsPropFile = args[++i]; _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); break; default: // process contexts if (!runnerServerInitialized) // log handlers not registered, server maybe not created, // etc { if (_server == null) // server not initialized yet { // build the server _server = new Server(); } // apply jetty config files if there are any if (_configFiles != null) { for (String cfg : _configFiles) { try (Resource resource = Resource.newResource(cfg)) { XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL()); xmlConfiguration.configure(_server); } } } // check that everything got configured, and if not, make the handlers HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class); if (handlers == null) { handlers = new HandlerCollection(); _server.setHandler(handlers); } // check if contexts already configured _contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class); if (_contexts == null) { _contexts = new ContextHandlerCollection(); prependHandler(_contexts, handlers); } if (_enableStats) { // if no stats handler already configured if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) { StatisticsHandler statsHandler = new StatisticsHandler(); Handler oldHandler = _server.getHandler(); statsHandler.setHandler(oldHandler); _server.setHandler(statsHandler); ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats"); statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/"); statsContext.setSessionHandler(new SessionHandler()); if (_statsPropFile != null) { HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile); Constraint constraint = new Constraint(); constraint.setName("Admin Only"); constraint.setRoles(new String[] {"admin"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); securityHandler.setConstraintMappings(Collections.singletonList(cm)); securityHandler.setAuthenticator(new BasicAuthenticator()); statsContext.setSecurityHandler(securityHandler); } } } // ensure a DefaultHandler is present if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) { handlers.addHandler(new DefaultHandler()); } // ensure a log handler is present _logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class); if (_logHandler == null) { _logHandler = new RequestLogHandler(); handlers.addHandler(_logHandler); } // check a connector is configured to listen on Connector[] connectors = _server.getConnectors(); if (connectors == null || connectors.length == 0) { ServerConnector connector = new ServerConnector(_server); connector.setPort(port); if (host != null) connector.setHost(host); _server.addConnector(connector); if (_enableStats) connector.addBean(new ConnectorStatistics()); } else { if (_enableStats) { for (Connector connector : connectors) { ((AbstractConnector) connector).addBean(new ConnectorStatistics()); } } } runnerServerInitialized = true; } // Create a context try (Resource ctx = Resource.newResource(args[i])) { if (!ctx.exists()) usage("Context '" + ctx + "' does not exist"); if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath; // Configure the context if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) { // It is a context config file XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL()); xmlConfiguration.getIdMap().put("Server", _server); ContextHandler handler = (ContextHandler) xmlConfiguration.configure(); if (contextPathSet) handler.setContextPath(contextPath); _contexts.addHandler(handler); handler.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } else { // assume it is a WAR file WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); webapp.setConfigurationClasses(__plusConfigurationClasses); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } } // reset contextPathSet = false; contextPath = __defaultContextPath; break; } } if (_server == null) usage("No Contexts defined"); _server.setStopAtShutdown(true); switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) { case 1: usage("Must specify --stop-key when --stop-port is specified"); break; case 2: usage("Must specify --stop-port when --stop-key is specified"); break; case 3: ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); monitor.setKey(stopKey); monitor.setExitVm(true); break; } if (_logFile != null) { NCSARequestLog requestLog = new NCSARequestLog(_logFile); requestLog.setExtended(false); _logHandler.setRequestLog(requestLog); } }
/* ------------------------------------------------------------ */ @Override protected void stopContext() throws Exception { super.stopContext(); }
/** @see org.eclipse.jetty.server.handler.ContextHandler#doStop() */ @Override protected void doStop() throws Exception { super.doStop(); _objFactory.clear(); }