Java Code Examples for io.undertow.server.handlers.resource.FileResourceManager

The following examples show how to use io.undertow.server.handlers.resource.FileResourceManager. These examples are extracted from open source projects. 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 Project: proteus   Source File: AssetsService.java    License: 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 2
Source Project: zooadmin   Source File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DeploymentInfo servletBuilder = Servlets.deployment()
            .setContextPath("/")
            .setClassLoader(Main.class.getClassLoader())
            .setDeploymentName("zooadmin.war")
            ;
    Integer port= PropUtil.getInt("port");
    String host=PropUtil.getString("host");
    String resource=PropUtil.getString("resource");
    FilterInfo jfinalFilter=new FilterInfo("jfinal",JFinalFilter.class);
    jfinalFilter.addInitParam("configClass","com.baicai.core.Config");
    servletBuilder.addFilter(jfinalFilter);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.REQUEST);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.FORWARD);
    servletBuilder.setResourceManager(new FileResourceManager(new File(resource), 1024));


    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect("/"))
           .addPrefixPath("/", manager.start());
    Undertow server = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(path)
            .build();
    // start server
    server.start();
    log.info("http://"+host+":"+port);
}
 
Example 3
Source Project: metamodel-membrane   Source File: WebServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void startServer(int port, boolean enableCors) throws Exception {
    final DeploymentInfo deployment = Servlets.deployment().setClassLoader(WebServer.class.getClassLoader());
    deployment.setContextPath("");
    deployment.setDeploymentName("membrane");
    deployment.addInitParameter("contextConfigLocation", "classpath:context/application-context.xml");
    deployment.setResourceManager(new FileResourceManager(new File("."), 0));
    deployment.addListener(Servlets.listener(ContextLoaderListener.class));
    deployment.addListener(Servlets.listener(RequestContextListener.class));
    deployment.addServlet(Servlets.servlet("dispatcher", DispatcherServlet.class).addMapping("/*")
            .addInitParam("contextConfigLocation", "classpath:context/dispatcher-servlet.xml"));
    deployment.addFilter(Servlets.filter(CharacterEncodingFilter.class).addInitParam("forceEncoding", "true")
            .addInitParam("encoding", "UTF-8"));

    final DeploymentManager manager = Servlets.defaultContainer().addDeployment(deployment);
    manager.deploy();

    final HttpHandler handler;
    if (enableCors) {
        CorsHandlers corsHandlers = new CorsHandlers();
        handler = corsHandlers.allowOrigin(manager.start());
    } else {
        handler = manager.start();
    }

    final Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0").setHandler(handler).build();
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // graceful shutdown of everything
            server.stop();
            try {
                manager.stop();
            } catch (ServletException e) {
            }
            manager.undeploy();
        }
    });
}
 
Example 4
@BeforeClass
public static void setUp() {
    if (server == null) {
        server = Undertow.builder()
                .addHttpListener(1234, "localhost")
                .setHandler(resource(new FileResourceManager(
                        new File("./src/test/resources/remotes"), 100)))
                .build();
        server.start();
    }
}
 
Example 5
Source Project: json-schema-validator   Source File: V7JsonSchemaTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() {
    if (server == null) {
        server = Undertow.builder()
                .addHttpListener(1234, "localhost")
                .setHandler(resource(new FileResourceManager(
                        new File("./src/test/resources/remotes"), 100)))
                .build();
        server.start();
    }
}
 
Example 6
Source Project: json-schema-validator   Source File: V4JsonSchemaTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() {
    if (server == null) {
        server = Undertow.builder()
                .addHttpListener(1234, "localhost")
                .setHandler(resource(new FileResourceManager(
                        new File("./src/test/resources/remotes"), 100)))
                .build();
        server.start();
    }
}
 
Example 7
Source Project: json-schema-validator   Source File: V6JsonSchemaTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() {
    if (server == null) {
        server = Undertow.builder()
                .addHttpListener(1234, "localhost")
                .setHandler(resource(new FileResourceManager(
                        new File("./src/test/resources/remotes"), 100)))
                .build();
        server.start();
    }
}
 
Example 8
Source Project: zooadmin   Source File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DeploymentInfo servletBuilder = Servlets.deployment()
            .setContextPath("/")
            .setClassLoader(Main.class.getClassLoader())
            .setDeploymentName("zooadmin.war")
            ;
    Integer port= PropUtil.getInt("port");
    String host=PropUtil.getString("host");
    String resource=PropUtil.getString("resource");
    FilterInfo jfinalFilter=new FilterInfo("jfinal",JFinalFilter.class);
    jfinalFilter.addInitParam("configClass","com.baicai.core.Config");
    servletBuilder.addFilter(jfinalFilter);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.REQUEST);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.FORWARD);
    servletBuilder.setResourceManager(new FileResourceManager(new File(resource), 1024));


    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect("/"))
           .addPrefixPath("/", manager.start());
    Undertow server = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(path)
            .build();
    // start server
    server.start();
    log.info("http://"+host+":"+port);
}
 
Example 9
public void setExtraResources(List extraResources) {
    List<ResourceManager> delegates = new ArrayList<>();
    for (Object o: extraResources) {
        File resource = File.class.cast(o);
        try {
            delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, false, "/"));
        } catch (IOException e) {
            LOGGER.warning("Unable to create cannonical file from {}. File skipped.", resource.getName(), e);
        }
    }
    delegates.addAll(this.delegates);
    this.delegates = delegates;
}
 
Example 10
Source Project: light   Source File: LightServer.java    License: Apache License 2.0 4 votes vote down vote up
static public void start() {
    // hosts and server configuration
    Map<String, Object> hostConfigMap = ServiceLocator.getInstance().getJsonMapConfig(ServiceLocator.HOST_CONFIG);
    Map<String, Object> serverConfigMap = ServiceLocator.getInstance().getJsonMapConfig(ServiceLocator.SERVER_CONFIG);

    OrientGraphFactory factory = ServiceLocator.getInstance().getFactory();
    // check if database exists, if not create it and init it.
    if(!factory.exists()) {
        try {
            OrientBaseGraph g = new OrientGraph(ServiceLocator.getInstance().getDbUrl());
            // database is auto created
            g.command(new OCommandSQL("alter database custom useLightweightEdges=true")).execute();
            g.command(new OCommandSQL("alter database DATETIMEFORMAT yyyy-MM-dd'T'HH:mm:ss.SSS")).execute();
            g.command(new OCommandSQL("alter database TIMEZONE UTC")).execute();
            OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
        } finally {
            // this also closes the OrientGraph instances created by the factory
            // Note that OrientGraphFactory does not implement Closeable
            factory.close();
        }
        InitDatabase.initDb();
        // load rule compileCache here
        AbstractRuleRule.loadCompileCache();
        // replay all the event to create database image.
        // TODO need to rethink replay as orientdb is used instead of Memory Image.
        replayEvent();
    } else {
        // load rule compileCache here
        AbstractRuleRule.loadCompileCache();
    }

    NameVirtualHostHandler virtualHostHandler = new NameVirtualHostHandler();
    Iterator<String> it = hostConfigMap.keySet().iterator();
    while (it.hasNext()) {
        String host = it.next();
        Map<String, String> hostPropMap = (Map<String, String>)hostConfigMap.get(host);
        String base = hostPropMap.get("base");
        String transferMinSize = hostPropMap.get("transferMinSize");
        virtualHostHandler
                .addHost(
                        host,
                        Handlers.predicates(
                            PredicatedHandlersParser.parse("not path-prefix('/images', '/assets', '/api') -> rewrite('/index.html')"
                            //PredicatedHandlersParser.parse("not path-suffix['.js', '.html', '.css'] -> rewrite['/index.html']"
                            //PredicatedHandlersParser.parse("path-prefix['/home', '/page', '/form'] -> rewrite['/index.html']"
                            , LightServer.class.getClassLoader()),
                                new PathHandler(resource(new FileResourceManager(
                                        new File(base), Integer
                                        .valueOf(transferMinSize))))
                                        .addPrefixPath("/api/rs",
                                                new EagerFormParsingHandler().setNext(
                                                        new RestHandler()))
                                        .addPrefixPath("/api/ws",
                                                websocket(new WebSocketHandler()))
                        ));
    }
    String ip = (String)serverConfigMap.get("ip");
    String port = (String)serverConfigMap.get("port");
    server = Undertow
            .builder()
            .addHttpListener(Integer.valueOf(port), ip)
            .setBufferSize(1024 * 16)
            .setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false)
            .setHandler(
                    Handlers.header(virtualHostHandler,
                            Headers.SERVER_STRING, "LIGHT"))
            .setWorkerThreads(200).build();
    server.start();

}