io.vertx.ext.web.handler.StaticHandler Java Examples

The following examples show how to use io.vertx.ext.web.handler.StaticHandler. 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: HttpApplication.java    From jkube with Eclipse Public License 2.0 7 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);

    router.get("/api/greeting").handler(this::greeting);
    router.get("/*").handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(
                    // Retrieve the port from the configuration, default to 8080.
                    config().getInteger("http.port", 8080), ar -> {
                        if (ar.succeeded()) {
                            System.out.println("Server starter on port " + ar.result().actualPort());
                        }
                        future.handle(ar.mapEmpty());
                    });

}
 
Example #2
Source File: VertxNubes.java    From nubes with Apache License 2.0 6 votes vote down vote up
private void setUpRouter(Router paramRouter) {
  router = paramRouter;
  router.route().failureHandler(failureHandler);
  if (locResolver != null) {
    locResolver.getAvailableLocales().forEach(this::loadResourceBundle);
    if (locResolver.getDefaultLocale() != null) {
      loadResourceBundle(locResolver.getDefaultLocale());
    }
  }
  if (config.getAuthProvider() != null) {
    registerAnnotationProcessor(Auth.class, new AuthProcessorFactory());
  }
  new RouteFactory(router, config).createHandlers();
  new SocketFactory(router, config).createHandlers();
  new EventBusBridgeFactory(router, config).createHandlers();
  StaticHandler staticHandler;
  final String webroot = config.getWebroot();
  if (webroot != null) {
    staticHandler = StaticHandler.create(webroot);
  } else {
    staticHandler = StaticHandler.create();
  }
  router.route(config.getAssetsPath() + "/*").handler(staticHandler);
}
 
Example #3
Source File: MainVerticle.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    final Router router = Router.router(vertx);

    final ThymeleafTemplateEngine templateEngine = ThymeleafTemplateEngine.create();

    router.get("/assets*").handler(StaticHandler.create());

    router.get("/").handler(ctx -> {
        ctx.put("welcome", "Hello vert.x!");

        templateEngine.render(ctx, "templates/index.html", res -> {
            if (res.succeeded()) {
                ctx.response().end(res.result());
            } else {
                ctx.fail(res.cause());
            }
        });

    });

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
 
Example #4
Source File: MainModule.java    From cassandra-sidecar with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
public Router vertxRouter(Vertx vertx)
{
    Router router = Router.router(vertx);
    router.route().handler(LoggerHandler.create());

    // Static web assets for Swagger
    StaticHandler swaggerStatic = StaticHandler.create("META-INF/resources/webjars/swagger-ui");
    router.route().path("/static/swagger-ui/*").handler(swaggerStatic);

    // Docs index.html page
    StaticHandler docs = StaticHandler.create("docs");
    router.route().path("/docs/*").handler(docs);

    return router;
}
 
Example #5
Source File: DFWebUI.java    From df_data_service with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {

    // Create a router object for web ui
    Router routerWeb = Router.router(vertx);

    // Bind new web ui
    routerWeb.route("/dfa/*").handler(StaticHandler.create("dfa").setCachingEnabled(false));
    // Bind api doc
    routerWeb.route("/api/*").handler(StaticHandler.create("apidoc").setCachingEnabled(true));
    // Bind landing page
    routerWeb.route("/*").handler(StaticHandler.create("landing").setCachingEnabled(true));

    // Create the HTTP server to serve the web ui
    vertx.createHttpServer().requestHandler(routerWeb::accept)
            .listen(config().getInteger("http.port.df.processor", 8000));

    try {
        LOG.info("DataFibers Welcome You @ http://" + InetAddress.getLocalHost().getHostAddress() + ":" +
                config().getInteger("http.port.df.processor", 8000));
    } catch (UnknownHostException e) {
        LOG.error(DFAPIMessage.logResponseMessage(9019,
                "NetworkHostException - "  + e.getCause()));
    }
}
 
Example #6
Source File: HttpApplication.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);

    router.get("/api/greeting").handler(this::greeting);
    router.get("/*").handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(
                    // Retrieve the port from the configuration, default to 8080.
                    config().getInteger("http.port", 8080), ar -> {
                        if (ar.succeeded()) {
                            System.out.println("Server starter on port " + ar.result().actualPort());
                        }
                        future.handle(ar.mapEmpty());
                    });

}
 
Example #7
Source File: HttpApplication.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);

    router.get("/api/greeting").handler(this::greeting);
    router.get("/*").handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(
                    // Retrieve the port from the configuration, default to 8080.
                    config().getInteger("http.port", 8080), ar -> {
                        if (ar.succeeded()) {
                            System.out.println("Server starter on port " + ar.result().actualPort());
                        }
                        future.handle(ar.mapEmpty());
                    });

}
 
Example #8
Source File: HttpApplication.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);

    router.get("/api/greeting").handler(this::greeting);
    router.get("/*").handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(
                    // Retrieve the port from the configuration, default to 8080.
                    config().getInteger("http.port", 8080), ar -> {
                        if (ar.succeeded()) {
                            System.out.println("Server starter on port " + ar.result().actualPort());
                        }
                        future.handle(ar.mapEmpty());
                    });

}
 
Example #9
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void startSecuredFileServer() throws InterruptedException {
  Router router = Router.router(vertx);
  router.route()
    .handler((RoutingContext ctx) -> {
      if (ctx.request().getHeader("Authorization") == null) ctx.fail(403);
      else ctx.next();
    })
    .handler(StaticHandler.create("src/test/resources"));
  CountDownLatch latch = new CountDownLatch(1);
  securedFileServer = vertx.createHttpServer(new HttpServerOptions().setPort(8081))
    .requestHandler(router).listen(onSuccess(res -> latch.countDown()));
  awaitLatch(latch);
}
 
Example #10
Source File: MyVerticle.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    Router router = Router.router(vertx);
    router.get("/*").handler(StaticHandler.create().setCachingEnabled(false));

    vertx.createHttpServer()
        .requestHandler(router::accept)
        .listen(8080, ar -> System.out.println("Server started on port: " + ar.result().actualPort()));
}
 
Example #11
Source File: SmallRyeGraphQLRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Handler<RoutingContext> uiHandler(String graphqlUiFinalDestination, String graphqlUiPath) {

        Handler<RoutingContext> handler = new ThreadLocalHandler(new Supplier<Handler<RoutingContext>>() {
            @Override
            public Handler<RoutingContext> get() {
                return StaticHandler.create().setAllowRootFileSystemAccess(true)
                        .setWebRoot(graphqlUiFinalDestination)
                        .setDefaultContentEncoding("UTF-8");
            }
        });

        return new Handler<RoutingContext>() {
            @Override
            public void handle(RoutingContext event) {
                if (event.normalisedPath().length() == graphqlUiPath.length()) {

                    event.response().setStatusCode(302);
                    event.response().headers().set(HttpHeaders.LOCATION, graphqlUiPath + "/");
                    event.response().end();
                    return;
                } else if (event.normalisedPath().length() == graphqlUiPath.length() + 1) {
                    event.reroute(graphqlUiPath + "/index.html");
                    return;
                }

                handler.handle(event);
            }
        };
    }
 
Example #12
Source File: ShoppingUIVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  Router router = Router.router(vertx);

  // event bus bridge
  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  router.route("/eventbus/*").handler(sockJSHandler);

  // static content
  router.route("/*").handler(StaticHandler.create());

  // get HTTP host and port from configuration, or use default value
  String host = config().getString("shopping.ui.http.address", "0.0.0.0");
  int port = config().getInteger("shopping.ui.http.port", 8080);

  // create HTTP server
  vertx.createHttpServer()
    .requestHandler(router::accept)
    .listen(port, ar -> {
      if (ar.succeeded()) {
        future.complete();
        logger.info(String.format("Shopping UI service is running at %d", port));
      } else {
        future.fail(ar.cause());
      }
    });
}
 
Example #13
Source File: VertxUI.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a VertXUI static-handler at the target folder and translate the given
 * class from java to javascript. Give url:null for only translating.
 * 
 * @param classs
 *            the class that will be compiled to javascript
 * @param urlWithoutAsterix
 *            the url that will be served, but without asterix for the static
 *            file handler; set to null if you only want compiling.
 * @param debug
 *            debug (true) or production (false)
 * @param withHtml
 *            with a generated .html file or not (advisable)
 * @return the static file handler.
 */
public static Handler<RoutingContext> with(Class<?> classs, String urlWithoutAsterix, boolean debug,
		boolean withHtml) {

	// Look for a sourcefolder. If none, we are in production so we don't do
	// anything at all.
	String clientFile = classs.getName().replace(".", "/") + ".java";
	Stream.of("src", "src/main", "src/main/java", "src/test", "src/test/java", folderSource).forEach(location -> {
		if (location != null && new File(location + "/" + clientFile).exists()) {
			folderSource = location;
		}
	});
	log.fine("source folder = " + new File(folderSource).getAbsolutePath());
	if (folderSource == null) { // production
		if (debug) {
			throw new IllegalArgumentException(
					"Sourcefolder not found but debug is still true, you didn't set the 'working directory' of your "
							+ "IntelliJ-run to the root of the project? Or did you want to run with debug=false instead?");
		}
		log.info("Production mode: all OK, no source folder found, not translating from java to javascript.");
	} else { // inside IDE
		VertxUI translated = new VertxUI(classs, debug, withHtml);

		if (FigWheelyServer.started) {
			String clientFolder = (folderSource + "/" + classs.getName()).replace(".", "/");
			clientFolder = clientFolder.substring(0, clientFolder.lastIndexOf("client") + 6);
			FigWheelyServer.addWatchable(urlWithoutAsterix + "a/a.nocache.js", clientFolder, translated);
		}
	}
	if (urlWithoutAsterix != null) { // only serve files when a target-URL is given
		return StaticHandler.create(VertxUI.getTargetFolder(debug)).setCachingEnabled(false)
				.setDefaultContentEncoding(VertxUI.charset);
	} else {
		return null;
	}
}
 
Example #14
Source File: FigWheelyServer.java    From vertxui with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Serve the root folder as static handler, but with notifications to the
 * browser if folder change. Does not work when figwheely wasn't started before,
 * so there is no performance loss if you leave this on.
 * 
 * @param root              the root folder
 * @param urlWithoutAsterix the url but without the asterix at the end
 * @return a static file handler with figwheely support
 */
public static Handler<RoutingContext> staticHandler(String root, String urlWithoutAsterix) {
	// log.info("creating figwheely static handler, started=" +
	// FigWheely.started);
	if (FigWheelyServer.started) {
		FigWheelyServer.addFromStaticHandler(Vertx.factory.context().owner().fileSystem(), root, urlWithoutAsterix,
				root);
	}

	return StaticHandler.create(root).setCachingEnabled(false).setDefaultContentEncoding(VertxUI.charset);
}
 
Example #15
Source File: HystrixDashboardVerticle.java    From standalone-hystrix-dashboard with MIT License 5 votes vote down vote up
/**
 * Create the routes for dashboard app
 *
 * @return A {@link Router} with all the routes needed for the app.
 */
private Router createRoutes() {
  final Router hystrixRouter = Router.router(vertx);

  // proxy stream handler
  hystrixRouter.get("/proxy.stream").handler(HystrixDashboardProxyConnectionHandler.create());

  // proxy the eureka apps listing
  hystrixRouter.get("/eureka").handler(HystrixDashboardProxyEurekaAppsListingHandler.create(vertx));

  hystrixRouter.route("/*")
               .handler(StaticHandler.create()
                                     .setCachingEnabled(true)
                                     .setCacheEntryTimeout(1000L * 60 * 60 * 24));

  final Router mainRouter = Router.router(vertx);

  // if send a route without the trailing '/' some problems will occur, so i redirect the guy using the trailing '/'
  mainRouter.route("/hystrix-dashboard")
            .handler(context -> {
              if (context.request().path().endsWith("/")) {
                context.next();
              } else {
                context.response()
                       .setStatusCode(HttpResponseStatus.MOVED_PERMANENTLY.code())
                       .putHeader(HttpHeaders.LOCATION, "/hystrix-dashboard/")
                       .end();
              }
            });

  mainRouter.mountSubRouter("/hystrix-dashboard", hystrixRouter);
  return mainRouter;
}
 
Example #16
Source File: HttpServer.java    From Lealone-Plugins with Apache License 2.0 5 votes vote down vote up
private void setStaticHandler(Router router) {
    for (String root : webRoot.split(",", -1)) {
        root = root.trim();
        if (root.isEmpty())
            continue;
        StaticHandler sh = StaticHandler.create(root);
        sh.setCachingEnabled(false);
        router.route("/*").handler(sh);
    }
}
 
Example #17
Source File: MyFirstVerticle.java    From my-vertx-first-app with Apache License 2.0 5 votes vote down vote up
private void startWebApp(Handler<AsyncResult<HttpServer>> next) {
  // Create a router object.
  Router router = Router.router(vertx);

  // Bind "/" to our hello message.
  router.route("/").handler(routingContext -> {
    HttpServerResponse response = routingContext.response();
    response
        .putHeader("content-type", "text/html")
        .end("<h1>Hello from my first Vert.x 3 application</h1>");
  });

  router.route("/assets/*").handler(StaticHandler.create("assets"));

  router.get("/api/whiskies").handler(this::getAll);
  router.route("/api/whiskies*").handler(BodyHandler.create());
  router.post("/api/whiskies").handler(this::addOne);
  router.get("/api/whiskies/:id").handler(this::getOne);
  router.put("/api/whiskies/:id").handler(this::updateOne);
  router.delete("/api/whiskies/:id").handler(this::deleteOne);


  // Create the HTTP server and pass the "accept" method to the request handler.
  vertx
      .createHttpServer()
      .requestHandler(router::accept)
      .listen(
          // Retrieve the port from the configuration,
          // default to 8080.
          config().getInteger("http.port", 8080),
          next::handle
      );
}
 
Example #18
Source File: SwaggerUI.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Override
public void registerWithRouter(Router router) {
  StaticHandler staticHandler = StaticHandler.create();
  staticHandler.setWebRoot("META-INF/resources/webjars");
  router.route("/static/*").handler(staticHandler);

  // Disable caching so you don't need to clear cache everytime yaml changes.
  StaticHandler swaggerHandler =
      StaticHandler.create().setWebRoot("webroot/swagger").setCachingEnabled(false);
  router.route("/doc/*").handler(swaggerHandler);
}
 
Example #19
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public StaticHandler setMaxAgeSeconds(long maxAgeSeconds) {
  if (maxAgeSeconds < 0) {
    throw new IllegalArgumentException("timeout must be >= 0");
  }
  this.maxAgeSeconds = maxAgeSeconds;
  return this;
}
 
Example #20
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public StaticHandler setIndexPage(String indexPage) {
  Objects.requireNonNull(indexPage);
  if (!indexPage.startsWith("/")) {
    indexPage = "/" + indexPage;
  }
  this.indexPage = indexPage;
  return this;
}
 
Example #21
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public StaticHandler setHttp2PushMapping(List<Http2PushMapping> http2PushMap) {
  if (http2PushMap != null) {
    this.http2PushMappings = new ArrayList<>(http2PushMap);
  }
  return this;
}
 
Example #22
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public StaticHandler skipCompressionForMediaTypes(Set<String> mediaTypes) {
  if (mediaTypes != null) {
    this.compressedMediaTypes = new HashSet<>(mediaTypes);
  }
  return this;
}
 
Example #23
Source File: StaticHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public StaticHandler skipCompressionForSuffixes(Set<String> fileSuffixes) {
  if (fileSuffixes != null) {
    this.compressedFileSuffixes = new HashSet<>(fileSuffixes);
  }
  return this;
}
 
Example #24
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Future<Void> startFileServer(Vertx vertx, VertxTestContext testContext) {
  Router router = Router.router(vertx);
  router.route().handler(StaticHandler.create("src/test/resources"));
  return testContext.assertComplete(
    vertx.createHttpServer()
      .requestHandler(router)
      .listen(9001)
      .mapEmpty()
  );
}
 
Example #25
Source File: RouterFactoryIntegrationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Future<Void> startSecuredFileServer(Vertx vertx, VertxTestContext testContext) {
  Router router = Router.router(vertx);
  router.route()
    .handler((RoutingContext ctx) -> {
      if (ctx.request().getHeader("Authorization") == null) ctx.fail(HttpResponseStatus.FORBIDDEN.code());
      else ctx.next();
    })
    .handler(StaticHandler.create("src/test/resources"));
  return testContext.assertComplete(
    vertx.createHttpServer()
      .requestHandler(router)
      .listen(9001)
      .mapEmpty()
  );
}
 
Example #26
Source File: OpenAPIHolderTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Future<Void> startSchemaServer(Vertx vertx, String path, List<Handler<RoutingContext>> authHandlers, int port) {
  Router r = Router.router(vertx);

  Route route = r.route("/*")
      .produces("application/yaml");
  authHandlers.forEach(route::handler);
  route.handler(StaticHandler.create(path).setCachingEnabled(true));

  schemaServer = vertx.createHttpServer(new HttpServerOptions().setPort(port))
      .requestHandler(r);
  return schemaServer.listen().mapEmpty();
}
 
Example #27
Source File: RouterFactoryBodyValidationIntegrationTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Future<Void> startFileServer(Vertx vertx, VertxTestContext testContext) {
  Router router = Router.router(vertx);
  router.route().handler(StaticHandler.create("./src/test/resources/specs/schemas"));
  return testContext.assertComplete(
    vertx.createHttpServer()
      .requestHandler(router)
      .listen(8081)
      .mapEmpty()
  );
}
 
Example #28
Source File: OpenAPI3SchemasTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void startSchemaServer() throws Exception {
  Router r = Router.router(vertx);
  r.route().handler(StaticHandler.create("./src/test/resources/swaggers/schemas"));
  CountDownLatch latch = new CountDownLatch(1);
  schemaServer = vertx.createHttpServer(new HttpServerOptions().setPort(8081))
    .requestHandler(r).listen(onSuccess(res -> latch.countDown()));
  awaitLatch(latch);
}
 
Example #29
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void startFileServer() throws InterruptedException {
  Router router = Router.router(vertx);
  router.route().handler(StaticHandler.create("src/test/resources"));
  CountDownLatch latch = new CountDownLatch(1);
  fileServer = vertx.createHttpServer(new HttpServerOptions().setPort(8081))
    .requestHandler(router).listen(onSuccess(res -> latch.countDown()));
  awaitLatch(latch);
}
 
Example #30
Source File: WebVerticle.java    From djl-demo with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	HttpServer server = vertx.createHttpServer();
	Router router = Router.router(vertx);
	router.route().handler(BodyHandler.create());

	SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
	BridgeOptions options = new BridgeOptions();

	options.addInboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER_REQUEST));

	options.addOutboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER));

	// Event bus
	router.mountSubRouter("/api/eventbus", sockJSHandler.bridge(options));

	// Static content (UI)
	router.route("/*").handler(StaticHandler.create());
	router.route("/*").handler(rc -> {
		if (!rc.currentRoute().getPath().startsWith("/api")) {
			rc.reroute("/index.html");
		}
	});

	server.requestHandler(router).listen(port, http -> {
		if (http.succeeded()) {
			LOGGER.info("HTTP server started: http://localhost:{0}", String.valueOf(port));
		} else {
			LOGGER.info("HTTP server failed on port {0}", String.valueOf(port));
		}
	});
}