Search in sources :

Example 16 with Resource

use of io.undertow.server.handlers.resource.Resource in project spring-boot by spring-projects.

the class JarResourceManagerTests method rootPathIsHandledCorrectly.

@Test
public void rootPathIsHandledCorrectly() throws IOException {
    Resource resource = this.resourceManager.getResource("/");
    assertThat(resource).isNotNull();
    assertThat(resource.isDirectory()).isTrue();
}
Also used : Resource(io.undertow.server.handlers.resource.Resource) Test(org.junit.Test)

Example 17 with Resource

use of io.undertow.server.handlers.resource.Resource in project spring-boot by spring-projects.

the class JarResourceManagerTests method resourceIsFoundInJarFile.

@Test
public void resourceIsFoundInJarFile() throws IOException {
    Resource resource = this.resourceManager.getResource("/hello.txt");
    assertThat(resource).isNotNull();
    assertThat(resource.isDirectory()).isFalse();
    assertThat(resource.getContentLength()).isEqualTo(5);
}
Also used : Resource(io.undertow.server.handlers.resource.Resource) Test(org.junit.Test)

Example 18 with Resource

use of io.undertow.server.handlers.resource.Resource in project kontraktor by RuedigerMoeller.

the class DynamicResourceManager method getResource.

@Override
public Resource getResource(String initialPath) {
    String normalizedPath;
    byte[] debugLib = debugInstalls.get(initialPath);
    if (debugLib != null) {
        return new MyResource(initialPath, initialPath.substring(1), debugLib, "" + "text/javascript", null);
    }
    if (initialPath.startsWith("/")) {
        normalizedPath = initialPath.substring(1);
    } else {
        normalizedPath = initialPath;
    }
    if (!isDevMode()) {
        // lookup cache if not devmode
        if (normalizedPath.startsWith("f5_")) {
            lookupCache.clear();
            return super.getResource(initialPath);
        }
        Resource res = lookupCache.get(normalizedPath);
        if (res != null) {
            return res;
        }
        if (cachedIndexDir != null && cachedIndexDir.exists() && initialPath.endsWith("index.html")) {
            try {
                byte[] bytes = FileUtil.readFully(new File(cachedIndexDir, normalizedPath));
                Log.Info(this, "reading " + normalizedPath + " from static file " + new File(cachedIndexDir, normalizedPath).getAbsolutePath());
                return mightCache(normalizedPath, new MyResource(initialPath, normalizedPath, bytes, "text/html", !isDevMode() ? lastStartup : null));
            } catch (IOException e) {
                Log.Warn(this, e);
            }
        }
    }
    // import shim is applied to *index.html file only
    if (initialPath.endsWith("index.html") && importShim != null) {
        try {
            Element element = importShim.shimImports(normalizedPath);
            if (element == null) {
                return super.getResource(initialPath);
            }
            byte[] bytes = element.toString().getBytes("UTF-8");
            if (!devMode && cachedIndexDir != null) {
                // save to file for static serving
                cachedIndexDir.mkdirs();
                Files.write(new File(cachedIndexDir, normalizedPath).toPath(), bytes);
            }
            return mightCache(normalizedPath, new MyResource(initialPath, normalizedPath, bytes, "text/html", !isDevMode() ? lastStartup : null));
        } catch (IOException e) {
            Log.Warn(this, e);
        }
    } else {
        File file = dependencyResolver.locateResource(normalizedPath);
        if (file != null) {
            // FIMXE: could be done via TranspilerHook now ..
            final String fname = file.getName();
            if (fname.endsWith(".js") && minify) {
                try {
                    byte[] bytes = FileUtil.readFully(file);
                    bytes = runJSPostProcessors(jsPostProcessors, bytes);
                    return mightCache(normalizedPath, new MyResource(initialPath, normalizedPath, bytes, "text/javascript", !isDevMode() ? lastStartup : null));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (transpilerMap != null && transpilerMap.size() > 0) {
                try {
                    int idx = fname.lastIndexOf('.');
                    if (idx > 0) {
                        String ext = fname.substring(idx + 1).toLowerCase();
                        TranspilerHook transpilerHook = transpilerMap.get(ext);
                        if (transpilerHook != null) {
                            byte[] transpiled = transpilerHook.transpile(file, this, new HashMap());
                            if (minify) {
                                transpiled = runJSPostProcessors(jsPostProcessors, transpiled);
                            }
                            if (transpiled != null) {
                                return mightCache(normalizedPath, new MyResource(initialPath, normalizedPath, transpiled, "text/javascript", !isDevMode() ? lastStartup : null));
                            }
                        }
                    }
                } catch (Exception ex) {
                    Log.Error(this, ex);
                }
            }
            try {
                return mightCache(normalizedPath, getFileResource(file, initialPath));
            } catch (IOException e) {
                FSTUtil.rethrow(e);
            }
        }
    }
    return super.getResource(initialPath);
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Element(org.jsoup.nodes.Element) FileResource(io.undertow.server.handlers.resource.FileResource) Resource(io.undertow.server.handlers.resource.Resource) IOException(java.io.IOException) TranspilerHook(org.nustaq.kontraktor.webapp.transpiler.TranspilerHook) File(java.io.File) IOException(java.io.IOException)

Example 19 with Resource

use of io.undertow.server.handlers.resource.Resource in project kontraktor by RuedigerMoeller.

the class Http4K method publishResourcePath.

public Http4K publishResourcePath(String hostName, String urlPath, int port, DynamicResourceManager man, boolean compress, Function<HttpServerExchange, Boolean> interceptor) {
    Pair<PathHandler, Undertow> server = getServer(port, hostName);
    ResourceHandler handler = new ResourceHandler(man);
    if (compress) {
        HttpHandler compressHandler = new EncodingHandler.Builder().build(new HashMap<>()).wrap(handler);
        HttpHandler httpHandler = new HttpHandler() {

            volatile byte[] zippedAggregate;

            @Override
            public void handleRequest(HttpServerExchange exchange) throws Exception {
                String requestPath = exchange.getRequestPath();
                if (exchange.getRequestMethod() == Methods.GET && !man.isDevMode() && (requestPath.equals("/") || requestPath.equals("") || requestPath.equals("/index.html"))) {
                    HeaderMap requestHeaders = exchange.getRequestHeaders();
                    String lastMod = requestHeaders.get(Headers.IF_MODIFIED_SINCE, 0);
                    if (lastMod != null) {
                        Date date = DateUtils.parseDate(lastMod);
                        if (date != null && date.getTime() >= man.getLastModified() - 2_000) {
                            exchange.setResponseCode(304);
                            exchange.endExchange();
                            return;
                        }
                    }
                    Resource cacheEntry = man.getCacheEntry("index.html");
                    if (cacheEntry instanceof DynamicResourceManager.MyResource) {
                        if (zippedAggregate == null) {
                            zippedAggregate = gzip(((DynamicResourceManager.MyResource) cacheEntry).getBytes());
                        }
                        exchange.setResponseCode(200);
                        exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, "gzip");
                        exchange.getResponseHeaders().put(Headers.LAST_MODIFIED, DateUtils.toDateString(man.getLastModifiedDate()));
                        Sender responseSender = exchange.getResponseSender();
                        responseSender.send(ByteBuffer.wrap(zippedAggregate));
                    } else {
                        zippedAggregate = null;
                        compressHandler.handleRequest(exchange);
                    }
                } else {
                    handler.handleRequest(exchange);
                }
            }
        };
        if (interceptor != null) {
            server.car().addPrefixPath(urlPath, httpExchange -> {
                boolean apply = interceptor.apply(httpExchange);
                if (!apply) {
                    httpHandler.handleRequest(httpExchange);
                }
            });
        } else {
            server.car().addPrefixPath(urlPath, httpHandler);
        }
    } else {
        if (interceptor != null) {
            server.car().addPrefixPath(urlPath, httpExchange -> {
                boolean apply = interceptor.apply(httpExchange);
                if (!apply) {
                    handler.handleRequest(httpExchange);
                }
            });
        } else {
            server.car().addPrefixPath(urlPath, handler);
        }
    }
    return this;
}
Also used : HttpHandler(io.undertow.server.HttpHandler) HashMap(java.util.HashMap) Resource(io.undertow.server.handlers.resource.Resource) PathHandler(io.undertow.server.handlers.PathHandler) ResourceHandler(io.undertow.server.handlers.resource.ResourceHandler) Date(java.util.Date) HttpServerExchange(io.undertow.server.HttpServerExchange) Sender(io.undertow.io.Sender) Undertow(io.undertow.Undertow)

Example 20 with Resource

use of io.undertow.server.handlers.resource.Resource in project undertow by undertow-io.

the class GetResourceTestCase method testSpecialCharacterInFileURL.

@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));
    }
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) Resource(io.undertow.server.handlers.resource.Resource) PathResourceManager(io.undertow.server.handlers.resource.PathResourceManager) Test(org.junit.Test)

Aggregations

Resource (io.undertow.server.handlers.resource.Resource)25 IOException (java.io.IOException)9 Path (java.nio.file.Path)7 Test (org.junit.Test)7 PathResourceManager (io.undertow.server.handlers.resource.PathResourceManager)4 ResourceManager (io.undertow.server.handlers.resource.ResourceManager)4 HttpServerExchange (io.undertow.server.HttpServerExchange)3 File (java.io.File)3 Sender (io.undertow.io.Sender)2 ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)2 UnitTest (io.undertow.testutils.category.UnitTest)2 OutputStream (java.io.OutputStream)2 Date (java.util.Date)2 VirtualFile (org.jboss.vfs.VirtualFile)2 Undertow (io.undertow.Undertow)1 IoCallback (io.undertow.io.IoCallback)1 HttpHandler (io.undertow.server.HttpHandler)1 PathHandler (io.undertow.server.handlers.PathHandler)1 FileResource (io.undertow.server.handlers.resource.FileResource)1 RangeAwareResource (io.undertow.server.handlers.resource.RangeAwareResource)1