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

The following examples show how to use io.undertow.server.handlers.resource.ResourceHandler. 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: 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 #2
Source File: AssetsService.java    From proteus with Apache License 2.0 6 votes vote down vote up
public RoutingHandler get()
{
    RoutingHandler router = new RoutingHandler();
    final String assetsPath = serviceConfig.getString("path");
    final String assetsDirectoryName = serviceConfig.getString("dir");
    final Integer assetsCacheTime = serviceConfig.getInt("cache.time");
    final FileResourceManager fileResourceManager = new FileResourceManager(Paths.get(assetsDirectoryName).toFile());

    router.add(Methods.GET,
            assetsPath + "/*",
            io.undertow.Handlers.rewrite("regex('" + assetsPath + "/(.*)')",
                    "/$1",
                    getClass().getClassLoader(),
                    new ResourceHandler(fileResourceManager).setCachable(TruePredicate.instance()).setCacheTime(assetsCacheTime)));

    this.registeredEndpoints.add(EndpointInfo.builder()
            .withConsumes("*/*")
            .withProduces("*/*")
            .withPathTemplate(assetsPath)
            .withControllerName(this.getClass().getSimpleName())
            .withMethod(Methods.GET)
            .build());

    return router;
}
 
Example #3
Source File: SikulixServer.java    From SikuliX1 with MIT License 6 votes vote down vote up
private static Undertow createServer(int port, String ipAddr) {
  ControllerCommand controller = new ControllerCommand();
  TasksCommand tasks = new TasksCommand();
  ScriptsCommand scripts = new ScriptsCommand(tasks);
  GroupsCommand groups = new GroupsCommand(scripts);

  ResourceManager resourceManager = new ClassPathResourceManager(RunTime.class.getClassLoader(), "htdocs");
  ResourceHandler resource = new ResourceHandler(resourceManager, AbstractCommand.getFallbackHandler());
  resource.addWelcomeFiles("ControlBox.html");

  RoutingHandler commands = Handlers.routing()
          .addAll(controller.getRouting())
          .addAll(tasks.getRouting())
          .addAll(scripts.getRouting())
          .addAll(groups.getRouting())
          .setFallbackHandler(resource);
  CommandRootHttpHandler cmdRoot = new CommandRootHttpHandler(commands);
  cmdRoot.addExceptionHandler(Throwable.class, AbstractCommand.getExceptionHttpHandler());

  Undertow server = Undertow.builder()
          .addHttpListener(port, ipAddr)
          .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true)
          .setHandler(cmdRoot)
          .build();
  return server;
}
 
Example #4
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 #5
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 #6
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 #7
Source File: TaskIDE.java    From greycat with Apache License 2.0 5 votes vote down vote up
public static void attach(final WSServer server, final Graph graph) {
    server.addHandler("taskide", new ResourceHandler(new ClassPathResourceManager(TaskIDE.class.getClassLoader(), "taskide")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false));
    server.addHandler("actionregistry", new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
            Buffer builder = new HeapBuffer();
            builder.writeString("[");
            ActionRegistry registry = graph.actionRegistry();
            ActionDeclaration[] declarations = registry.declarations();
            for (int i = 0; i < declarations.length; i++) {
                ActionDeclaration declaration = declarations[i];
                if (i != 0) {
                    builder.writeString(",");
                }
                builder.writeString("{\"name\":");
                TaskHelper.serializeString(declaration.name(), builder, false);
                builder.writeString(",\"description\":");
                TaskHelper.serializeString(declaration.description(), builder, false);
                byte[] params = declaration.params();
                if (params != null) {
                    builder.writeString(",\"params\":[");
                    for (int j = 0; j < params.length; j++) {
                        if (j != 0) {
                            builder.writeString(",");
                        }
                        TaskHelper.serializeString(Type.typeName(params[j]), builder, false);
                    }
                    builder.writeString("]");
                }
                builder.writeString("}");
            }
            builder.writeString("]");
            httpServerExchange.getResponseHeaders().add(new HttpString("Access-Control-Allow-Origin"), "*");
            httpServerExchange.setStatusCode(StatusCodes.OK);
            httpServerExchange.getResponseSender().send(builder.toString());
        }
    });

}
 
Example #8
Source File: Server.java    From greycat with Apache License 2.0 5 votes vote down vote up
public Server() {
    Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0",
            Handlers.path()
                    .addPrefixPath("rpc", this)
                    .addPrefixPath("/", new ResourceHandler(new ClassPathResourceManager(Server.class.getClassLoader(), "static")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false))
    ).build();
    server.start();
    System.out.println("Server running at : 9077");
}
 
Example #9
Source File: ResourceHelpers.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Helper to add given PathResourceProviders to a PathHandler.
 *
 * @param pathResourceProviders List of instances of classes implementing PathResourceProvider.
 * @param pathHandler The handler that will have these handlers added to it.
 */
public static void addProvidersToPathHandler(PathResourceProvider[] pathResourceProviders, PathHandler pathHandler) {
    if (pathResourceProviders != null && pathResourceProviders.length > 0) {
        for (PathResourceProvider pathResourceProvider : pathResourceProviders) {
            if (pathResourceProvider.isPrefixPath()) {
                pathHandler.addPrefixPath(pathResourceProvider.getPath(), new ResourceHandler(pathResourceProvider.getResourceManager()));
            } else {
                pathHandler.addExactPath(pathResourceProvider.getPath(), new ResourceHandler(pathResourceProvider.getResourceManager()));
            }
        }
    }
}
 
Example #10
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 #11
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 #12
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 #13
Source File: Application.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Create routes for WebSockets ServerSentEvent and Resource files
 */
private static void createRoutes() {
    pathHandler = new PathHandler(getRoutingHandler());
    
    Router.getWebSocketRoutes().forEach((WebSocketRoute webSocketRoute) -> 
        pathHandler.addExactPath(webSocketRoute.getUrl(),
                Handlers.websocket(getInstance(WebSocketHandler.class)
                        .withControllerClass(webSocketRoute.getControllerClass())
                        .withAuthentication(webSocketRoute.hasAuthentication())))
    );
    
    Router.getServerSentEventRoutes().forEach((ServerSentEventRoute serverSentEventRoute) ->
        pathHandler.addExactPath(serverSentEventRoute.getUrl(),
                Handlers.serverSentEvents(getInstance(ServerSentEventHandler.class)
                        .withAuthentication(serverSentEventRoute.hasAuthentication())))
    );
    
    Router.getPathRoutes().forEach((PathRoute pathRoute) ->
        pathHandler.addPrefixPath(pathRoute.getUrl(),
                new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + pathRoute.getUrl())))
    );
    
    Config config = getInstance(Config.class);
    if (config.isApplicationAdminEnable()) {
        pathHandler.addPrefixPath("/@admin/assets/", new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), "templates/@admin/assets/")));            
    }
}
 
Example #14
Source File: Server.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static HttpHandler createStaticResourceHandler() {
    final ResourceManager staticResources =
            new ClassPathResourceManager(Server.class.getClassLoader(), "static");
    // Cache tuning is copied from Undertow unit tests.
    final ResourceManager cachedResources =
            new CachingResourceManager(100, 65536,
                                       new DirectBufferCache(1024, 10, 10480),
                                       staticResources,
                                       (int)Duration.ofDays(1).getSeconds());
    final ResourceHandler resourceHandler = new ResourceHandler(cachedResources);
    resourceHandler.setWelcomeFiles("index.html");
    return resourceHandler;
}
 
Example #15
Source File: WSSharedServerTest.java    From greycat with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    final Graph graph = new GraphBuilder()
            .withMemorySize(10000)
            .build();
    graph.connect(new Callback<Boolean>() {
        @Override
        public void on(Boolean connectResult) {
            WSSharedServer graphServer = new WSSharedServer(graph, 8050);
            graphServer.addHandler("hello", new ResourceHandler(new ClassPathResourceManager(this.getClass().getClassLoader(), "hello")).addWelcomeFiles("index.html").setDirectoryListingEnabled(true));
            graphServer.start();
            System.out.println("Connected!");


            Node root = graph.newNode(0, 0);
            root.set("name", Type.STRING, "root");

            Node n0 = graph.newNode(0, 0);
            n0.set("name", Type.STRING, "n0");

            Node n1 = graph.newNode(0, 0);
            n1.set("name", Type.STRING, "n0");

            root.addToRelation("children", n0);
            root.addToRelation("children", n1);

            graph.declareIndex(0, "nodes", new Callback<NodeIndex>() {
                @Override
                public void on(NodeIndex indexNode) {
                    indexNode.update(root);
                    System.out.println(indexNode.toString());
                    StateChunk chunk = (StateChunk) graph.space().get(((BaseNode) indexNode)._index_stateChunk);
                    Buffer buffer = graph.newBuffer();
                    chunk.save(buffer);

                    System.out.println(new String(buffer.data()));
                    System.out.println(chunk.index());
                }
            }, "name");
        }
    });
}
 
Example #16
Source File: Application.java    From mangooio with Apache License 2.0 4 votes vote down vote up
private static RoutingHandler getRoutingHandler() {
    final RoutingHandler routingHandler = Handlers.routing();
    routingHandler.setFallbackHandler(Application.getInstance(FallbackHandler.class));
    
    Config config = getInstance(Config.class);
    if (config.isApplicationAdminEnable()) {
        Bind.controller(AdminController.class)
            .withRoutes(
                    On.get().to("/@admin").respondeWith("index"),
                    On.get().to("/@admin/login").respondeWith("login"),
                    On.get().to("/@admin/twofactor").respondeWith("twofactor"),
                    On.get().to("/@admin/scheduler").respondeWith("scheduler"),
                    On.get().to("/@admin/logger").respondeWith("logger"),
                    On.get().to("/@admin/routes").respondeWith("routes"),
                    On.get().to("/@admin/tools").respondeWith("tools"),
                    On.get().to("/@admin/scheduler/execute/{name}").respondeWith("execute"),
                    On.get().to("/@admin/scheduler/state/{name}").respondeWith("state"),   
                    On.get().to("/@admin/logout").respondeWith("logout"),
                    On.post().to("/@admin/authenticate").respondeWith("authenticate"),
                    On.post().to("/@admin/verify").respondeWith("verify"),
                    On.post().to("/@admin/logger/ajax").respondeWith("loggerajax"),
                    On.post().to("/@admin/tools/ajax").respondeWith("toolsajax")
             );
    }

    Router.getRequestRoutes().forEach((RequestRoute requestRoute) -> {
        DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class)
                .dispatch(requestRoute.getControllerClass(), requestRoute.getControllerMethod())
                .isBlocking(requestRoute.isBlocking())
                .withBasicAuthentication(requestRoute.getUsername(), requestRoute.getPassword())
                .withAuthentication(requestRoute.hasAuthentication())
                .withAuthorization(requestRoute.hasAuthorization())
                .withLimit(requestRoute.getLimit());
        
        routingHandler.add(requestRoute.getMethod().toString(), requestRoute.getUrl(), dispatcherHandler);  
    });
    
    ResourceHandler resourceHandler = Handlers.resource(new ClassPathResourceManager(
            Thread.currentThread().getContextClassLoader(),
            Default.FILES_FOLDER.toString() + '/'));
    
    Router.getFileRoutes().forEach((FileRoute fileRoute) -> routingHandler.add(Methods.GET, fileRoute.getUrl(), resourceHandler));
    
    return routingHandler;
}
 
Example #17
Source File: Handlers.java    From quarkus-http with Apache License 2.0 2 votes vote down vote up
/**
 * Return a new resource handler
 *
 * @param resourceManager The resource manager to use
 * @return A new resource handler
 */
public static ResourceHandler resource(final ResourceManager resourceManager) {
    return new ResourceHandler(resourceManager).setDirectoryListingEnabled(false);
}
 
Example #18
Source File: Handlers.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Return a new resource handler
 *
 * @param resourceManager The resource manager to use
 * @return A new resource handler
 */
public static ResourceHandler resource(final ResourceManager resourceManager) {
    return new ResourceHandler(resourceManager).setDirectoryListingEnabled(false);
}