Search in sources :

Example 46 with ServletContainer

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

the class UIServer method main.

/**
 * main.
 * @param args args
 */
public static void main(String[] args) {
    Map<String, Object> conf = ConfigUtils.readStormConfig();
    int headerBufferSize = (int) conf.get(DaemonConfig.UI_HEADER_BUFFER_BYTES);
    final Integer httpsPort = ObjectReader.getInt(conf.get(DaemonConfig.UI_HTTPS_PORT), 0);
    final String httpsKsPath = (String) (conf.get(DaemonConfig.UI_HTTPS_KEYSTORE_PATH));
    final String httpsKsPassword = (String) (conf.get(DaemonConfig.UI_HTTPS_KEYSTORE_PASSWORD));
    final String httpsKsType = (String) (conf.get(DaemonConfig.UI_HTTPS_KEYSTORE_TYPE));
    final String httpsKeyPassword = (String) (conf.get(DaemonConfig.UI_HTTPS_KEY_PASSWORD));
    final String httpsTsPath = (String) (conf.get(DaemonConfig.UI_HTTPS_TRUSTSTORE_PATH));
    final String httpsTsPassword = (String) (conf.get(DaemonConfig.UI_HTTPS_TRUSTSTORE_PASSWORD));
    final String httpsTsType = (String) (conf.get(DaemonConfig.UI_HTTPS_TRUSTSTORE_TYPE));
    final Boolean httpsWantClientAuth = (Boolean) (conf.get(DaemonConfig.UI_HTTPS_WANT_CLIENT_AUTH));
    final Boolean httpsNeedClientAuth = (Boolean) (conf.get(DaemonConfig.UI_HTTPS_NEED_CLIENT_AUTH));
    final Boolean disableHttpBinding = (Boolean) (conf.get(DaemonConfig.UI_DISABLE_HTTP_BINDING));
    final boolean enableSslReload = ObjectReader.getBoolean(conf.get(DaemonConfig.UI_HTTPS_ENABLE_SSL_RELOAD), false);
    Server jettyServer = UIHelpers.jettyCreateServer((int) conf.get(DaemonConfig.UI_PORT), null, httpsPort, headerBufferSize, disableHttpBinding);
    UIHelpers.configSsl(jettyServer, httpsPort, httpsKsPath, httpsKsPassword, httpsKsType, httpsKeyPassword, httpsTsPath, httpsTsPassword, httpsTsType, httpsNeedClientAuth, httpsWantClientAuth, enableSslReload);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    jettyServer.setHandler(context);
    FilterConfiguration filterConfiguration = new FilterConfiguration((String) conf.get(DaemonConfig.UI_FILTER), (Map<String, String>) conf.get(DaemonConfig.UI_FILTER_PARAMS));
    final List<FilterConfiguration> filterConfigurationList = Arrays.asList(filterConfiguration);
    UIHelpers.configFilters(context, filterConfigurationList);
    StormMetricsRegistry metricsRegistry = new StormMetricsRegistry();
    ResourceConfig resourceConfig = new ResourceConfig().packages("org.apache.storm.daemon.ui.resources").registerInstances(new AbstractBinder() {

        @Override
        protected void configure() {
            super.bind(metricsRegistry).to(StormMetricsRegistry.class);
        }
    }).register(AuthorizedUserFilter.class).register(HeaderResponseFilter.class).register(AuthorizationExceptionMapper.class).register(NotAliveExceptionMapper.class).register(DefaultExceptionMapper.class);
    ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(resourceConfig));
    jerseyServlet.setInitOrder(0);
    context.addServlet(jerseyServlet, STORM_API_URL_PREFIX + "*");
    addRequestContextFilter(context, DaemonConfig.UI_HTTP_CREDS_PLUGIN, conf);
    // add special pathspec of static content mapped to the homePath
    ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
    String packagedStaticFileLocation = System.getProperty(STORM_HOME) + FILE_SEPARATOR + "public/";
    if (Files.exists(Paths.get(packagedStaticFileLocation))) {
        holderHome.setInitParameter("resourceBase", packagedStaticFileLocation);
    } else {
        LOG.warn("Cannot find static file directory in " + packagedStaticFileLocation + " - assuming that UIServer is being launched" + "in a development environment and not from a packaged release");
        String developmentStaticFileLocation = UIServer.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "WEB-INF";
        if (Files.exists(Paths.get(developmentStaticFileLocation))) {
            holderHome.setInitParameter("resourceBase", developmentStaticFileLocation);
        } else {
            throw new RuntimeException("Cannot find static file directory in development " + "location " + developmentStaticFileLocation);
        }
    }
    holderHome.setInitParameter("dirAllowed", "true");
    holderHome.setInitParameter("pathInfoOnly", "true");
    context.addFilter(new FilterHolder(new HeaderResponseServletFilter(metricsRegistry)), "/*", EnumSet.allOf(DispatcherType.class));
    context.addServlet(holderHome, "/*");
    // Lastly, the default servlet for root content (always needed, to satisfy servlet spec)
    ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
    holderPwd.setInitParameter("dirAllowed", "true");
    context.addServlet(holderPwd, "/");
    metricsRegistry.startMetricsReporters(conf);
    Utils.addShutdownHookWithForceKillIn1Sec(metricsRegistry::stopMetricsReporters);
    try {
        jettyServer.start();
        jettyServer.join();
    } catch (Throwable t) {
        LOG.error("Exception in UIServer: ", t);
        throw new RuntimeException(t);
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) NotAliveExceptionMapper(org.apache.storm.daemon.ui.exceptionmappers.NotAliveExceptionMapper) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) StormMetricsRegistry(org.apache.storm.metric.StormMetricsRegistry) AbstractBinder(org.glassfish.hk2.utilities.binding.AbstractBinder) HeaderResponseFilter(org.apache.storm.daemon.ui.filters.HeaderResponseFilter) HeaderResponseServletFilter(org.apache.storm.daemon.ui.filters.HeaderResponseServletFilter) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DispatcherType(javax.servlet.DispatcherType)

Example 47 with ServletContainer

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

the class JsonRestServer method start.

/**
 * Start the JsonRestServer.
 *
 * @param resources         The path handling resources to register.
 */
public void start(Object... resources) {
    log.info("Starting REST server");
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider(JsonUtil.JSON_SERDE));
    for (Object resource : resources) {
        resourceConfig.register(resource);
        log.info("Registered resource {}", resource);
    }
    resourceConfig.register(RestExceptionMapper.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter();
    slf4jRequestLogWriter.setLoggerName(JsonRestServer.class.getCanonicalName());
    CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T");
    requestLogHandler.setRequestLog(requestLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler(), requestLogHandler });
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);
    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new RuntimeException("Unable to start REST server", e);
    }
    log.info("REST server listening at " + jettyServer.getURI());
}
Also used : CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) Slf4jRequestLogWriter(org.eclipse.jetty.server.Slf4jRequestLogWriter) IOException(java.io.IOException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler)

Example 48 with ServletContainer

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

the class WebServer method createServletContextHandler.

private ServletContextHandler createServletContextHandler(final boolean authEnabled) throws DrillbitStartupException {
    // Add resources
    final ErrorHandler errorHandler = new DrillErrorHandler();
    errorHandler.setShowStacks(true);
    errorHandler.setShowMessageInTitle(true);
    final ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContextHandler.setErrorHandler(errorHandler);
    servletContextHandler.setContextPath("/");
    final ServletHolder servletHolder = new ServletHolder(new ServletContainer(new DrillRestServer(workManager, servletContextHandler.getServletContext(), drillbit)));
    servletHolder.setInitOrder(1);
    servletContextHandler.addServlet(servletHolder, "/*");
    servletContextHandler.addServlet(new ServletHolder(new MetricsServlet(metrics)), STATUS_METRICS_PATH);
    servletContextHandler.addServlet(new ServletHolder(new ThreadDumpServlet()), STATUS_THREADS_PATH);
    final ServletHolder staticHolder = new ServletHolder("static", DefaultServlet.class);
    // Get resource URL for Drill static assets, based on where Drill icon is located
    String drillIconResourcePath = Resource.newClassPathResource(BASE_STATIC_PATH + DRILL_ICON_RESOURCE_RELATIVE_PATH).getURI().toString();
    staticHolder.setInitParameter("resourceBase", drillIconResourcePath.substring(0, drillIconResourcePath.length() - DRILL_ICON_RESOURCE_RELATIVE_PATH.length()));
    staticHolder.setInitParameter("dirAllowed", "false");
    staticHolder.setInitParameter("pathInfoOnly", "true");
    servletContextHandler.addServlet(staticHolder, "/static/*");
    // Add Local path resource (This will allow access to dynamically created files like JavaScript)
    final ServletHolder dynamicHolder = new ServletHolder("dynamic", DefaultServlet.class);
    // Skip if unable to get a temp directory (e.g. during Unit tests)
    if (getOrCreateTmpJavaScriptDir() != null) {
        dynamicHolder.setInitParameter("resourceBase", getOrCreateTmpJavaScriptDir().getAbsolutePath());
        dynamicHolder.setInitParameter("dirAllowed", "true");
        dynamicHolder.setInitParameter("pathInfoOnly", "true");
        servletContextHandler.addServlet(dynamicHolder, "/dynamic/*");
    }
    if (authEnabled) {
        // DrillSecurityHandler is used to support SPNEGO and FORM authentication together
        servletContextHandler.setSecurityHandler(new DrillHttpSecurityHandlerProvider(config, workManager.getContext()));
        servletContextHandler.setSessionHandler(createSessionHandler(servletContextHandler.getSecurityHandler()));
    }
    // Applying filters for CSRF protection.
    servletContextHandler.addFilter(CsrfTokenInjectFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    for (String path : new String[] { "/query", "/storage/create_update", "/option/*" }) {
        servletContextHandler.addFilter(CsrfTokenValidateFilter.class, path, EnumSet.of(DispatcherType.REQUEST));
    }
    if (config.getBoolean(ExecConstants.HTTP_CORS_ENABLED)) {
        FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
        holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, StringUtils.join(config.getStringList(ExecConstants.HTTP_CORS_ALLOWED_ORIGINS), ","));
        holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, StringUtils.join(config.getStringList(ExecConstants.HTTP_CORS_ALLOWED_METHODS), ","));
        holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, StringUtils.join(config.getStringList(ExecConstants.HTTP_CORS_ALLOWED_HEADERS), ","));
        holder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, String.valueOf(config.getBoolean(ExecConstants.HTTP_CORS_CREDENTIALS)));
        for (String path : new String[] { "*.json", "/storage/*/enable/*", "/status*" }) {
            servletContextHandler.addFilter(holder, path, EnumSet.of(DispatcherType.REQUEST));
        }
    }
    // Allow for Other Drillbits to make REST calls
    FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
    filterHolder.setInitParameter("allowedOrigins", "*");
    // Allowing CORS for metrics only
    servletContextHandler.addFilter(filterHolder, STATUS_METRICS_PATH, null);
    FilterHolder responseHeadersSettingFilter = new FilterHolder(ResponseHeadersSettingFilter.class);
    responseHeadersSettingFilter.setInitParameters(ResponseHeadersSettingFilter.retrieveResponseHeaders(config));
    servletContextHandler.addFilter(responseHeadersSettingFilter, "/*", EnumSet.of(DispatcherType.REQUEST));
    return servletContextHandler;
}
Also used : DrillErrorHandler(org.apache.drill.exec.server.rest.auth.DrillErrorHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) DrillErrorHandler(org.apache.drill.exec.server.rest.auth.DrillErrorHandler) DrillHttpSecurityHandlerProvider(org.apache.drill.exec.server.rest.auth.DrillHttpSecurityHandlerProvider) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) MetricsServlet(com.codahale.metrics.servlets.MetricsServlet) ThreadDumpServlet(com.codahale.metrics.servlets.ThreadDumpServlet) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 49 with ServletContainer

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

the class WebServer method buildServlets.

/**
 * Build the web app with embedded servlets.
 * <p>
 * <b>ServletContextHandler</b>: is a Jetty-provided handler that add the
 * extra bits needed to set up the context that servlets expect. Think of it
 * as an adapter between the (simple) Jetty handler and the (more complex)
 * servlet API.
 */
private void buildServlets(Config config) {
    final ServletContextHandler servletContextHandler = new ServletContextHandler(null, "/");
    servletContextHandler.setErrorHandler(createErrorHandler());
    jettyServer.setHandler(servletContextHandler);
    // Servlet holder for the pages of the Drill AM web app. The web app is a
    // javax.ws application driven from annotations. The servlet holder "does
    // the right thing" to drive the application, which is rooted at "/".
    // The servlet container comes from Jersey, and manages the servlet
    // lifecycle.
    final ServletHolder servletHolder = new ServletHolder(new ServletContainer(new WebUiPageTree(dispatcher)));
    servletHolder.setInitOrder(1);
    servletContextHandler.addServlet(servletHolder, "/*");
    final ServletHolder restHolder = new ServletHolder(new ServletContainer(new AmRestApi(dispatcher)));
    restHolder.setInitOrder(2);
    servletContextHandler.addServlet(restHolder, "/rest/*");
    // Applying filters for CSRF protection.
    servletContextHandler.addFilter(CsrfTokenInjectFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    for (String path : new String[] { "/resize", "/stop", "/cancel" }) {
        servletContextHandler.addFilter(CsrfTokenValidateFilter.class, path, EnumSet.of(DispatcherType.REQUEST));
    }
    // Static resources (CSS, images, etc.)
    setupStaticResources(servletContextHandler);
    if (AMSecurityManagerImpl.isEnabled()) {
        servletContextHandler.setSecurityHandler(createSecurityHandler());
        servletContextHandler.setSessionHandler(createSessionHandler(config, servletContextHandler.getSecurityHandler()));
    }
}
Also used : ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 50 with ServletContainer

use of org.glassfish.jersey.servlet.ServletContainer in project data-transfer-project by google.

the class JerseyTransportBinder method start.

@SuppressWarnings("unchecked")
public void start() {
    try {
        Set<Object> controllers = new HashSet<>();
        controllers.add(new DataTypesController(actions.get(GetDataTypes.class)));
        controllers.add(new TransferServicesController(actions.get(GetTransferServices.class)));
        controllers.add(new TransferController(actions.get(CreateTransferJob.class), actions.get(GenerateServiceAuthData.class), actions.get(ReserveWorker.class), actions.get(GetReservedWorker.class), actions.get(StartTransferJob.class), actions.get(GetTransferJob.class)));
        // Create a Jersey JAX-RS Application (resourceConfig), add the actions, and register it with
        // the Jetty transport.
        ResourceConfig resourceConfig = new ResourceConfig();
        // resourceConfig.register(JacksonFeature.class)
        resourceConfig.registerInstances(controllers);
        ServletContainer servletContainer = new ServletContainer(resourceConfig);
        jettyTransport.registerServlet("/api/*", servletContainer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ServletContainer(org.glassfish.jersey.servlet.ServletContainer) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) HashSet(java.util.HashSet)

Aggregations

ServletContainer (org.glassfish.jersey.servlet.ServletContainer)50 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)30 ResourceConfig (org.glassfish.jersey.server.ResourceConfig)30 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