io.vertx.ext.web.Route Java Examples

The following examples show how to use io.vertx.ext.web.Route. 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: RestRsRouteInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
private static void initHttpOptions(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Route route = router.options(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value()
                    + OPTIONS.class.getName()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(
            methodId,
            vxmsShared,
            service,
            restMethod,
            route,
            errorMethodStream,
            consumes,
            OPTIONS.class);
}
 
Example #2
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
private static void initHttpPut(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Route route = router.put(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value()
                    + PUT.class.getName()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(
            methodId, vxmsShared, service, restMethod, route, errorMethodStream, consumes, PUT.class);
}
 
Example #3
Source File: BlockingHandlerDecorator.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  Route currentRoute = context.currentRoute();
  context.vertx().executeBlocking(fut -> {
    decoratedHandler.handle(new RoutingContextDecorator(currentRoute, context));
    fut.complete();
  }, ordered, res -> {
    if (res.failed()) {
      // This means an exception was thrown from the blocking handler
      context.fail(res.cause());
    }
  });
}
 
Example #4
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 初始化流量限制
 * 
 * @param api
 * @param route
 */
public void initApiLimit(VxApis api, Route route) {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	// 添加consumes
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	if (api.getLimitUnit() != null) {
		if (api.getApiLimit() <= -1 && api.getIpLimit() <= -1) {
			api.setLimitUnit(null);
		}
	}
	// 流量限制处理处理器
	VxApiRouteHandlerApiLimit apiLimitHandler = VxApiRouteHandlerApiLimit.create(api);
	route.handler(apiLimitHandler);
}
 
Example #5
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 初始化异常Handler
 * 
 * @param api
 * @param route
 */
public void initExceptionHanlder(VxApis api, Route route) {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	route.failureHandler(rct -> {
		rct.response().putHeader(SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(CONTENT_TYPE, api.getContentType())
				.setStatusCode(api.getResult().getFailureStatus()).end(api.getResult().getFailureExample());
		VxApiTrackInfos infos = new VxApiTrackInfos(appName, api.getApiName());
		if (rct.failure() != null) {
			infos.setErrMsg(rct.failure().getMessage());
			infos.setErrStackTrace(rct.failure().getStackTrace());
		} else {
			infos.setErrMsg("没有进一步信息 failure 为 null");
		}
		vertx.eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_ERROR, infos.toJson());
	});
}
 
Example #6
Source File: SmallRyeMetricsProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
@Record(STATIC_INIT)
void createRoute(BuildProducer<RouteBuildItem> routes,
        SmallRyeMetricsRecorder recorder,
        HttpRootPathBuildItem httpRoot,
        BuildProducer<NotFoundPageDisplayableEndpointBuildItem> displayableEndpoints,
        LaunchModeBuildItem launchModeBuildItem) {
    Function<Router, Route> route = recorder.route(metrics.path + (metrics.path.endsWith("/") ? "*" : "/*"));
    Function<Router, Route> slash = recorder.route(metrics.path);

    // add metrics endpoint for not found display in dev or test mode
    if (launchModeBuildItem.getLaunchMode().isDevOrTest()) {
        displayableEndpoints.produce(new NotFoundPageDisplayableEndpointBuildItem(metrics.path));
    }
    routes.produce(new RouteBuildItem(route, recorder.handler(httpRoot.adjustPath(metrics.path)), HandlerType.BLOCKING));
    routes.produce(new RouteBuildItem(slash, recorder.handler(httpRoot.adjustPath(metrics.path)), HandlerType.BLOCKING));
}
 
Example #7
Source File: OpenAPI3RouterFactoryTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Test
public void pathResolverShouldNotCreateRegex() throws Exception {
  CountDownLatch latch = new CountDownLatch(1);
  OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/produces_consumes_test.yaml",
    openAPI3RouterFactoryAsyncResult -> {
      routerFactory = openAPI3RouterFactoryAsyncResult.result();
      routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));

      routerFactory.addHandlerByOperationId("consumesTest", routingContext ->
        routingContext
          .response()
          .setStatusCode(200)
          .setStatusMessage("OK")
      );

      latch.countDown();
    });
  awaitLatch(latch);

  router = routerFactory.getRouter();

  assertTrue(router.getRoutes().stream().map(Route::getPath).anyMatch("/consumesTest"::equals));
}
 
Example #8
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
protected static void initHttpGet(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Route route = router.get(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value()
                    + GET.class.getName()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(
            methodId, vxmsShared, service, restMethod, route, errorMethodStream, consumes, GET.class);
}
 
Example #9
Source File: RouterImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private String getAndCheckRoutePath(RoutingContext routingContext) {
  final RoutingContextImplBase ctx = (RoutingContextImplBase) routingContext;
  final Route route = ctx.currentRoute();

  if (!route.isRegexPath()) {
    if (route.getPath() == null) {
      // null route
      return "/";
    } else {
      // static route e.g.: /foo
      return route.getPath();
    }
  }
  // regex
  if (ctx.matchRest != -1) {
    if (ctx.matchNormalized) {
      return ctx.normalizedPath().substring(0, ctx.matchRest);
    } else {
      return ctx.request().path().substring(0, ctx.matchRest);
    }
  } else {
    // failure did not match
    throw new IllegalStateException("Sub routers must be mounted on paths (constant or parameterized)");
  }
}
 
Example #10
Source File: RouteManager.java    From festival with Apache License 2.0 6 votes vote down vote up
private void handleMapping(RouteAttribute routeAttribute, Route route) {

        if (log.isInfoEnabled()) {
            log.info("register {} mapping path:{}!", routeAttribute.getHttpMethod().name(), routeAttribute.getUrl());
        }

        Filter invoker = (routingContext, filterChain) -> routeAttribute.getContextHandler().handle(routingContext);

        route.handler(routingContext -> {
            routingContext.data().put(ROUTE_ATTRIBETE_KEY, routeAttribute);
            try {
                filterChainFactory.getFilterChain(invoker)
                        .doFilter(routingContext);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                routingContext.fail(500, e);
            }
        });
    }
 
Example #11
Source File: RoutingVerticle.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
protected void buildHandlers(Route route, RouteConfig config, Environment environment) {
    String handler = config.getHandlers().get(0);
    String[] splitsHandler = StringUtils.splitByWholeSeparator(handler, SERVICE_SEPARATOR);

    if (splitsHandler.length != 2) {
        throw new IllegalArgumentException("handler error");
    }

    String serviceKey = splitsHandler[0];
    String methodName = splitsHandler[1];
    Object service = serviceMap.get(serviceKey);

    if (service == null) {
        throw new IllegalArgumentException(String.format("service %s not exist", serviceKey));
    }

    Map<String, Class<?>> params = ASMUtils.getParams(service.getClass(), methodName);
    ConvertInvoker handlerInvoker = new ConvertInvoker(service, methodName, params);
    route.handler(new RestHandler(handlerInvoker));
}
 
Example #12
Source File: RuntimeTransport.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
private void logApiMountEvent(ServiceWrapper service, String serviceApiPath, Router router) {
  List<Route> serviceRoutes = router.getRoutes();
  if (serviceRoutes.isEmpty()) {
    // The service has no API: nothing to log
    return;
  }

  String serviceName = service.getName();
  int port = server.getActualPort().orElse(0);
  // Currently the API is mounted on *all* interfaces, see VertxServer#start
  logger.info("Service {} API is mounted at <host>::{}{}", serviceName, port, serviceApiPath);

  // Log the full path to one of the service endpoint
  serviceRoutes.stream()
      .map(Route::getPath)
      .filter(Objects::nonNull) // null routes are possible in failure handlers, for instance
      .findAny()
      .ifPresent(someRoute ->
          logger.info("    E.g.: http://127.0.0.1:{}{}", port, serviceApiPath + someRoute)
      );
}
 
Example #13
Source File: RestRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initHttpOperation(
        String methodId, VxmsShared vxmsShared, Route route, MethodDescriptor descriptor) {

    initHttpRoute(
            methodId,
            vxmsShared,
            descriptor.method,
            descriptor.consumes,
            descriptor.errorMethod,
            route);
}
 
Example #14
Source File: RestRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
protected static void initHttpGet(
        VxmsShared vxmsShared, Router router, MethodDescriptor descriptor) {
    final Route route = router.get(URIUtil.cleanPath(descriptor.path));
    final Context context = getContext(vxmsShared);
    final String methodId =
            descriptor.path
                    + HttpMethod.GET.name()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(methodId, vxmsShared, route, descriptor);
}
 
Example #15
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Function<Router, Route> route(String name) {
    return new Function<Router, Route>() {
        @Override
        public Route apply(Router router) {
            return router.route(name);
        }
    };
}
 
Example #16
Source File: RouteBuildItem.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Deprecated
public RouteBuildItem(Function<Router, Route> routeFunction, Handler<RoutingContext> handler, HandlerType type,
        boolean resume) {
    this.routeFunction = routeFunction;
    this.handler = handler;
    this.type = type;
}
 
Example #17
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initHttpOperation(
        String methodId,
        VxmsShared vxmsShared,
        Object service,
        Method restMethod,
        Route route,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes,
        Class<? extends Annotation> httpAnnotation) {
    final Optional<Method> errorMethod =
            errorMethodStream.filter(method -> method.isAnnotationPresent(httpAnnotation)).findFirst();
    initHttpRoute(methodId, vxmsShared, service, restMethod, consumes, errorMethod, route);
}
 
Example #18
Source File: RestRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initHttpDelete(
        VxmsShared vxmsShared, Router router, MethodDescriptor descriptor) {
    final Route route = router.delete(URIUtil.cleanPath(descriptor.path));
    final Context context = getContext(vxmsShared);
    final String methodId =
            descriptor.path
                    + HttpMethod.DELETE.name()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(methodId, vxmsShared, route, descriptor);
}
 
Example #19
Source File: RouteImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Route failureHandler(Handler<RoutingContext> exceptionHandler) {
  if (state.isExclusive()) {
    throw new IllegalStateException("This Route is exclusive for already mounted sub router.");
  }

  state = state.addFailureHandler(exceptionHandler);
  checkAdd();
  return this;
}
 
Example #20
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 初始化权限认证
 * 
 * @param path
 *          路径
 * @param method
 *          类型
 * @param consumes
 *          接收类型
 * @param route
 *          路由
 * @throws Exception
 */
public void initAuthHandler(VxApis api, Route route) throws Exception {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	// 添加consumes
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	// 添加handler
	VxApiAuthOptions authOptions = api.getAuthOptions();
	VxApiAuth authHandler = VxApiAuthFactory.getVxApiAuth(authOptions.getInFactoryName(), authOptions.getOption(), api, httpClient);
	route.handler(authHandler);
}
 
Example #21
Source File: AbstractVertxBasedHttpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates the router for handling requests.
 * <p>
 * This method creates a router instance along with a route matching all request. That route is initialized with the
 * following handlers and failure handlers:
 * <ol>
 * <li>a handler to add a Micrometer {@code Timer.Sample} to the routing context,</li>
 * <li>a handler and failure handler that creates tracing data for all server requests,</li>
 * <li>a handler to log when the connection is closed prematurely,</li>
 * <li>a default failure handler,</li>
 * <li>a handler limiting the body size of requests to the maximum payload size set in the <em>config</em>
 * properties,</li>
 * <li>(optional) a handler that applies the trace sampling priority configured for the tenant/auth-id of a
 * request.</li>
 * </ol>
 *
 * @return The newly created router (never {@code null}).
 */
protected Router createRouter() {

    final Router router = Router.router(vertx);
    final Route matchAllRoute = router.route();
    // the handlers and failure handlers are added here in a specific order!
    // 1. handler to start the metrics timer
    matchAllRoute.handler(ctx -> {
        ctx.put(KEY_MICROMETER_SAMPLE, getMetrics().startTimer());
        ctx.next();
    });
    // 2. tracing handler
    final TracingHandler tracingHandler = createTracingHandler();
    matchAllRoute.handler(tracingHandler).failureHandler(tracingHandler);

    // 3. handler to log when the connection is closed prematurely
    matchAllRoute.handler(ctx -> {
        if (!ctx.response().closed() && !ctx.response().ended()) {
            ctx.response().closeHandler(v -> logResponseGettingClosedPrematurely(ctx));
        }
        ctx.next();
    });

    // 4. default handler for failed routes
    matchAllRoute.failureHandler(new DefaultFailureHandler());

    // 5. BodyHandler with request size limit
    log.info("limiting size of inbound request body to {} bytes", getConfig().getMaxPayloadSize());
    final BodyHandler bodyHandler = BodyHandler.create(DEFAULT_UPLOADS_DIRECTORY)
            .setBodyLimit(getConfig().getMaxPayloadSize());
    matchAllRoute.handler(bodyHandler);

    // 6. handler to set the trace sampling priority
    Optional.ofNullable(getTenantTraceSamplingHandler())
            .ifPresent(tenantTraceSamplingHandler -> matchAllRoute.handler(tenantTraceSamplingHandler));
    return router;
}
 
Example #22
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initHttpAll(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Optional<Method> errorMethod = errorMethodStream.findFirst();
    final Route route = router.route(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value() + HTTP_ALL + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpRoute(methodId, vxmsShared, service, restMethod, consumes, errorMethod, route);
}
 
Example #23
Source File: RouteImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Route handler(Handler<RoutingContext> contextHandler) {
  if (state.isExclusive()) {
    throw new IllegalStateException("This Route is exclusive for already mounted sub router.");
  }
  state = state.addContextHandler(contextHandler);

  checkAdd();
  return this;
}
 
Example #24
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 #25
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 初始化参数检查,参数检查已经交给处理器做了
 * 
 * @param api
 * @param route
 */
public void initParamCheck(VxApis api, Route route) {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	// 添加consumes
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	VxApiRouteHandlerParamCheck paramCheckHandler = VxApiRouteHandlerParamCheck.create(api, appOption.getContentLength());
	route.handler(paramCheckHandler);

}
 
Example #26
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 初始化与后端服务交互
 * 
 * @param isNext
 *          下一步还是结束(也就是说如有后置处理器inNext=true,反则false)
 * @param api
 * @param route
 * @throws Exception
 */
public void initServerHandler(boolean isNext, VxApis api, Route route) throws Exception {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	if (api.getServerEntrance().getServerType() == ApiServerTypeEnum.CUSTOM) {
		serverCustomTypeHandler(isNext, api, route);
	} else if (api.getServerEntrance().getServerType() == ApiServerTypeEnum.REDIRECT) {
		serverRedirectTypeHandler(isNext, api, route);
	} else if (api.getServerEntrance().getServerType() == ApiServerTypeEnum.HTTP_HTTPS) {
		serverHttpTypeHandler(isNext, api, route);
	} else {
		route.handler(rct -> {
			// TODO 当没有响应服务时next或者结束请求
			if (isNext) {
				rct.next();
			} else {
				rct.response().putHeader(SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(CONTENT_TYPE, api.getContentType()).setStatusCode(404)
						.end();
			}
		});
	}
}
 
Example #27
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 自定义服务类型处理器
 * 
 * @param isNext
 * @param api
 * @param route
 * @throws Exception
 */
public void serverCustomTypeHandler(boolean isNext, VxApis api, Route route) throws Exception {
	JsonObject body = api.getServerEntrance().getBody();
	VxApiCustomHandlerOptions options = VxApiCustomHandlerOptions.fromJson(body);
	if (options == null) {
		throw new NullPointerException("自定义服务类型的配置文件无法装换为服务类");
	}
	if (body.getValue("isNext") == null) {
		body.put("isNext", isNext);
	}
	options.setOption(body);
	VxApiCustomHandler customHandler = VxApiCustomHandlerFactory.getCustomHandler(options.getInFactoryName(), options.getOption(), api,
			httpClient);
	route.handler(customHandler);
}
 
Example #28
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void updateHttpConsumes(Optional<Consumes> consumes, Route route) {
    consumes.ifPresent(
            cs -> {
                if (cs.value().length > 0) {
                    Stream.of(cs.value()).forEach(route::consumes);
                }
            });
}
 
Example #29
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initHttpRoute(
        String methodId,
        VxmsShared vxmsShared,
        Object service,
        Method restMethod,
        Optional<Consumes> consumes,
        Optional<Method> errorMethod,
        Route route) {
    route.handler(
            routingContext ->
                    handleRESTRoutingContext(
                            methodId, vxmsShared, service, restMethod, errorMethod, routingContext));
    updateHttpConsumes(consumes, route);
}
 
Example #30
Source File: VertxServer.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
@Override
public void removeSubRouter(String mountPoint) {
  synchronized (lock) {
    checkNotStopped();
    rootRouter.getRoutes()
        .stream()
        .filter(r -> r.getPath().equals(mountPoint))
        .forEach(Route::remove);
  }
}