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

The following examples show how to use org.eclipse.jetty.util.resource.PathResource. 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: WebServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private ServerConnector getConnector() {
  if ( sslConfig != null ) {
    log.logBasic( BaseMessages.getString( PKG, "WebServer.Log.SslModeUsing" ) );
    SslConnectionFactory connector = new SslConnectionFactory();

    SslContextFactory contextFactory = new SslContextFactory();
    contextFactory.setKeyStoreResource( new PathResource( new File( sslConfig.getKeyStore() ) ) );
    contextFactory.setKeyStorePassword( sslConfig.getKeyStorePassword() );
    contextFactory.setKeyManagerPassword( sslConfig.getKeyPassword() );
    contextFactory.setKeyStoreType( sslConfig.getKeyStoreType() );
    return new ServerConnector( server, connector );
  } else {
    return new ServerConnector( server );
  }

}
 
Example #2
Source File: FileHandler.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Resource getResource(String path) {
    try {
        Resource resource = super.getResource(path);
        if (resource == null) return null;
        if (!(resource instanceof PathResource) || !resource.exists()) return resource;
        File f = resource.getFile();
        if (f.isDirectory() && !path.equals("/")) return resource;
        CacheResource cache = resourceCache.get(f);
        if (cache != null) return cache;
        if (f.length() < CACHE_LIMIT || f.getName().endsWith(".html") || path.equals("/")) {
            cache = new CacheResource((PathResource) resource);
            resourceCache.put(f, cache);
            return cache;
        }
        return resource;
    } catch (IOException e) {
        Data.logger.warn("", e);
    }
    return null;
}
 
Example #3
Source File: FileHandler.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public CacheResource(PathResource pathResource) throws IOException {
    this.file = pathResource.getFile();
    if (this.file.isDirectory()) this.file = new File(this.file, "index.html");
    this.includes = new ArrayList<>(8);
    initCache(System.currentTimeMillis());
    pathResource.close();
    
}
 
Example #4
Source File: GraphQlServer.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(HTTP_PORT);

  ServletContextHandler context = new ServletContextHandler(server, "/", SESSIONS);

  context.addEventListener(
      new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
          return Guice.createInjector(
              new ServletModule() {
                @Override
                protected void configureServlets() {
                  serve("/graphql").with(GraphQlServlet.class);
                }
              },
              new DataLoaderModule(),
              new SchemaProviderModule(), // Part of Rejoiner framework (Provides `@Schema
              // GraphQLSchema`)
              new ClientModule(), // Installs all of the client modules
              new SchemaModule() // Installs all of the schema modules
              );
        }
      });

  context.addFilter(GuiceFilter.class, "/*", EnumSet.of(REQUEST, ASYNC));

  context.setBaseResource(
      new PathResource(new File("./src/main/resources").toPath().toRealPath()));
  context.addServlet(DefaultServlet.class, "/");
  server.start();
  logger.info("Server running on port " + HTTP_PORT);
  server.join();
}
 
Example #5
Source File: EmbeddedJetty.java    From junit-servers with MIT License 4 votes vote down vote up
/**
 * Build web app context used to launch server.
 * May be override by subclasses.
 *
 * @throws Exception May be thrown by web app context initialization (will be wrapped later).
 */
private WebAppContext createdWebAppContext() throws Exception {
	final String path = configuration.getPath();
	final String webapp = configuration.getWebapp();
	final String classpath = configuration.getClasspath();
	final ClassLoader parentClassLoader = configuration.getParentClassLoader();
	final String overrideDescriptor = configuration.getOverrideDescriptor();
	final Resource baseResource = configuration.getBaseResource();
	final String containerJarPattern = configuration.getContainerJarPattern();
	final String webInfJarPattern = configuration.getWebInfJarPattern();

	final WebAppContext ctx = new WebAppContext();

	if (containerJarPattern != null) {
		log.debug("Setting jetty 'containerJarPattern' attribute: {}", containerJarPattern);
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerJarPattern);
	}
	else if (Java.isPostJdk9()) {
		// Fix to make TLD scanning works with Java >= 9
		log.debug("Setting default jetty 'containerJarPattern' for JRE >= 9: {}");
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar");
	}

	if (webInfJarPattern != null) {
		log.debug("Setting jetty 'WebInfJarPattern' attribute: {}", webInfJarPattern);
		ctx.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfJarPattern);
	}

	final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader();
	final ClassLoader classLoader;

	if (parentClassLoader != null) {
		log.debug("Overriding jetty parent classloader");
		classLoader = new CompositeClassLoader(parentClassLoader, systemClassLoader);
	}
	else {
		log.debug("Using current thread classloader as jetty parent classloader");
		classLoader = systemClassLoader;
	}

	log.debug("Set jetty classloader");
	ctx.setClassLoader(classLoader);

	log.debug("Set jetty context path to: {}", path);
	ctx.setContextPath(path);

	if (baseResource == null) {
		// use default base resource
		log.debug("Initializing default jetty base resource from: {}", webapp);
		ctx.setBaseResource(newResource(webapp));
	}
	else {
		log.debug("Initializing jetty base resource from: {}", baseResource);
		ctx.setBaseResource(baseResource);
	}

	if (overrideDescriptor != null) {
		log.debug("Set jetty descriptor: {}", overrideDescriptor);
		ctx.setOverrideDescriptor(overrideDescriptor);
	}

	log.debug("Initializing jetty configuration classes");
	ctx.setConfigurations(new Configuration[] {
		new WebInfConfiguration(),
		new WebXmlConfiguration(),
		new AnnotationConfiguration(),
		new JettyWebXmlConfiguration(),
		new MetaInfConfiguration(),
		new FragmentConfiguration()
	});

	if (isNotBlank(classpath)) {
		log.debug("Adding jetty container resource: {}", classpath);

		// Fix to scan Spring WebApplicationInitializer
		// This will add compiled classes to jetty classpath
		// See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration
		// And more precisely: http://stackoverflow.com/a/18449506/1215828
		final File classes = new File(classpath);
		final PathResource containerResources = new PathResource(classes.toURI());
		ctx.getMetaData().addContainerResource(containerResources);
	}

	ctx.setParentLoaderPriority(true);
	ctx.setWar(webapp);
	ctx.setServer(server);

	// Add server context
	server.setHandler(ctx);

	return ctx;
}
 
Example #6
Source File: VertxPluginRegistryTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Build and start a fake local Maven Repository server based on Jetty
 *
 * @throws Exception
 */
@BeforeClass
public static void BuildLocalMavenRepo() throws Exception {
    //This function create a Localhost fake Maven Repository, hosting a single Test Plugin

    //Get Test plugin file
    File sourcePlugin = new File("src/test/resources/io/apiman/gateway/platforms/vertx3/engine/plugin-with-policyDefs.war");
    if (!sourcePlugin.exists()) {
        throw new Exception("Failed to find test plugin war at: " + sourcePlugin.getAbsolutePath());
    }

    //Create Local Maven Repository folder
    File repoFolder = Files.createTempDirectory("MockedMavenRepo").toFile();

    //Define Test plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);

    //Build Test Plugin path in local Maven Repository folder
    File PluginFile = new File(repoFolder, PluginUtils.getMavenPath(coordinates));
    PluginFile.getParentFile().mkdirs();

    //Copy Test Plugin war into repository
    FileUtils.copyFile(sourcePlugin, PluginFile);

    //Create local Maven Repository Web Server
    mavenServer = new Server();
    ServerConnector connector = new ServerConnector(mavenServer);
    // auto-bind to available port
    connector.setPort(0);
    connector.setHost("0.0.0.0");
    mavenServer.addConnector(connector);

    //Add classic ressource handler
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    PathResource pathResource = new PathResource(repoFolder);
    resourceHandler.setBaseResource(pathResource);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
    mavenServer.setHandler(handlers);

    //Start local Maven Repository Server
    mavenServer.start();

    // Determine Base URI for Server
    String host = connector.getHost();
    if (host == null || host == "0.0.0.0") host = "127.0.0.1";
    int port = connector.getLocalPort();
    mavenServerUri = new URI(String.format("http://%s:%d/", host, port));
}