io.undertow.server.handlers.resource.PathResourceManager Java Examples

The following examples show how to use io.undertow.server.handlers.resource.PathResourceManager. 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: DefaultServletCachingTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws ServletException, IOException {

    tmpDir = Files.createTempDirectory(DIR_NAME);

    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();

    DeploymentInfo builder = new DeploymentInfo()
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .setClassLoader(ServletPathMappingTestCase.class.getClassLoader())
            .setContextPath("/servletContext")
            .setDeploymentName("servletContext.war")
            .setResourceManager(new CachingResourceManager(100, 10000, dataCache, new PathResourceManager(tmpDir, 10485760, false, false, false), METADATA_MAX_AGE));

    builder.addServlet(new ServletInfo("DefaultTestServlet", PathTestServlet.class)
            .addMapping("/path/default"))
            .addFilter(Servlets.filter("message", MessageFilter.class).addInitParam(MessageFilter.MESSAGE, "FILTER_TEXT "))
            .addFilterUrlMapping("message", "*.txt", DispatcherType.REQUEST);

    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    root.addPrefixPath(builder.getContextPath(), manager.start());

    DefaultServer.setRootHandler(root);
}
 
Example #2
Source File: RangeRequestTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws URISyntaxException {
    Path rootPath = Paths.get(RangeRequestTestCase.class.getResource("range.txt").toURI()).getParent();
    PathHandler path = Handlers.path();
    path.addPrefixPath("/path", new ByteRangeHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.setResponseHeader(HttpHeaderNames.LAST_MODIFIED, DateUtils.toDateString(new Date(10000)));
            exchange.setResponseHeader(HttpHeaderNames.ETAG, "\"someetag\"");
            exchange.setResponseContentLength("0123456789".length());
            exchange.writeAsync(Unpooled.copiedBuffer("0123456789", StandardCharsets.UTF_8), true, IoCallback.END_EXCHANGE, null);
        }
    }, true));
    path.addPrefixPath("/resource",  new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/cachedresource",  new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/resource-blocking",  new BlockingHandler(new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true)));
    path.addPrefixPath("/cachedresource-blocking",  new BlockingHandler(new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true)));
    DefaultServer.setRootHandler(path);
}
 
Example #3
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testETagFunction() throws Exception {
    final String fileName = "page.html";
    final Path rootPath = Paths.get(getClass().getResource(fileName).toURI()).getParent();
    final ResourceManager resourceManager = PathResourceManager.builder()
            .setBase(rootPath)
            .setETagFunction(new PathResourceManager.ETagFunction() {
                @Override
                public ETag generate(Path path) {
                    return new ETag(true, path.getFileName().toString());
                }
            })
            .build();
    ETag expected = new ETag(true, fileName);
    ETag actual = resourceManager.getResource("page.html").getETag();
    Assert.assertEquals(expected, actual);
}
 
Example #4
Source File: FileServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
      .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))
        .setDirectoryListingEnabled(true))
      .build();
    server.start();
}
 
Example #5
Source File: FileServer.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
    Undertow server = Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))
                    .setDirectoryListingEnabled(true))
            .build();
    server.start();
}
 
Example #6
Source File: Server.java    From griffin with Apache License 2.0 5 votes vote down vote up
/**
    * Creates and starts the server to serve the contents of OUTPUT_DIRECTORY on port
9090.
    */
   protected void startPreview() {
       ResourceHandler resourceHandler = resource(new PathResourceManager(Paths.get(OUTPUT_DIRECTORY), 100, true, true))
               .setDirectoryListingEnabled(false);
       FileErrorPageHandler errorHandler = new FileErrorPageHandler(Paths.get(OUTPUT_DIRECTORY).resolve("404.html"), StatusCodes.NOT_FOUND);
       errorHandler.setNext(resourceHandler);
       GracefulShutdownHandler shutdown = Handlers.gracefulShutdown(errorHandler);
       Undertow server = Undertow.builder().addHttpListener(port, "localhost")
               .setHandler(shutdown)
               .build();
       server.start();
   }
 
Example #7
Source File: VirtualHostHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public VirtualHostHandler() {
    VirtualHostConfig config = (VirtualHostConfig)Config.getInstance().getJsonObjectConfig(VirtualHostConfig.CONFIG_NAME, VirtualHostConfig.class);
    virtualHostHandler = new NameVirtualHostHandler();
    for(VirtualHost host: config.hosts) {
        virtualHostHandler.addHost(host.domain, new PathHandler().addPrefixPath(host.getPath(), new ResourceHandler((new PathResourceManager(Paths.get(host.getBase()), host.getTransferMinSize()))).setDirectoryListingEnabled(host.isDirectoryListingEnabled())));
    }
}
 
Example #8
Source File: PathResourceHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public PathResourceHandler() {
    PathResourceConfig config = (PathResourceConfig)Config.getInstance().getJsonObjectConfig(PathResourceConfig.CONFIG_NAME, PathResourceConfig.class);
    if(config.isPrefix()) {
        pathHandler = new PathHandler()
                .addPrefixPath(config.getPath(), new ResourceHandler(new PathResourceManager(Paths.get(config.getBase()), config.getTransferMinSize()))
                        .setDirectoryListingEnabled(config.isDirectoryListingEnabled()));
    } else {
        pathHandler = new PathHandler()
                .addExactPath(config.getPath(), new ResourceHandler(new PathResourceManager(Paths.get(config.getBase()), config.getTransferMinSize()))
                        .setDirectoryListingEnabled(config.isDirectoryListingEnabled()));
    }
}
 
Example #9
Source File: CustomResourceHandler.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
private static ResourceManager buildResourceManager(Preferences preferences) {
    Path root = Paths.get(preferences.getString("webContent", "./WebContent")).toAbsolutePath();
    boolean cacheEnabled = preferences.getBoolean("cacheEnabled", true);

    return PathResourceManager.builder()
            .setBase(root)
            .setAllowResourceChangeListeners(false)
            .setETagFunction(new ETagSupplier(cacheEnabled, Utils.generateAlphanumericString(5)))
            .build();
}
 
Example #10
Source File: DebugVisualizerServer.java    From greycat with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String urltoConnect = "ws://localhost:5678";
        final String serverUrl = "0.0.0.0";
        final int serverPort = 8080;

        Undertow server = Undertow.builder()
                .addHttpListener(serverPort,serverUrl)
                .setHandler(
                        Handlers.path(
                                Handlers.resource(
                                        new PathResourceManager(Paths.get("plugins/visualizer/src/main/resources").toAbsolutePath(),0)
                                )
                        )
                )
                .build();


        server.start();

        StringBuilder goToBuilder = new StringBuilder();
        goToBuilder.append("http://")
                .append(serverUrl)
                .append(":")
                .append(serverPort)
                .append("?q=")
                .append(urltoConnect);
        System.out.println("Go to: " + goToBuilder);


        System.out.println();

    }
 
Example #11
Source File: PreCompressedResourceTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("UT3 - P4")
public void testCorrectResourceSelected() throws IOException, URISyntaxException {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

    try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
        DefaultServer.setRootHandler(new CanonicalPathHandler()
                .setNext(new PathHandler()
                        .addPrefixPath("/path",new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gzip"))
                                        .setDirectoryListingEnabled(true)))
                );

        //assert response without compression
        final String plainResponse = assertResponse(client.execute(get), false);

        //assert compressed response generated by filter
        assertResponse(compClient.execute(get), true, plainResponse);

        //generate resources
        generatePreCompressedResource("gzip");
        generatePreCompressedResource("nonsense");
        generatePreCompressedResource("gzip.nonsense");

        //assert compressed response that was pre compressed
        assertResponse(compClient.execute(get), true, plainResponse, "gzip");

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #12
Source File: PreCompressedResourceTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testContentEncodedResource() throws IOException, URISyntaxException {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

    try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
        DefaultServer.setRootHandler(new CanonicalPathHandler()
                .setNext(new PathHandler()
                        .addPrefixPath("/path", new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gz"))
                                .setDirectoryListingEnabled(true))));

        //assert response without compression
        final String plainResponse = assertResponse(client.execute(get), false);

        //assert compressed response, that doesn't exists, so returns plain
        assertResponse(compClient.execute(get), false, plainResponse);

        //generate compressed resource with extension .gz
        generatePreCompressedResource("gz");

        //assert compressed response that was pre compressed
        assertResponse(compClient.execute(get), true, plainResponse, "gz");

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #13
Source File: FileHandlerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws URISyntaxException {
    Path rootPath = Paths.get(FileHandlerTestCase.class.getResource("page.html").toURI()).getParent().getParent();
    HttpHandler root = new CanonicalPathHandler()
            .setNext(new PathHandler()
                    .addPrefixPath("/path", new ResourceHandler(new PathResourceManager(rootPath, 1))
                            // 1 byte = force transfer
                            .setDirectoryListingEnabled(true)));
    Undertow undertow = Undertow.builder()
            .addHttpListener(8888, "localhost")
            .setHandler(root)
            .build();
    undertow.start();
}
 
Example #14
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testBaseDirInSymlink() throws Exception {
    Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));

    Path filePath = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = filePath.getParent();

    Path newDir = rootPath.resolve("newDir");
    Path innerPage = newDir.resolve("page.html");
    Path newSymlink = rootPath.resolve("newSymlink");
    try {
        Files.createDirectories(newDir);
        Files.copy(filePath, innerPage);
        Files.createSymbolicLink(newSymlink, newDir);

        Assert.assertTrue("Ensure that newSymlink is still a symlink as expected", Files.isSymbolicLink(newSymlink));
        final PathResourceManager resourceManager = new PathResourceManager(newSymlink, 1024 * 1024);
        Assert.assertNotNull(resourceManager.getResource("page.html"));
        Assert.assertNull(resourceManager.getResource("Page.html"));
        Assert.assertNotNull(resourceManager.getResource("./page.html"));

    } finally {
        Files.deleteIfExists(newSymlink);
        Files.deleteIfExists(innerPage);
        Files.deleteIfExists(newDir);
        Files.deleteIfExists(newDir);
    }

}
 
Example #15
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testCantEscapeRoot() throws Exception {

    final Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent().resolve("subdir");
    final PathResourceManager resourceManager = new PathResourceManager(rootPath, 1024 * 1024);
    Assert.assertNotNull(resourceManager.getResource("a.txt"));
    Assert.assertNull(resourceManager.getResource("../page.html"));
}
 
Example #16
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testListDir() throws Exception {

    final Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    final PathResourceManager resourceManager = new PathResourceManager(rootPath, 1024 * 1024);
    Resource subdir = resourceManager.getResource("subdir");
    Resource found = subdir.list().get(0);
    Assert.assertEquals("subdir" + File.separatorChar+ "a.txt", found.getPath());
}
 
Example #17
Source File: PathResourceManagerTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResource() throws Exception {

    final Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    final PathResourceManager resourceManager = new PathResourceManager(rootPath, 1024 * 1024);
    Assert.assertNotNull(resourceManager.getResource("page.html"));
    Assert.assertNotNull(resourceManager.getResource("./page.html"));
    Assert.assertNotNull(resourceManager.getResource("../file/page.html"));
}
 
Example #18
Source File: GetResourceTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpecialCharacterInFileURL() throws IOException {
    String tmp = System.getProperty("java.io.tmpdir");
    PathResourceManager pathResourceManager = new PathResourceManager(Paths.get(tmp), 1);
    Path file = Paths.get(tmp, "1#2.txt");
    Files.write(file, "Hi".getBytes());
    Resource res = pathResourceManager.getResource("1#2.txt");
    try(InputStream in = res.getUrl().openStream()) {
        Assert.assertEquals("Hi", FileUtils.readFile(in));
    }
}
 
Example #19
Source File: Http2Server.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    String version = System.getProperty("java.version");
    System.out.println("Java version " + version);
    if(version.charAt(0) == '1' && Integer.parseInt(version.charAt(2) + "") < 8 ) {
        System.out.println("This example requires Java 1.8 or later");
        System.out.println("The HTTP2 spec requires certain cyphers that are not present in older JVM's");
        System.out.println("See section 9.2.2 of the HTTP2 specification for details");
        System.exit(1);
    }
    String bindAddress = System.getProperty("bind.address", "localhost");
    SSLContext sslContext = createSSLContext(loadKeyStore("server.keystore"), loadKeyStore("server.truststore"));
    Undertow server = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8080, bindAddress)
            .addHttpsListener(8443, bindAddress, sslContext)
            .setHandler(new SessionAttachmentHandler(new LearningPushHandler(100, -1, Handlers.header(predicate(secure(), resource(new PathResourceManager(Paths.get(System.getProperty("example.directory", System.getProperty("user.home"))), 100))
                    .setDirectoryListingEnabled(true), new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.getResponseHeaders().add(Headers.LOCATION, "https://" + exchange.getHostName() + ":" + (exchange.getHostPort() + 363) + exchange.getRelativePath());
                    exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                }
            }), "x-undertow-transport", ExchangeAttributes.transportProtocol())), new InMemorySessionManager("test"), new SessionCookieConfig())).build();

    server.start();

    SSLContext clientSslContext = createSSLContext(loadKeyStore("client.keystore"), loadKeyStore("client.truststore"));
    LoadBalancingProxyClient proxy = new LoadBalancingProxyClient()
            .addHost(new URI("https://localhost:8443"), null, new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, clientSslContext), UndertowOptionMap.create(UndertowOptions.ENABLE_HTTP2, true))
            .setConnectionsPerThread(20);

    Undertow reverseProxy = Undertow.builder()
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true)
            .addHttpListener(8081, bindAddress)
            .addHttpsListener(8444, bindAddress, sslContext)
            .setHandler(ProxyHandler.builder().setProxyClient(proxy).setMaxRequestTime( 30000).build())
            .build();
    reverseProxy.start();

}