org.eclipse.jetty.util.resource.ResourceCollection Java Examples

The following examples show how to use org.eclipse.jetty.util.resource.ResourceCollection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KsqlRestApplication.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceCollection getStaticResources() {
  log.info("User interface enabled: {}", isUiEnabled);
  if (isUiEnabled) {
    try {
      return new ResourceCollection(
          Resource.newResource(new File(this.uiFolder, EXPANDED_FOLDER).getCanonicalFile()));
    } catch (Exception e) {
      log.error("Unable to load ui from {}. You can disable the ui by setting {} to false",
          this.uiFolder + EXPANDED_FOLDER,
          KsqlRestConfig.UI_ENABLED_CONFIG,
          e);
    }
  }

  return super.getStaticResources();
}
 
Example #2
Source File: JettyAutoConfiguration.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
@Bean
public WebServerFactoryCustomizer<JettyServletWebServerFactory> jsfJettyFactoryCustomizer() {
	return factory -> factory.addServerCustomizers(new JettyServerCustomizer() {
		@Override
		@SneakyThrows(IOException.class)
		public void customize(Server server) {
			Handler[] childHandlersByClass = server.getChildHandlersByClass(WebAppContext.class);
			final WebAppContext webAppContext = (WebAppContext) childHandlersByClass[0];

			String classPathResourceString = JettyAutoConfiguration.this.jettyProperties.getClassPathResource();

			webAppContext.setBaseResource(new ResourceCollection(
				Resource.newResource(new ClassPathResource(classPathResourceString).getURI()),
				webAppContext.getBaseResource()));

			log.info("Setting Jetty classLoader to {} directory", classPathResourceString);
		}
	});
}
 
Example #3
Source File: ApplicationGroupTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticResourceIsolation() throws Exception {
  TestApp app1 = new TestApp("/app1");
  TestApp app2 = new TestApp("/app2") {
    @Override
    public void setupResources(final Configurable<?> config, final TestRestConfig appConfig) {
      config.register(RestResource.class);
      config.property(ServletProperties.FILTER_STATIC_CONTENT_REGEX, "/(index\\.html|)");
    }

    @Override
    protected ResourceCollection getStaticResources() {
      return new ResourceCollection(Resource.newClassPathResource("static"));
    }
  };

  server.registerApplication(app1);
  server.registerApplication(app2);
  server.start();

  assertThat(makeGetRequest("/app1/index.html"), is(Code.NOT_FOUND));
  assertThat(makeGetRequest("/app2/index.html"), is(Code.OK));
}
 
Example #4
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ContextHandler createDocsWebApp(final String contextPath) {
    try {
        final ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);

        // load the docs directory
        final File docsDir = Paths.get("docs").toRealPath().toFile();
        final Resource docsResource = Resource.newResource(docsDir);

        // load the component documentation working directory
        final String componentDocsDirPath = props.getProperty(NiFiProperties.COMPONENT_DOCS_DIRECTORY, "work/docs/components");
        final File workingDocsDirectory = Paths.get(componentDocsDirPath).toRealPath().getParent().toFile();
        final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);

        // load the rest documentation
        final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
        if (!webApiDocsDir.exists()) {
            final boolean made = webApiDocsDir.mkdirs();
            if (!made) {
                throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
            }
        }
        final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);

        // create resources for both docs locations
        final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
        resourceHandler.setBaseResource(resources);

        // create the context handler
        final ContextHandler handler = new ContextHandler(contextPath);
        handler.setHandler(resourceHandler);

        logger.info("Loading documents web app with context path set to " + contextPath);
        return handler;
    } catch (Exception ex) {
        throw new IllegalStateException("Resource directory paths are malformed: " + ex.getMessage());
    }
}
 
Example #5
Source File: HelloWorldApplication.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
@Override
protected ResourceCollection getStaticResources() {
  return new ResourceCollection(Resource.newClassPathResource("static"));
}
 
Example #6
Source File: Application.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
final Handler configureHandler() {
  ResourceConfig resourceConfig = new ResourceConfig();
  configureBaseApplication(resourceConfig, getMetricsTags());
  configureResourceExtensions(resourceConfig);
  setupResources(resourceConfig, getConfiguration());

  // Configure the servlet container
  ServletContainer servletContainer = new ServletContainer(resourceConfig);
  final FilterHolder servletHolder = new FilterHolder(servletContainer);

  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath(path);

  ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
  defaultHolder.setInitParameter("dirAllowed", "false");

  ResourceCollection staticResources = getStaticResources();
  if (staticResources != null) {
    context.setBaseResource(staticResources);
  }

  configureSecurityHandler(context);

  if (isCorsEnabled()) {
    String allowedOrigins = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
    filterHolder.setName("cross-origin");
    filterHolder.setInitParameter(
            CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins

    );
    String allowedMethods = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_METHODS);
    String allowedHeaders = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_HEADERS);
    if (allowedMethods != null && !allowedMethods.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
    }
    if (allowedHeaders != null && !allowedHeaders.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, allowedHeaders);
    }
    // handle preflight cors requests at the filter level, do not forward down the filter chain
    filterHolder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false");
    context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
  }

  if (config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG) != null
          && !config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG).isEmpty()) {
    configureHttpResponsHeaderFilter(context);
  }

  configurePreResourceHandling(context);
  context.addFilter(servletHolder, "/*", null);
  configurePostResourceHandling(context);
  context.addServlet(defaultHolder, "/*");

  applyCustomConfiguration(context, REST_SERVLET_INITIALIZERS_CLASSES_CONFIG);

  RequestLogHandler requestLogHandler = new RequestLogHandler();
  requestLogHandler.setRequestLog(requestLog);

  HandlerCollection handlers = new HandlerCollection();
  handlers.setHandlers(new Handler[]{context, requestLogHandler});

  return handlers;
}
 
Example #7
Source File: StaticResourcesTest.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
@Override
protected ResourceCollection getStaticResources() {
  return new ResourceCollection(Resource.newClassPathResource("static"));
}
 
Example #8
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public void startWebSocketServer(final Injector injector) {
  httpServer = new Server();

  List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
  if (connectors.isEmpty()) {
    LOG.severe("No valid http end point address provided!");
  }
  for (Connector connector : connectors) {
    httpServer.addConnector(connector);
  }
  final WebAppContext context = new WebAppContext();

  context.setParentLoaderPriority(true);

  if (jettySessionManager != null) {
    // This disables JSessionIDs in URLs redirects
    // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
    // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
    jettySessionManager.setSessionIdPathParameterName(null);

    context.getSessionHandler().setSessionManager(jettySessionManager);
  }
  final ResourceCollection resources = new ResourceCollection(resourceBases);
  context.setBaseResource(resources);

  addWebSocketServlets();

  try {

    final ServletModule servletModule = getServletModule();

    ServletContextListener contextListener = new GuiceServletContextListener() {

      private final Injector childInjector = injector.createChildInjector(servletModule);

      @Override
      protected Injector getInjector() {
        return childInjector;
      }
    };

    context.addEventListener(contextListener);
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
    httpServer.setHandler(context);

    httpServer.start();
    restoreSessions();

  } catch (Exception e) { // yes, .start() throws "Exception"
    LOG.severe("Fatal error starting http server.", e);
    return;
  }
  LOG.fine("WebSocket server running.");
}
 
Example #9
Source File: Application.java    From rest-utils with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a list of static resources to serve using the default servlet.
 *
 * <p>For example, static files can be served from class loader resources by returning
 * {@code
 * new ResourceCollection(Resource.newClassPathResource("static"));
 * }
 *
 * <p>For those resources to get served, it is necessary to add a static resources property to the
 * config in @link{{@link #setupResources(Configurable, RestConfig)}}, e.g. using something like
 * {@code
 * config.property(ServletProperties.FILTER_STATIC_CONTENT_REGEX, "/(static/.*|.*\\.html|)");
 * }
 *
 * @return static resource collection
 */
protected ResourceCollection getStaticResources() {
  return null;
}