Java Code Examples for io.vertx.ext.web.Route#handler()

The following examples show how to use io.vertx.ext.web.Route#handler() . 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: HttpServiceBase.java    From hono with Eclipse Public License 2.0 6 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:
 * <ul>
 * <li>a handler and failure handler that creates tracing data for all server requests,</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>
 * </ul>
 *
 * @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. tracing handler
    final TracingHandler tracingHandler = createTracingHandler();
    matchAllRoute.handler(tracingHandler).failureHandler(tracingHandler);
    // 2. default handler for failed routes
    matchAllRoute.failureHandler(new DefaultFailureHandler());
    // 3. BodyHandler with request size limit
    log.info("limiting size of inbound request body to {} bytes", getConfig().getMaxPayloadSize());
    matchAllRoute.handler(BodyHandler.create().setUploadsDirectory(DEFAULT_UPLOADS_DIRECTORY)
            .setBodyLimit(getConfig().getMaxPayloadSize()));
    //4. AuthHandler
    addAuthHandler(router);
    return router;
}
 
Example 2
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 3
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 初始化后置路由器
 * 
 * @param path
 *          路径
 * @param method
 *          类型
 * @param consumes
 *          接收类型
 * @param route
 *          路由
 * @throws Exception
 */
public void initAfterHandler(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
	VxApiAfterHandlerOptions options = api.getAfterHandlerOptions();
	VxApiAfterHandler afterHandler = VxApiAfterHandlerFactory.getAfterHandler(options.getInFactoryName(), options.getOption(), api,
			httpClient);
	route.handler(afterHandler);
}
 
Example 4
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 初始化前置路由器
 * 
 * @param path
 *          路径
 * @param method
 *          类型
 * @param consumes
 *          接收类型
 * @param route
 *          路由
 * @throws Exception
 */
public void initBeforeHandler(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
	VxApiBeforeHandlerOptions options = api.getBeforeHandlerOptions();
	VxApiBeforeHandler beforeHandler = VxApiBeforeHandlerFactory.getBeforeHandler(options.getInFactoryName(), options.getOption(), api,
			httpClient);
	route.handler(beforeHandler);
}
 
Example 5
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 6
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 7
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 8
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 9
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 10
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Add authentication handler to the router if needed.
 *
 * @param router The router.
 */
protected void addAuthHandler(final Router router) {
    if (authHandler != null) {
        final Route matchAllRoute = router.route();
        matchAllRoute.handler(authHandler);
    }
}
 
Example 11
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 12
Source File: TestDefaultEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testOnRequest(@Mocked Router router, @Mocked Route route
    , @Mocked RoutingContext context
    , @Mocked HttpServerRequest requst
    , @Mocked EdgeInvocation invocation) {
  DefaultEdgeDispatcher dispatcher = new DefaultEdgeDispatcher();
  Map<String, String> pathParams = new HashMap<>();
  pathParams.put("param0", "testService");
  pathParams.put("param1", "v1");

  new Expectations() {
    {
      router.routeWithRegex("/api/([^\\\\/]+)/([^\\\\/]+)/(.*)");
      result = route;
      route.handler((Handler<RoutingContext>) any);
      result = route;
      route.failureHandler((Handler<RoutingContext>) any);
      result = route;
      context.pathParams();
      result = pathParams;
      context.request();
      result = requst;
      requst.path();
      result = "/api/testService/v1/hello";
      invocation.setVersionRule("1.0.0.0-2.0.0.0");
      invocation.init("testService", context, "/testService/v1/hello",
          Deencapsulation.getField(dispatcher, "httpServerFilters"));
      invocation.edgeInvoke();
    }
  };
  dispatcher.init(router);
  Assert.assertEquals(dispatcher.enabled(), false);
  Assert.assertEquals(Utils.findActualPath("/api/test", 1), "/test");
  Assert.assertEquals(dispatcher.getOrder(), 20000);

  dispatcher.onRequest(context);
  // assert done in expectations.
}
 
Example 13
Source File: SummerRouter.java    From Summer with MIT License 5 votes vote down vote up
public void registerResource(Class clazz){

        if (isRegister(clazz)){
            return;
        }
        ClassInfo classInfo = MethodsProcessor.get(classInfos, clazz);
        if (classInfo!=null){
            for (MethodInfo methodInfo:classInfo.getMethodInfoList()) {
                String p = classInfo.getClassPath()+methodInfo.getMethodPath();
                p = PathParamConverter.converter(p);
                p =addContextPath(p);
                Route route=null;
                if (methodInfo.getHttpMethod()== null){
                    route = router.route(p);
                }else
                if (methodInfo.getHttpMethod()== GET.class){
                    route = router.get(p);
                }else if (methodInfo.getHttpMethod()== POST.class){
                    route = router.post(p);
                }else if (methodInfo.getHttpMethod()== PUT.class){
                    route = router.put(p);
                }else if (methodInfo.getHttpMethod()== DELETE.class){
                    route = router.delete(p);
                }else if (methodInfo.getHttpMethod()== OPTIONS.class){
                    route = router.options(p);
                }else if (methodInfo.getHttpMethod()== HEAD.class){
                    route = router.head(p);
                }
                if (methodInfo.isBlocking()){
                    route.blockingHandler(getHandler(classInfo,methodInfo));
                }else{
                    route.handler(getHandler(classInfo,methodInfo));
                }
            }
        }
    }
 
Example 14
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void addRoute(RuntimeValue<Router> router, Function<Router, Route> route, Handler<RoutingContext> handler,
        HandlerType blocking) {

    Route vr = route.apply(router.getValue());

    Handler<RoutingContext> requestHandler = handler;
    if (blocking == HandlerType.BLOCKING) {
        vr.blockingHandler(requestHandler, false);
    } else if (blocking == HandlerType.FAILURE) {
        vr.failureHandler(requestHandler);
    } else {
        vr.handler(requestHandler);
    }
}
 
Example 15
Source File: RouterEventTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void observeRouter(@Observes Router router) {
    counter++;
    router.get("/boom").handler(ctx -> ctx.response().setStatusCode(200).end("ok"));
    Route post = router.post("/post");
    post.consumes("text/plain");
    post.handler(BodyHandler.create());
    post.handler(ctx -> ctx.response().end(Integer.toString(counter)));
}
 
Example 16
Source File: HandlerConsumer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(Route route) {
    route.handler(handler);
}
 
Example 17
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@Override
protected void doStart() throws Exception {
    super.doStart();

    final PlatformHttpEndpoint endpoint = getEndpoint();
    final String path = endpoint.getPath();
    /* Transform from the Camel path param syntax /path/{key} to vert.x web's /path/:key */
    final String vertxPathParamPath = PATH_PARAMETER_PATTERN.matcher(path).replaceAll(":$1");
    final Route newRoute = router.route(vertxPathParamPath);

    final Set<Method> methods = Method.parseList(endpoint.getHttpMethodRestrict());
    if (!methods.equals(Method.getAll())) {
        methods.stream().forEach(m -> newRoute.method(HttpMethod.valueOf(m.name())));
    }
    if (endpoint.getConsumes() != null) {
        newRoute.consumes(endpoint.getConsumes());
    }
    if (endpoint.getProduces() != null) {
        newRoute.produces(endpoint.getProduces());
    }

    handlers.forEach(newRoute::handler);

    newRoute.handler(
            ctx -> {
                Exchange exchg = null;
                try {
                    final Exchange exchange = exchg = toExchange(ctx);
                    createUoW(exchange);
                    getAsyncProcessor().process(
                            exchange,
                            doneSync -> writeResponse(ctx, exchange, getEndpoint().getHeaderFilterStrategy()));
                } catch (Exception e) {
                    ctx.fail(e);
                    getExceptionHandler().handleException("Failed handling platform-http endpoint " + path, exchg, e);
                } finally {
                    if (exchg != null) {
                        doneUoW(exchg);
                    }
                }
            });

    this.route = newRoute;
}
 
Example 18
Source File: RouteManager.java    From festival with Apache License 2.0 4 votes vote down vote up
private void setTimeoutIfNeed(RouteAttribute routeAttribute, Route route) {
    if (routeAttribute.getTimeout() > 0) {
        route.handler(TimeoutHandler.create(routeAttribute.getTimeout()));
    }
}
 
Example 19
Source File: SwaggerRouter.java    From vertx-swagger with Apache License 2.0 4 votes vote down vote up
private static void configureRoute(Route route, String serviceId, Operation operation, EventBus eventBus, Function<RoutingContext, DeliveryOptions> configureMessage) {
    Optional.ofNullable(operation.getConsumes()).ifPresent(consumes -> consumes.forEach(route::consumes));
    Optional.ofNullable(operation.getProduces()).ifPresent(produces -> produces.forEach(route::produces));

    route.handler(context -> {
        try {
            JsonObject message = new JsonObject();
            operation.getParameters().forEach(parameter -> {
                String name = parameter.getName();
                Object value = PARAMETER_EXTRACTORS.get(parameter.getIn()).extract(name, parameter, context);
                message.put(name, value);
            });

            // callback to configure message e.g. provide message header values
            DeliveryOptions deliveryOptions = configureMessage != null ? configureMessage.apply(context) : new DeliveryOptions();

            addAuthUserHeader(context, deliveryOptions);

            context.request().headers().forEach(entry -> deliveryOptions.addHeader(entry.getKey(), entry.getValue()));
            
            eventBus.<String> send(serviceId, message, deliveryOptions, operationResponse -> {
                if (operationResponse.succeeded()) {
                    manageHeaders(context.response(), operationResponse.result().headers());

                    if (operationResponse.result().body() != null) {
                        context.response().end(operationResponse.result().body());
                    } else {
                        context.response().end();
                    }
                  
                } else {
                    vertxLogger.error("Internal Server Error", operationResponse.cause());
                    manageError((ReplyException)operationResponse.cause(), context.response());
                }
            });
        } catch (Exception e) {
            vertxLogger.error("sending Bad Request", e);
            badRequestEnd(context.response());
        }

    });
}
 
Example 20
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 2 votes vote down vote up
/**
 * 页面跳转服务类型处理器
 * 
 * @param isNext
 * @param api
 * @param route
 * @throws NullPointerException
 */
public void serverRedirectTypeHandler(boolean isNext, VxApis api, Route route) throws NullPointerException {
	VxApiRouteHandlerRedirectType redirectTypehandler = VxApiRouteHandlerRedirectType.create(isNext, api);
	route.handler(redirectTypehandler);
}