Search in sources :

Example 81 with Handler

use of org.eclipse.jetty.server.Handler in project cuba by cuba-platform.

the class CubaJettyServer method createServer.

protected Server createServer() throws Exception {
    ClassLoader serverClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader sharedClassLoader = new URLClassLoader(pathsToURLs(serverClassLoader, SHARED_CLASS_PATH_IN_JAR), serverClassLoader);
    Server server;
    if (jettyConfUrl != null) {
        XmlConfiguration xmlConfiguration = new XmlConfiguration(jettyConfUrl);
        server = (Server) xmlConfiguration.configure();
    } else {
        server = new Server(port);
    }
    server.setStopAtShutdown(true);
    List<Handler> handlers = new ArrayList<>();
    if (CubaJettyUtils.hasCoreApp(serverClassLoader)) {
        String coreContextPath = contextPath;
        if (isSingleJar(serverClassLoader)) {
            if (PATH_DELIMITER.equals(contextPath)) {
                coreContextPath = PATH_DELIMITER + "app-core";
            } else {
                coreContextPath = contextPath + "-core";
            }
        }
        handlers.add(createAppContext(serverClassLoader, sharedClassLoader, CORE_PATH_IN_JAR, coreContextPath));
    }
    if (hasWebApp(serverClassLoader)) {
        handlers.add(createAppContext(serverClassLoader, sharedClassLoader, WEB_PATH_IN_JAR, contextPath));
    }
    if (hasPortalApp(serverClassLoader)) {
        String portalContextPath = contextPath;
        if (isSingleJar(serverClassLoader)) {
            portalContextPath = this.portalContextPath;
        }
        handlers.add(createAppContext(serverClassLoader, sharedClassLoader, PORTAL_PATH_IN_JAR, portalContextPath));
    }
    if (hasFrontApp(serverClassLoader)) {
        handlers.add(createFrontAppContext(serverClassLoader, sharedClassLoader));
    }
    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(handlers.toArray(new Handler[handlers.size()]));
    server.setHandler(handlerCollection);
    return server;
}
Also used : Server(org.eclipse.jetty.server.Server) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) Handler(org.eclipse.jetty.server.Handler) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) WebXmlConfiguration(org.eclipse.jetty.webapp.WebXmlConfiguration) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration)

Example 82 with Handler

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

the class JettyServer method start.

@Override
public void start() {
    try {
        ExtensionManager.discoverExtensions(systemBundle, bundles);
        ExtensionManager.logClassLoaderMapping();
        DocGenerator.generate(props, extensionMapping);
        // start the server
        server.start();
        // ensure everything started successfully
        for (Handler handler : server.getChildHandlers()) {
            // see if the handler is a web app
            if (handler instanceof WebAppContext) {
                WebAppContext context = (WebAppContext) handler;
                // cause it to be unavailable
                if (context.getUnavailableException() != null) {
                    startUpFailure(context.getUnavailableException());
                }
            }
        }
        // this must be done after starting the server (and ensuring there were no start up failures)
        if (webApiContext != null) {
            // give the web api the component ui extensions
            final ServletContext webApiServletContext = webApiContext.getServletHandler().getServletContext();
            webApiServletContext.setAttribute("nifi-ui-extensions", componentUiExtensions);
            // get the application context
            final WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(webApiServletContext);
            // component ui extensions
            if (CollectionUtils.isNotEmpty(componentUiExtensionWebContexts)) {
                final NiFiWebConfigurationContext configurationContext = webApplicationContext.getBean("nifiWebConfigurationContext", NiFiWebConfigurationContext.class);
                for (final WebAppContext customUiContext : componentUiExtensionWebContexts) {
                    // set the NiFi context in each custom ui servlet context
                    final ServletContext customUiServletContext = customUiContext.getServletHandler().getServletContext();
                    customUiServletContext.setAttribute("nifi-web-configuration-context", configurationContext);
                    // add the security filter to any ui extensions wars
                    final FilterHolder securityFilter = webApiContext.getServletHandler().getFilter("springSecurityFilterChain");
                    if (securityFilter != null) {
                        customUiContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
                    }
                }
            }
            // content viewer extensions
            if (CollectionUtils.isNotEmpty(contentViewerWebContexts)) {
                for (final WebAppContext contentViewerContext : contentViewerWebContexts) {
                    // add the security filter to any content viewer  wars
                    final FilterHolder securityFilter = webApiContext.getServletHandler().getFilter("springSecurityFilterChain");
                    if (securityFilter != null) {
                        contentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
                    }
                }
            }
            // content viewer controller
            if (webContentViewerContext != null) {
                final ContentAccess contentAccess = webApplicationContext.getBean("contentAccess", ContentAccess.class);
                // add the content access
                final ServletContext webContentViewerServletContext = webContentViewerContext.getServletHandler().getServletContext();
                webContentViewerServletContext.setAttribute("nifi-content-access", contentAccess);
                final FilterHolder securityFilter = webApiContext.getServletHandler().getFilter("springSecurityFilterChain");
                if (securityFilter != null) {
                    webContentViewerContext.addFilter(securityFilter, "/*", EnumSet.allOf(DispatcherType.class));
                }
            }
        }
        // ensure the web document war was loaded and provide the extension mapping
        if (webDocsContext != null) {
            final ServletContext webDocsServletContext = webDocsContext.getServletHandler().getServletContext();
            webDocsServletContext.setAttribute("nifi-extension-mapping", extensionMapping);
        }
        // in a cluster
        if (props.isNode()) {
            FlowService flowService = null;
            try {
                logger.info("Loading Flow...");
                ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(webApiContext.getServletContext());
                flowService = ctx.getBean("flowService", FlowService.class);
                // start and load the flow
                flowService.start();
                flowService.load(null);
                logger.info("Flow loaded successfully.");
            } catch (BeansException | LifeCycleStartException | IOException | FlowSerializationException | FlowSynchronizationException | UninheritableFlowException e) {
                // ensure the flow service is terminated
                if (flowService != null && flowService.isRunning()) {
                    flowService.stop(false);
                }
                logger.error("Unable to load flow due to: " + e, e);
                // cannot wrap the exception as they are not defined in a classloader accessible to the caller
                throw new Exception("Unable to load flow due to: " + e);
            }
        }
        // dump the application url after confirming everything started successfully
        dumpUrls();
    } catch (Exception ex) {
        startUpFailure(ex);
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ContentAccess(org.apache.nifi.web.ContentAccess) FlowSynchronizationException(org.apache.nifi.controller.serialization.FlowSynchronizationException) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) FlowSerializationException(org.apache.nifi.controller.serialization.FlowSerializationException) IOException(java.io.IOException) 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) WebApplicationContext(org.springframework.web.context.WebApplicationContext) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) UninheritableFlowException(org.apache.nifi.controller.UninheritableFlowException) ServletContext(javax.servlet.ServletContext) LifeCycleStartException(org.apache.nifi.lifecycle.LifeCycleStartException) DispatcherType(javax.servlet.DispatcherType) NiFiWebConfigurationContext(org.apache.nifi.web.NiFiWebConfigurationContext) FlowService(org.apache.nifi.services.FlowService) BeansException(org.springframework.beans.BeansException)

Example 83 with Handler

use of org.eclipse.jetty.server.Handler in project camel by apache.

the class JettyHttpComponent method createEndpoint.

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    // must extract well known parameters before we create the endpoint
    List<Handler> handlerList = resolveAndRemoveReferenceListParameter(parameters, "handlers", Handler.class);
    HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
    JettyHttpBinding jettyBinding = resolveAndRemoveReferenceParameter(parameters, "jettyHttpBindingRef", JettyHttpBinding.class);
    Boolean enableJmx = getAndRemoveParameter(parameters, "enableJmx", Boolean.class);
    Boolean enableMultipartFilter = getAndRemoveParameter(parameters, "enableMultipartFilter", Boolean.class, true);
    Filter multipartFilter = resolveAndRemoveReferenceParameter(parameters, "multipartFilterRef", Filter.class);
    List<Filter> filters = resolveAndRemoveReferenceListParameter(parameters, "filtersRef", Filter.class);
    Boolean enableCors = getAndRemoveParameter(parameters, "enableCORS", Boolean.class, false);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParametersRef", SSLContextParameters.class);
    SSLContextParameters ssl = sslContextParameters != null ? sslContextParameters : this.sslContextParameters;
    String proxyHost = getAndRemoveParameter(parameters, "proxyHost", String.class, getProxyHost());
    Integer proxyPort = getAndRemoveParameter(parameters, "proxyPort", Integer.class, getProxyPort());
    Integer httpClientMinThreads = getAndRemoveParameter(parameters, "httpClientMinThreads", Integer.class, this.httpClientMinThreads);
    Integer httpClientMaxThreads = getAndRemoveParameter(parameters, "httpClientMaxThreads", Integer.class, this.httpClientMaxThreads);
    HttpClient httpClient = resolveAndRemoveReferenceParameter(parameters, "httpClient", HttpClient.class);
    Boolean async = getAndRemoveParameter(parameters, "async", Boolean.class);
    // extract httpClient. parameters
    Map<String, Object> httpClientParameters = IntrospectionSupport.extractProperties(parameters, "httpClient.");
    // extract filterInit. parameters
    Map<String, String> filterInitParameters = IntrospectionSupport.extractStringProperties(IntrospectionSupport.extractProperties(parameters, "filterInit."));
    String address = remaining;
    URI addressUri = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(address));
    URI endpointUri = URISupport.createRemainingURI(addressUri, parameters);
    // need to keep the httpMethodRestrict parameter for the endpointUri
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    // restructure uri to be based on the parameters left as we dont want to include the Camel internal options
    URI httpUri = URISupport.createRemainingURI(addressUri, parameters);
    // create endpoint after all known parameters have been extracted from parameters
    // include component scheme in the uri
    String scheme = ObjectHelper.before(uri, ":");
    endpointUri = new URI(scheme + ":" + endpointUri);
    JettyHttpEndpoint endpoint = createEndpoint(endpointUri, httpUri);
    if (async != null) {
        endpoint.setAsync(async);
    }
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    // setup the proxy host and proxy port
    if (proxyHost != null) {
        endpoint.setProxyHost(proxyHost);
        endpoint.setProxyPort(proxyPort);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }
    if (httpClientParameters != null && !httpClientParameters.isEmpty()) {
        endpoint.setHttpClientParameters(httpClientParameters);
    }
    if (filterInitParameters != null && !filterInitParameters.isEmpty()) {
        endpoint.setFilterInitParameters(filterInitParameters);
    }
    if (handlerList.size() > 0) {
        endpoint.setHandlers(handlerList);
    }
    // prefer to use endpoint configured over component configured
    if (binding == null) {
        // fallback to component configured
        binding = getHttpBinding();
    }
    if (binding != null) {
        endpoint.setBinding(binding);
    }
    // prefer to use endpoint configured over component configured
    if (jettyBinding == null) {
        // fallback to component configured
        jettyBinding = getJettyHttpBinding();
    }
    if (jettyBinding != null) {
        endpoint.setJettyBinding(jettyBinding);
    }
    if (enableJmx != null) {
        endpoint.setEnableJmx(enableJmx);
    } else {
        // set this option based on setting of JettyHttpComponent
        endpoint.setEnableJmx(isEnableJmx());
    }
    endpoint.setEnableMultipartFilter(enableMultipartFilter);
    if (multipartFilter != null) {
        endpoint.setMultipartFilter(multipartFilter);
        endpoint.setEnableMultipartFilter(true);
    }
    if (enableCors) {
        endpoint.setEnableCORS(enableCors);
        if (filters == null) {
            filters = new ArrayList<Filter>(1);
        }
        filters.add(new CrossOriginFilter());
    }
    if (filters != null) {
        endpoint.setFilters(filters);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }
    if (ssl != null) {
        endpoint.setSslContextParameters(ssl);
    }
    if (httpClientMinThreads != null) {
        endpoint.setHttpClientMinThreads(httpClientMinThreads);
    }
    if (httpClientMaxThreads != null) {
        endpoint.setHttpClientMaxThreads(httpClientMaxThreads);
    }
    if (httpClient != null) {
        endpoint.setHttpClient(httpClient);
    }
    endpoint.setSendServerVersion(isSendServerVersion());
    setProperties(endpoint, parameters);
    // re-create http uri after all parameters has been set on the endpoint, as the remainders are for http uri
    httpUri = URISupport.createRemainingURI(addressUri, parameters);
    endpoint.setHttpUri(httpUri);
    return endpoint;
}
Also used : UrlRewrite(org.apache.camel.http.common.UrlRewrite) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) Handler(org.eclipse.jetty.server.Handler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpRestHeaderFilterStrategy(org.apache.camel.http.common.HttpRestHeaderFilterStrategy) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) URI(java.net.URI) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) Filter(javax.servlet.Filter) MultiPartFilter(org.eclipse.jetty.servlets.MultiPartFilter) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) HttpClient(org.eclipse.jetty.client.HttpClient) HttpBinding(org.apache.camel.http.common.HttpBinding)

Example 84 with Handler

use of org.eclipse.jetty.server.Handler in project camel by apache.

the class JettyHttpComponent method addJettyHandlers.

protected void addJettyHandlers(Server server, List<Handler> handlers) {
    if (handlers != null && !handlers.isEmpty()) {
        for (Handler handler : handlers) {
            if (handler instanceof HandlerWrapper) {
                // avoid setting a handler more than once
                if (!isHandlerInChain(server.getHandler(), handler)) {
                    ((HandlerWrapper) handler).setHandler(server.getHandler());
                    server.setHandler(handler);
                }
            } else {
                HandlerCollection handlerCollection = new HandlerCollection();
                handlerCollection.addHandler(server.getHandler());
                handlerCollection.addHandler(handler);
                server.setHandler(handlerCollection);
            }
        }
    }
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) Handler(org.eclipse.jetty.server.Handler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) HandlerWrapper(org.eclipse.jetty.server.handler.HandlerWrapper)

Example 85 with Handler

use of org.eclipse.jetty.server.Handler in project archiva by apache.

the class HttpProxyTransferTest method setUp.

@Before
public void setUp() throws Exception {
    proxyHandler = applicationContext.getBean("repositoryProxyConnectors#test", RepositoryProxyConnectors.class);
    config = applicationContext.getBean("archivaConfiguration#mock", ArchivaConfiguration.class);
    // clear from previous tests - TODO the spring context should be initialised per test instead, or the config
    // made a complete mock
    config.getConfiguration().getProxyConnectors().clear();
    // Setup source repository (using default layout)
    String repoPath = "target/test-repository/managed/" + getClass().getSimpleName();
    Path destRepoDir = Paths.get(repoPath);
    // Cleanout destination dirs.
    if (Files.exists(destRepoDir)) {
        FileUtils.deleteDirectory(destRepoDir.toFile());
    }
    // Make the destination dir.
    Files.createDirectories(destRepoDir);
    MavenManagedRepository repo = new MavenManagedRepository(MANAGED_ID, "Default Managed Repository", Paths.get(repoPath).getParent());
    repo.setLocation(new URI(repoPath));
    repo.setLayout("default");
    RepositoryContentProvider provider = applicationContext.getBean("repositoryContentProvider#maven", RepositoryContentProvider.class);
    ManagedRepositoryContent repoContent = provider.createManagedContent(repo);
    managedDefaultRepository = repoContent;
    ((DefaultManagedRepositoryAdmin) applicationContext.getBean(ManagedRepositoryAdmin.class)).setArchivaConfiguration(config);
    RepositoryRegistry managedRepositoryAdmin = applicationContext.getBean(RepositoryRegistry.class);
    if (managedRepositoryAdmin.getManagedRepository(repo.getId()) == null) {
        managedRepositoryAdmin.putRepository(repo);
    }
    // config.getConfiguration().addManagedRepository( repo );
    Handler handler = new AbstractHandler() {

        @Override
        public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print("get-default-layout-1.0.jar\n\n");
            assertNotNull(request.getHeader("Proxy-Connection"));
            ((Request) request).setHandled(true);
        }

        public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print("get-default-layout-1.0.jar\n\n");
            assertNotNull(request.getHeader("Proxy-Connection"));
            ((Request) request).setHandled(true);
        }
    };
    server = new Server();
    ServerConnector serverConnector = new ServerConnector(server, new HttpConnectionFactory());
    server.addConnector(serverConnector);
    server.setHandler(handler);
    server.start();
    int port = serverConnector.getLocalPort();
    NetworkProxyConfiguration proxyConfig = new NetworkProxyConfiguration();
    proxyConfig.setHost("localhost");
    proxyConfig.setPort(port);
    proxyConfig.setProtocol("http");
    proxyConfig.setId(PROXY_ID);
    config.getConfiguration().addNetworkProxy(proxyConfig);
    // Setup target (proxied to) repository.
    RemoteRepositoryConfiguration repoConfig = new RemoteRepositoryConfiguration();
    repoConfig.setId(PROXIED_ID);
    repoConfig.setName("Proxied Repository 1");
    repoConfig.setLayout("default");
    repoConfig.setUrl("http://www.example.com/");
    config.getConfiguration().addRemoteRepository(repoConfig);
}
Also used : Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) MavenManagedRepository(org.apache.archiva.repository.maven2.MavenManagedRepository) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) Handler(org.eclipse.jetty.server.Handler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) RepositoryProxyConnectors(org.apache.archiva.proxy.model.RepositoryProxyConnectors) URI(java.net.URI) ArchivaConfiguration(org.apache.archiva.configuration.ArchivaConfiguration) DefaultManagedRepositoryAdmin(org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServerConnector(org.eclipse.jetty.server.ServerConnector) RepositoryContentProvider(org.apache.archiva.repository.RepositoryContentProvider) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) ManagedRepositoryAdmin(org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin) DefaultManagedRepositoryAdmin(org.apache.archiva.admin.repository.managed.DefaultManagedRepositoryAdmin) NetworkProxyConfiguration(org.apache.archiva.configuration.NetworkProxyConfiguration) RepositoryRegistry(org.apache.archiva.repository.RepositoryRegistry) RemoteRepositoryConfiguration(org.apache.archiva.configuration.RemoteRepositoryConfiguration) Before(org.junit.Before)

Aggregations

Handler (org.eclipse.jetty.server.Handler)119 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)37 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)37 Server (org.eclipse.jetty.server.Server)35 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)26 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)25 RequestLogHandler (org.eclipse.jetty.server.handler.RequestLogHandler)23 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)22 ArrayList (java.util.ArrayList)21 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)18 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)18 IOException (java.io.IOException)15 Test (org.junit.Test)15 HttpServletResponse (javax.servlet.http.HttpServletResponse)14 ServerConnector (org.eclipse.jetty.server.ServerConnector)13 ErrorHandler (org.eclipse.jetty.server.handler.ErrorHandler)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 Request (org.eclipse.jetty.server.Request)12 URI (java.net.URI)11 SecurityHandler (org.eclipse.jetty.security.SecurityHandler)11