Search in sources :

Example 16 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project kafka by apache.

the class RestServer method initializeResources.

public void initializeResources(Herder herder) {
    log.info("Initializing REST resources");
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider());
    resourceConfig.register(new RootResource(herder));
    resourceConfig.register(new ConnectorsResource(herder, config));
    resourceConfig.register(new ConnectorPluginsResource(herder));
    resourceConfig.register(ConnectExceptionMapper.class);
    resourceConfig.property(ServerProperties.WADL_FEATURE_DISABLE, true);
    registerRestExtensions(herder, resourceConfig);
    List<String> adminListeners = config.getList(WorkerConfig.ADMIN_LISTENERS_CONFIG);
    ResourceConfig adminResourceConfig;
    if (adminListeners == null) {
        log.info("Adding admin resources to main listener");
        adminResourceConfig = resourceConfig;
        adminResourceConfig.register(new LoggingResource());
    } else if (adminListeners.size() > 0) {
        // TODO: we need to check if these listeners are same as 'listeners'
        // TODO: the following code assumes that they are different
        log.info("Adding admin resources to admin listener");
        adminResourceConfig = new ResourceConfig();
        adminResourceConfig.register(new JacksonJsonProvider());
        adminResourceConfig.register(new LoggingResource());
        adminResourceConfig.register(ConnectExceptionMapper.class);
    } else {
        log.info("Skipping adding admin resources");
        // set up adminResource but add no handlers to it
        adminResourceConfig = resourceConfig;
    }
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);
    List<Handler> contextHandlers = new ArrayList<>();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    contextHandlers.add(context);
    ServletContextHandler adminContext = null;
    if (adminResourceConfig != resourceConfig) {
        adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
        ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig));
        adminContext.setContextPath("/");
        adminContext.addServlet(adminServletHolder, "/*");
        adminContext.setVirtualHosts(new String[] { "@" + ADMIN_SERVER_CONNECTOR_NAME });
        contextHandlers.add(adminContext);
    }
    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (!Utils.isBlank(allowedOrigins)) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (!Utils.isBlank(allowedMethods)) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
    String headerConfig = config.getString(WorkerConfig.RESPONSE_HTTP_HEADERS_CONFIG);
    if (!Utils.isBlank(headerConfig)) {
        configureHttpResponsHeaderFilter(context);
    }
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter();
    slf4jRequestLogWriter.setLoggerName(RestServer.class.getCanonicalName());
    CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T");
    requestLogHandler.setRequestLog(requestLog);
    contextHandlers.add(new DefaultHandler());
    contextHandlers.add(requestLogHandler);
    handlers.setHandlers(contextHandlers.toArray(new Handler[0]));
    try {
        context.start();
    } catch (Exception e) {
        throw new ConnectException("Unable to initialize REST resources", e);
    }
    if (adminResourceConfig != resourceConfig) {
        try {
            log.debug("Starting admin context");
            adminContext.start();
        } catch (Exception e) {
            throw new ConnectException("Unable to initialize Admin REST resources", e);
        }
    }
    log.info("REST resources initialized; server is started and ready to handle requests");
}
Also used : RootResource(org.apache.kafka.connect.runtime.rest.resources.RootResource) ConnectorsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) LoggingResource(org.apache.kafka.connect.runtime.rest.resources.LoggingResource) CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ArrayList(java.util.ArrayList) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) Handler(org.eclipse.jetty.server.Handler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ConnectorPluginsResource(org.apache.kafka.connect.runtime.rest.resources.ConnectorPluginsResource) ConnectExceptionMapper(org.apache.kafka.connect.runtime.rest.errors.ConnectExceptionMapper) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) Slf4jRequestLogWriter(org.eclipse.jetty.server.Slf4jRequestLogWriter) IOException(java.io.IOException) ConfigException(org.apache.kafka.common.config.ConfigException) ConnectException(org.apache.kafka.connect.errors.ConnectException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ConnectException(org.apache.kafka.connect.errors.ConnectException)

Example 17 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project stanbol by apache.

the class JerseyEndpoint method initJersey.

/**
 * Initialize the Jersey subsystem
 */
private synchronized void initJersey() throws NamespaceException, ServletException {
    if (componentContext == null) {
        // we have not yet been activated
        return;
    }
    // end of STANBOL-1073 work around
    if (componentContext == null) {
        log.debug(" ... can not init Jersey Endpoint - Component not yet activated!");
        // throw new IllegalStateException("Null ComponentContext, not activated?");
        return;
    }
    shutdownJersey();
    log.info("(Re)initializing the Stanbol Jersey subsystem");
    // register all the JAX-RS resources into a a JAX-RS application and bind it to a configurable URL
    // prefix
    DefaultApplication app = new DefaultApplication();
    String staticUrlRoot = (String) componentContext.getProperties().get(STATIC_RESOURCES_URL_ROOT_PROPERTY);
    String applicationAlias = (String) componentContext.getProperties().get(ALIAS_PROPERTY);
    // incrementally contribute fragment resources
    List<LinkResource> linkResources = new ArrayList<LinkResource>();
    List<ScriptResource> scriptResources = new ArrayList<ScriptResource>();
    for (WebFragment fragment : webFragments) {
        log.debug("Registering web fragment '{}' into jaxrs application", fragment.getName());
        linkResources.addAll(fragment.getLinkResources());
        scriptResources.addAll(fragment.getScriptResources());
        navigationLinks.removeAll(fragment.getNavigationLinks());
        navigationLinks.addAll(fragment.getNavigationLinks());
        app.contributeClasses(fragment.getJaxrsResourceClasses());
        app.contributeSingletons(fragment.getJaxrsResourceSingletons());
    }
    app.contributeSingletons(components);
    Collections.sort(linkResources);
    Collections.sort(scriptResources);
    Collections.sort(navigationLinks);
    // bind the aggregate JAX-RS application to a dedicated servlet
    ServletContainer container = new ServletContainer(ResourceConfig.forApplication(app));
    Bundle appBundle = componentContext.getBundleContext().getBundle();
    httpService.registerServlet(applicationAlias, container, getInitParams(), null);
    registeredAliases.add(applicationAlias);
    // forward the main Stanbol OSGi runtime context so that JAX-RS resources can lookup arbitrary
    // services
    servletContext = container.getServletContext();
    servletContext.setAttribute(BundleContext.class.getName(), componentContext.getBundleContext());
    layoutConfiguration.setRootUrl(applicationAlias);
    // servletContext.setAttribute(BaseStanbolResource.ROOT_URL, applicationAlias);
    layoutConfiguration.setStaticResourcesRootUrl(staticUrlRoot);
    // servletContext.setAttribute(BaseStanbolResource.STATIC_RESOURCES_ROOT_URL, staticUrlRoot);
    layoutConfiguration.setLinkResources(linkResources);
    // servletContext.setAttribute(BaseStanbolResource.LINK_RESOURCES, linkResources);
    layoutConfiguration.setScriptResources(scriptResources);
    // servletContext.setAttribute(BaseStanbolResource.SCRIPT_RESOURCES, scriptResources);
    layoutConfiguration.setNavigationsLinks(navigationLinks);
    // servletContext.setAttribute(BaseStanbolResource.NAVIGATION_LINKS, navigationLinks);
    servletContext.setAttribute(CORS_ORIGIN, corsOrigins);
    servletContext.setAttribute(CORS_ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeaders);
    log.info("JerseyEndpoint servlet registered at {}", applicationAlias);
}
Also used : LinkResource(org.apache.stanbol.commons.web.base.LinkResource) WebFragment(org.apache.stanbol.commons.web.base.WebFragment) Bundle(org.osgi.framework.Bundle) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ArrayList(java.util.ArrayList) ScriptResource(org.apache.stanbol.commons.web.base.ScriptResource) BundleContext(org.osgi.framework.BundleContext)

Example 18 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project Gaffer by gchq.

the class RestApiTestClient method createHttpServer.

private HttpServer createHttpServer() {
    final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(uriString));
    final String webappContextName = "WebappContext";
    final WebappContext context = new WebappContext(webappContextName, "/".concat(fullPath));
    context.addListener(ServletLifecycleListener.class.getName());
    final String servletContainerName = "ServletContainer";
    final ServletRegistration registration = context.addServlet(servletContainerName, new ServletContainer(new ResourceConfig(config)));
    registration.addMapping("/*");
    context.deploy(server);
    return server;
}
Also used : ServletRegistration(org.glassfish.grizzly.servlet.ServletRegistration) WebappContext(org.glassfish.grizzly.servlet.WebappContext) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig)

Example 19 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project Payara by payara.

the class OpenApiServletContainerInitializer method onStartup.

@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    // Only deploy to app root
    if (!"".equals(ctx.getContextPath())) {
        return;
    }
    OpenApiServiceConfiguration configuration = Globals.getDefaultHabitat().getService(OpenApiServiceConfiguration.class);
    // Check if there is already an endpoint for OpenAPI
    Map<String, ? extends ServletRegistration> registrations = ctx.getServletRegistrations();
    for (ServletRegistration reg : registrations.values()) {
        if (reg.getMappings().contains(configuration.getEndpoint())) {
            return;
        }
    }
    String virtualServers = configuration.getVirtualServers();
    if (!isEmpty(virtualServers) && !asList(virtualServers.split(",")).contains(ctx.getVirtualServerName())) {
        return;
    }
    // Start the OpenAPI application
    ServletContainer servletContainer = new ServletContainer(new OpenApiApplication());
    ServletRegistration.Dynamic reg = ctx.addServlet("microprofile-openapi-servlet", servletContainer);
    reg.setLoadOnStartup(1);
    reg.addMapping("/" + configuration.getEndpoint() + "/*");
    if (Boolean.parseBoolean(configuration.getSecurityEnabled())) {
        String[] roles = configuration.getRoles().split(",");
        reg.setServletSecurity(new ServletSecurityElement(new HttpConstraintElement(CONFIDENTIAL, roles)));
        ctx.declareRoles(roles);
    }
}
Also used : ServletRegistration(javax.servlet.ServletRegistration) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) OpenApiApplication(fish.payara.microprofile.openapi.rest.app.OpenApiApplication) HttpConstraintElement(javax.servlet.HttpConstraintElement) OpenApiServiceConfiguration(fish.payara.microprofile.openapi.impl.admin.OpenApiServiceConfiguration) ServletSecurityElement(javax.servlet.ServletSecurityElement)

Example 20 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project Payara by payara.

the class ListRestEndpointsCommand method getSpecifiedJerseyApplications.

/**
 * Gets a map of Jersey container to the Jersey container name, from a given component name and list of web modules.
 * If the component name is null, then this will return all Jersey applications.
 * @param componentName the name of the Jersey component.
 * @param modules a list of web modules.
 * @return a map of Jersey containers to their names.
 */
private Map<ServletContainer, String> getSpecifiedJerseyApplications(String componentName, List<WebModule> modules) {
    Map<ServletContainer, String> jerseyApplicationMap = new HashMap<>();
    for (WebModule webModule : modules) {
        // loop through all servlets in the given web module
        for (Container container : webModule.findChildren()) {
            // check that it is actually a servlet
            if (container instanceof StandardWrapper) {
                // cast to a servlet from generic container
                StandardWrapper servlet = (StandardWrapper) container;
                // if it is a jersey application servlet, and if a component name has been specified and this servlet matches
                if (servlet.getServletClass() == ServletContainer.class && (componentName == null ^ servlet.getName().equals(componentName))) {
                    Collection<String> mappings = servlet.getMappings();
                    String servletMapping = null;
                    if (mappings.size() > 0) {
                        // May be represented as "path/to/resource/*", which needs to be removed
                        servletMapping = mappings.toArray()[0].toString().replaceAll("/\\*", "");
                    }
                    jerseyApplicationMap.put((ServletContainer) servlet.getServlet(), servletMapping);
                }
            }
        }
    }
    return jerseyApplicationMap;
}
Also used : ServletContainer(org.glassfish.jersey.servlet.ServletContainer) WebContainer(com.sun.enterprise.web.WebContainer) Container(org.apache.catalina.Container) HashMap(java.util.HashMap) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) WebModule(com.sun.enterprise.web.WebModule) StandardWrapper(org.apache.catalina.core.StandardWrapper)

Aggregations

ServletContainer (org.glassfish.jersey.servlet.ServletContainer)49 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)30 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)29 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)24 Server (org.eclipse.jetty.server.Server)10 IOException (java.io.IOException)7 DispatcherType (javax.servlet.DispatcherType)6 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)6 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)5 ServletRegistrationBean (org.springframework.boot.web.servlet.ServletRegistrationBean)5 Bean (org.springframework.context.annotation.Bean)5 JacksonJaxbJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider)4 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)4 RequestLogHandler (org.eclipse.jetty.server.handler.RequestLogHandler)4 StatisticsHandler (org.eclipse.jetty.server.handler.StatisticsHandler)4 ServletRegistration (javax.servlet.ServletRegistration)3 ConnectException (org.apache.kafka.connect.errors.ConnectException)3 ConnectorPluginsResource (org.apache.kafka.connect.runtime.rest.resources.ConnectorPluginsResource)3 ConnectorsResource (org.apache.kafka.connect.runtime.rest.resources.ConnectorsResource)3 Slf4jRequestLog (org.eclipse.jetty.server.Slf4jRequestLog)3