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");
}
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);
}
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;
}
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);
}
}
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;
}
Aggregations