Search in sources :

Example 41 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project nifi by apache.

the class JettyServer method createDocsWebApp.

private ContextHandler createDocsWebApp(final String contextPath) {
    try {
        final ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        final File docsDir = getDocsDir("docs");
        final Resource docsResource = Resource.newResource(docsDir);
        // load the component documentation working directory
        final File componentDocsDirPath = props.getComponentDocumentationWorkingDirectory();
        final File workingDocsDirectory = getWorkingDocsDirectory(componentDocsDirPath);
        final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);
        final File webApiDocsDir = getWebApiDocsDir();
        final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);
        // create resources for both docs locations
        final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
        resourceHandler.setBaseResource(resources);
        // create the context handler
        final ContextHandler handler = new ContextHandler(contextPath);
        handler.setHandler(resourceHandler);
        logger.info("Loading documents web app with context path set to " + contextPath);
        return handler;
    } catch (Exception ex) {
        logger.error("Unhandled Exception in createDocsWebApp: " + ex.getMessage());
        startUpFailure(ex);
        // required by compiler, though never be executed.
        return null;
    }
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Resource(org.eclipse.jetty.util.resource.Resource) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) JarFile(java.util.jar.JarFile) File(java.io.File) ServletException(javax.servlet.ServletException) UninheritableFlowException(org.apache.nifi.controller.UninheritableFlowException) FlowSerializationException(org.apache.nifi.controller.serialization.FlowSerializationException) SocketException(java.net.SocketException) FlowSynchronizationException(org.apache.nifi.controller.serialization.FlowSynchronizationException) LifeCycleStartException(org.apache.nifi.lifecycle.LifeCycleStartException) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Example 42 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project JMRI by JMRI.

the class WebServer method registerResource.

/**
     * Register a URL pattern to return resources from the file system. The
     * filePath may start with any of the following:
     * <ol>
     * <li>{@link jmri.util.FileUtil#PREFERENCES}
     * <li>{@link jmri.util.FileUtil#PROFILE}
     * <li>{@link jmri.util.FileUtil#SETTINGS}
     * <li>{@link jmri.util.FileUtil#PROGRAM}
     * </ol>
     * Note that the filePath can be overridden by an otherwise identical
     * filePath starting with any of the portable paths above it in the
     * preceding list.
     *
     * @param urlPattern the pattern to get resources for
     * @param filePath   the portable path for the resources
     * @throws IllegalArgumentException if urlPattern is already registered to
     *                                  deny access or for a servlet or if
     *                                  filePath is not allowed
     */
public void registerResource(String urlPattern, String filePath) throws IllegalArgumentException {
    if (this.registeredUrls.get(urlPattern) != null) {
        throw new IllegalArgumentException("urlPattern \"" + urlPattern + "\" is already registered.");
    }
    this.registeredUrls.put(urlPattern, Registration.RESOURCE);
    ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    servletContext.setContextPath(urlPattern);
    HandlerList handlers = new HandlerList();
    if (filePath.startsWith(FileUtil.PROGRAM) && !filePath.equals(FileUtil.PROGRAM)) {
        // make it possible to override anything under program: with an identical path under preference:, profile:, or settings:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.SETTINGS)));
        ResourceHandler programHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, programHandler, new DefaultHandler() });
    } else if (filePath.startsWith(FileUtil.SETTINGS) && !filePath.equals(FileUtil.SETTINGS)) {
        // make it possible to override anything under settings: with an identical path under preference: or profile:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        ResourceHandler settingsHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, settingsHandler, new DefaultHandler() });
    } else if (filePath.startsWith(FileUtil.PROFILE) && !filePath.equals(FileUtil.PROFILE)) {
        // make it possible to override anything under profile: with an identical path under preference:
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler preferenceHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.SETTINGS, FileUtil.PREFERENCES)));
        ResourceHandler projectHandler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath.replace(FileUtil.PROGRAM, FileUtil.PROFILE)));
        handlers.setHandlers(new Handler[] { preferenceHandler, projectHandler, new DefaultHandler() });
    } else if (FileUtil.isPortableFilename(filePath)) {
        log.debug("Setting up handler chain for {}", urlPattern);
        ResourceHandler handler = new DirectoryHandler(FileUtil.getAbsoluteFilename(filePath));
        handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });
    } else if (URIforPortablePath(filePath) == null) {
        throw new IllegalArgumentException("\"" + filePath + "\" is not allowed.");
    }
    ContextHandler handlerContext = new ContextHandler();
    handlerContext.setContextPath(urlPattern);
    handlerContext.setHandler(handlers);
    ((ContextHandlerCollection) this.server.getHandler()).addHandler(handlerContext);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DirectoryHandler(jmri.web.servlet.directory.DirectoryHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DirectoryHandler(jmri.web.servlet.directory.DirectoryHandler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler)

Example 43 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project opennms by OpenNMS.

the class JUnitServer method initializeServerWithConfig.

protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
        server = new Server();
        // SSL context configuration
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(config.keystore());
        sslContextFactory.setKeyStorePassword(config.keystorePassword());
        sslContextFactory.setKeyManagerPassword(config.keyPassword());
        sslContextFactory.setTrustStorePath(config.keystore());
        sslContextFactory.setTrustStorePassword(config.keystorePassword());
        // HTTP Configuration
        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        http_config.setSecurePort(config.port());
        http_config.setOutputBufferSize(32768);
        http_config.setRequestHeaderSize(8192);
        http_config.setResponseHeaderSize(8192);
        http_config.setSendServerVersion(true);
        http_config.setSendDateHeader(false);
        // SSL HTTP Configuration
        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());
        // SSL Connector
        ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
        sslConnector.setPort(config.port());
        server.addConnector(sslConnector);
    } 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.setHotReload(true);
        m_server.addBean(loginService);
        final ConstraintSecurityHandler security = new ConstraintSecurityHandler();
        final Set<String> knownRoles = new HashSet<>();
        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.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);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) JUnitHttpServer(org.opennms.core.test.http.annotations.JUnitHttpServer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Constraint(org.eclipse.jetty.util.security.Constraint) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) HashSet(java.util.HashSet) Webapp(org.opennms.core.test.http.annotations.Webapp)

Example 44 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project graphhopper by graphhopper.

the class GHServer method start.

public void start(Injector injector) throws Exception {
    if (this.injector != null)
        throw new IllegalArgumentException("Server already started");
    this.injector = injector;
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setDirectoriesListed(false);
    resHandler.setWelcomeFiles(new String[] { "index.html" });
    resHandler.setRedirectWelcome(false);
    String contextPath = args.get("jetty.contextpath", "/");
    ContextHandler contextHandler = new ContextHandler();
    contextHandler.setErrorHandler(new GHErrorHandler());
    contextHandler.setContextPath(contextPath);
    contextHandler.setBaseResource(Resource.newResource(args.get("jetty.resourcebase", "./web/src/main/webapp")));
    contextHandler.setHandler(resHandler);
    server = new Server();
    // getSessionHandler and getSecurityHandler should always return null
    ServletContextHandler servHandler = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servHandler.setContextPath(contextPath);
    // Putting this here (and not in the guice servlet module) because it should take precedence
    // over more specific routes. And guice, strangely, is order-dependent (even though, except in the servlet
    // extension, modules are _not_ supposed to be ordered).
    servHandler.addServlet(new ServletHolder(injector.getInstance(InvalidRequestServlet.class)), "/*");
    servHandler.addFilter(new FilterHolder(new GuiceFilter()), "/*", EnumSet.allOf(DispatcherType.class));
    ServerConnector connector0 = new ServerConnector(server);
    int httpPort = args.getInt("jetty.port", 8989);
    String host = args.get("jetty.host", "");
    connector0.setPort(httpPort);
    int requestHeaderSize = args.getInt("jetty.request_header_size", -1);
    if (requestHeaderSize > 0)
        connector0.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().setRequestHeaderSize(requestHeaderSize);
    if (!host.isEmpty())
        connector0.setHost(host);
    server.addConnector(connector0);
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { contextHandler, servHandler });
    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setIncludedMethods("GET", "POST");
    // Note: gzip only affects the response body like our previous 'GHGZIPHook' behaviour: http://stackoverflow.com/a/31565805/194609
    // If no mimeTypes are defined the content-type is "not 'application/gzip'", See also https://github.com/graphhopper/directions-api/issues/28 for pitfalls
    // gzipHandler.setIncludedMimeTypes();
    gzipHandler.setHandler(handlers);
    GraphHopperService graphHopper = injector.getInstance(GraphHopperService.class);
    graphHopper.start();
    createCallOnDestroyModule("AutoCloseable for GraphHopper", graphHopper);
    server.setHandler(gzipHandler);
    server.setStopAtShutdown(true);
    server.start();
    logger.info("Started server at HTTP " + host + ":" + httpPort);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) GuiceFilter(com.google.inject.servlet.GuiceFilter) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DispatcherType(javax.servlet.DispatcherType)

Example 45 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project winery by eclipse.

the class WineryUsingHttpServer method createHttpServerForRepositoryUi.

/**
 * Starts the repository UI on port {@value #REPOSITORY_UI_PORT}
 */
public static Server createHttpServerForRepositoryUi() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(REPOSITORY_UI_PORT);
    server.setConnectors(new Connector[] { connector });
    ResourceHandler rh0 = new ResourceHandler();
    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/");
    // Path indexHtmlPath = MavenTestingUtils.getProjectFilePath("../org.eclipse.winery.repository.ui/dist/index.html").getParent();
    Path indexHtmlPath = MavenTestingUtils.getBasePath().resolve("org.eclipse.winery.repository.ui").resolve("dist");
    if (Files.exists(indexHtmlPath)) {
        LOGGER.debug("Serving UI from " + indexHtmlPath.toString());
    } else {
        // not sure, why we sometimes have to use `getParent()`.
        indexHtmlPath = MavenTestingUtils.getBasePath().getParent().resolve("org.eclipse.winery.repository.ui").resolve("dist");
        if (Files.exists(indexHtmlPath)) {
            LOGGER.debug("Serving UI from " + indexHtmlPath.toString());
        } else {
            LOGGER.error("Path does not exist " + indexHtmlPath);
        }
    }
    context0.setBaseResource(Resource.newResource(indexHtmlPath.toFile()));
    context0.setHandler(rh0);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { context0 });
    server.setHandler(contexts);
    return server;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection)

Aggregations

ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)127 Server (org.eclipse.jetty.server.Server)47 ServerConnector (org.eclipse.jetty.server.ServerConnector)27 URI (java.net.URI)21 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)20 Test (org.junit.Test)20 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)19 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)19 IOException (java.io.IOException)18 Handler (org.eclipse.jetty.server.Handler)14 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)14 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)14 File (java.io.File)13 ServletException (javax.servlet.ServletException)13 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)13 BeforeClass (org.junit.BeforeClass)11 BaseIntegrationTest (com.ctrip.framework.apollo.BaseIntegrationTest)10 Config (com.ctrip.framework.apollo.Config)10 ApolloConfig (com.ctrip.framework.apollo.core.dto.ApolloConfig)10 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)10