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);
}
}
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());
}
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;
}
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()));
}
}
use of org.glassfish.jersey.servlet.ServletContainer in project heron by twitter.
the class Runtime method main.
@SuppressWarnings({ "IllegalCatch", "RegexpSinglelineJava" })
public static void main(String[] args) throws Exception {
final Options options = createOptions();
final Options helpOptions = constructHelpOptions();
CommandLineParser parser = new DefaultParser();
// parse the help options first.
CommandLine cmd = parser.parse(helpOptions, args, true);
if (cmd.hasOption(Flag.Help.name)) {
usage(options);
return;
}
try {
cmd = parser.parse(options, args);
} catch (ParseException pe) {
System.err.println(pe.getMessage());
usage(options);
return;
}
final boolean verbose = isVerbose(cmd);
// set and configure logging level
Logging.setVerbose(verbose);
Logging.configure(verbose);
LOG.debug("API server overrides:\n {}", cmd.getOptionProperties(Flag.Property.name));
final String toolsHome = getToolsHome();
// read command line flags
final String cluster = cmd.getOptionValue(Flag.Cluster.name);
final String heronConfigurationDirectory = getConfigurationDirectory(toolsHome, cmd);
final String heronDirectory = getHeronDirectory(cmd);
final String releaseFile = getReleaseFile(toolsHome, cmd);
final String configurationOverrides = loadOverrides(cmd);
final int port = getPort(cmd);
final String downloadHostName = getDownloadHostName(cmd);
final String heronCorePackagePath = getHeronCorePackagePath(cmd);
final Config baseConfiguration = ConfigUtils.getBaseConfiguration(heronDirectory, heronConfigurationDirectory, releaseFile, configurationOverrides);
final ResourceConfig config = new ResourceConfig(Resources.get());
final Server server = new Server(port);
final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
contextHandler.setContextPath("/");
LOG.info("using configuration path: {}", heronConfigurationDirectory);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_CLUSTER, cluster);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION, baseConfiguration);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_DIRECTORY, heronConfigurationDirectory);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_OVERRIDE_PATH, configurationOverrides);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_PORT, String.valueOf(port));
contextHandler.setAttribute(HeronResource.ATTRIBUTE_DOWNLOAD_HOSTNAME, Utils.isNotEmpty(downloadHostName) ? String.valueOf(downloadHostName) : null);
contextHandler.setAttribute(HeronResource.ATTRIBUTE_HERON_CORE_PACKAGE_PATH, Utils.isNotEmpty(heronCorePackagePath) ? String.valueOf(heronCorePackagePath) : null);
server.setHandler(contextHandler);
final ServletHolder apiServlet = new ServletHolder(new ServletContainer(config));
contextHandler.addServlet(apiServlet, API_BASE_PATH);
try {
server.start();
LOG.info("Heron API server started at {}", server.getURI());
server.join();
} catch (Exception ex) {
final String message = getErrorMessage(server, port, ex);
LOG.error(message);
System.err.println(message);
System.exit(1);
} finally {
server.destroy();
}
}
Aggregations