com.blade.mvc.RouteContext Java Examples

The following examples show how to use com.blade.mvc.RouteContext. 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: XssMiddleware.java    From blade with Apache License 2.0 6 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    if (xssOption.isExclusion(context.uri())) {
        return true;
    }

    this.filterHeaders(context.headers());
    this.filterParameters(context.parameters());

    if (context.contentType().toLowerCase().contains("json")) {
        String body = context.bodyToString();
        if (StringKit.isNotEmpty(body)) {
            String filterBody = stripXSS(body);
            context.body(new StringBody(filterBody));
        }
    }
    return true;
}
 
Example #2
Source File: BasicAuthMiddleware.java    From blade with Apache License 2.0 6 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    boolean isAuth = false;

    for (String startExclusion : urlStartExclusions) {
        if ("/".equals(startExclusion) || context.uri().startsWith(startExclusion)) {
            isAuth = true;
            break;
        }
    }

    if (!isAuth) {
        return true;
    }

    String authorization = context.header("Authorization");
    String user          = this.searchCredential(authorization);
    if (null == user) {
        context.header("WWW-Authenticate", this.realm).status(401);
        return false;
    }
    return true;
}
 
Example #3
Source File: RouteActionArguments.java    From blade with Apache License 2.0 6 votes vote down vote up
public static Object[] getRouteActionParameters(RouteContext context) {
    Method  actionMethod = context.routeAction();
    Request request      = context.request();
    actionMethod.setAccessible(true);

    Parameter[] parameters     = actionMethod.getParameters();
    Object[]    args           = new Object[parameters.length];
    String[]    parameterNames = ASMUtils.findMethodParmeterNames(actionMethod);

    for (int i = 0, len = parameters.length; i < len; i++) {
        Parameter parameter = parameters[i];
        String    paramName = Objects.requireNonNull(parameterNames)[i];
        Type      argType   = parameter.getParameterizedType();
        if (containsAnnotation(parameter)) {
            args[i] = getAnnotationParam(parameter, paramName, request);
            continue;
        }
        if (ReflectKit.isBasicType(argType)) {
            args[i] = request.query(paramName);
            continue;
        }
        args[i] = getCustomType(parameter, paramName, context);
    }
    return args;
}
 
Example #4
Source File: RouteBuilder.java    From blade with Apache License 2.0 6 votes vote down vote up
public void addWebHook(final Class<?> webHook, String pattern) {
    Method before = ReflectKit.getMethod(webHook, HttpMethod.BEFORE.name().toLowerCase(), RouteContext.class);
    Method after  = ReflectKit.getMethod(webHook, HttpMethod.AFTER.name().toLowerCase(), RouteContext.class);

    routeMatcher.addRoute(com.blade.mvc.route.Route.builder()
            .targetType(webHook)
            .action(before)
            .path(pattern)
            .httpMethod(HttpMethod.BEFORE)
            .build());

    routeMatcher.addRoute(com.blade.mvc.route.Route.builder()
            .targetType(webHook)
            .action(after)
            .path(pattern)
            .httpMethod(HttpMethod.AFTER)
            .build());
}
 
Example #5
Source File: CsrfMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    if (csrfOption.isIgnoreMethod(context.method())) {
        if (csrfOption.isStartExclusion(context.uri())) {
            return true;
        }
        this.genToken(context);
        return true;
    }

    if (csrfOption.isExclusion(context.uri())) {
        return true;
    }

    String tokenUUID = context.session().attribute(sessionToken);
    if (StringKit.isEmpty(tokenUUID)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }

    String token = csrfOption.getTokenGetter().apply(context.request());
    if (StringKit.isEmpty(token)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }
    String hash = new String(Base64.getDecoder().decode(token));
    if (!PasswordKit.checkPassword(tokenUUID, hash)) {
        csrfOption.getErrorHandler().accept(context);
        return false;
    }

    return true;
}
 
Example #6
Source File: CsrfMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
public String genToken(RouteContext context) {
    String tokenUUID = context.session().attribute(sessionToken);
    if (StringKit.isEmpty(tokenUUID)) {
        tokenUUID = UUID.UU64();
        context.session().attribute(sessionToken, tokenUUID);
    }
    String token = Base64.getEncoder().encodeToString(PasswordKit.hashPassword(tokenUUID).getBytes());
    context.attribute("_csrf_token", token);
    context.attribute("_csrf_token_input", "<input type='hidden' name='_token' value='" + token + "'/>");
    return token;
}
 
Example #7
Source File: CorsMiddleware.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RouteContext context) {
    context.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    context.header("Access-Control-Allow-Origin", "*");
    context.header("Access-Control-Allow-Headers", CorsConfiger.ALL);
    context.status(204);
}
 
Example #8
Source File: Application.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void updates(RouteContext ctx) {
    int queries = getQueries(ctx.fromString("queries", "1"));

    List<Integer> idList = generateIdList(queries);

    List<World> worlds = idList.stream()
            .map(id -> select().from(World.class).byId(id))
            .peek(Application::updateWorld).collect(toList());

    ctx.json(worlds).contentType(JSON_CONTENT_TYPE).header(SERVER_HEADER, SERVER_VALUE);
}
 
Example #9
Source File: BasicAuthMiddlewareTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthFail() throws Exception {
    Request mockRequest = mockHttpRequest("GET");

    WebContext.init(Blade.of(), "/");

    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Basic YmxhZGU6YmxhZGUyMg==");

    when(mockRequest.parameters()).thenReturn(new HashMap<>());
    when(mockRequest.headers()).thenReturn(headers);

    Request  request  = new HttpRequest(mockRequest);
    Response response = mockHttpResponse(200);

    RouteContext context = new RouteContext(request, response);

    context.initRoute(Route.builder()
            .action(AuthHandler.class.getMethod("handle", RouteContext.class))
            .targetType(AuthHandler.class)
            .target(new AuthHandler()).build());

    WebContext.set(new WebContext(request, response, null));

    AuthOption authOption = AuthOption.builder().build();
    authOption.addUser("admin", "123456");

    BasicAuthMiddleware basicAuthMiddleware = new BasicAuthMiddleware(authOption);
    boolean             flag                = basicAuthMiddleware.before(context);
    assertFalse(flag);
}
 
Example #10
Source File: RouteMethodHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(WebContext webContext) throws Exception {
    RouteContext context = new RouteContext(webContext.getRequest(), webContext.getResponse());

    // if execution returns false then execution is interrupted
    String uri   = context.uri();
    Route  route = webContext.getRoute();
    if (null == route) {
        throw new NotFoundException(context.uri());
    }

    // init route, request parameters, route action method and parameter.
    context.initRoute(route);

    // execution middleware
    if (hasMiddleware && !invokeMiddleware(routeMatcher.getMiddleware(), context)) {
        return;
    }
    context.injectParameters();

    // web hook before
    if (hasBeforeHook && !invokeHook(routeMatcher.getBefore(uri), context)) {
        return;
    }

    // execute
    this.routeHandle(context);

    // webHook
    if (hasAfterHook) {
        this.invokeHook(routeMatcher.getAfter(uri), context);
    }
}
 
Example #11
Source File: RouteMethodHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private boolean invokeMiddleware(List<Route> middleware, RouteContext context) throws BladeException {
    if (BladeKit.isEmpty(middleware)) {
        return true;
    }
    for (Route route : middleware) {
        WebHook webHook = (WebHook) WebContext.blade().ioc().getBean(route.getTargetType());
        boolean flag    = webHook.before(context);
        if (!flag) return false;
    }
    return true;
}
 
Example #12
Source File: BasicAuthMiddlewareTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthSuccess() throws Exception {

    Request mockRequest = mockHttpRequest("GET");

    WebContext.init(Blade.of(), "/");

    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Basic YWRtaW46MTIzNDU2");

    when(mockRequest.parameters()).thenReturn(new HashMap<>());
    when(mockRequest.headers()).thenReturn(headers);

    Request  request  = new HttpRequest(mockRequest);
    Response response = mockHttpResponse(200);

    RouteContext context = new RouteContext(request, response);
    context.initRoute(Route.builder()
            .action(AuthHandler.class.getMethod("handle", RouteContext.class))
            .targetType(AuthHandler.class)
            .target(new AuthHandler()).build());

    WebContext.set(new WebContext(request, response, null));

    AuthOption authOption = AuthOption.builder().build();
    authOption.addUser("admin", "123456");

    BasicAuthMiddleware basicAuthMiddleware = new BasicAuthMiddleware(authOption);
    boolean             flag                = basicAuthMiddleware.before(context);
    assertTrue(flag);
}
 
Example #13
Source File: BaeldungMiddleware.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public boolean before(RouteContext context) {
    log.info("[BaeldungMiddleware] called before Route method and other WebHooks");
    return true;
}
 
Example #14
Source File: BaeldungHook.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public boolean before(RouteContext ctx) {
    log.info("[BaeldungHook] called before Route method");
    return true;
}
 
Example #15
Source File: Application.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void db(RouteContext ctx) {
    World world = select().from(World.class).byId(generateId());
    ctx.json(world).contentType(JSON_CONTENT_TYPE).header(SERVER_HEADER, SERVER_VALUE);
}
 
Example #16
Source File: BladeWebHookType.java    From blade with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RouteContext context) {
    System.out.println("before...");
}
 
Example #17
Source File: BasicAuthMiddlewareTest.java    From blade with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RouteContext context) {
    context.text("登录成功");
}
 
Example #18
Source File: HttpServerHandler.java    From blade with Apache License 2.0 4 votes vote down vote up
private WebContext executeLogic(WebContext webContext) {
    try {
        WebContext.set(webContext);
        Request request = webContext.getRequest();
        String method = request.method();
        String uri = request.uri();
        Instant start = null;

        if (ALLOW_COST && !PERFORMANCE) {
            start = Instant.now();
        }

        if (isStaticFile(method, uri)) {
            staticFileHandler.handle(webContext);
        } else {
            if (HttpMethod.OPTIONS.name().equals(method) && null != WebContext.blade().corsMiddleware()) {
                WebContext.blade().corsMiddleware().handle(new RouteContext(webContext.getRequest(), webContext.getResponse()));
            } else {
                Route route = routeMatcher.lookupRoute(method, uri);
                if (null != route) {
                    webContext.setRoute(route);
                } else {
                    throw new NotFoundException(uri);
                }
                routeHandler.handle(webContext);
            }

            if (PERFORMANCE) {
                return webContext;
            }

            if (ALLOW_COST) {
                long cost = log200AndCost(log, start, BladeCache.getPaddingMethod(method), uri);
                request.attribute(REQUEST_COST_TIME, cost);
            } else {
                log200(log, BladeCache.getPaddingMethod(method), uri);
            }
        }
        return webContext;
    } catch (Exception e) {
        throw BladeException.wrapper(e);
    }
}
 
Example #19
Source File: RouteMatcher.java    From blade with Apache License 2.0 4 votes vote down vote up
private Route addRoute(HttpMethod httpMethod, String path, RouteHandler handler, String methodName) throws NoSuchMethodException {
    Class<?> handleType = handler.getClass();
    Method   method     = handleType.getMethod(methodName, RouteContext.class);
    return addRoute(httpMethod, path, handler, RouteHandler.class, method);
}
 
Example #20
Source File: Signature.java    From blade with Apache License 2.0 4 votes vote down vote up
public RouteContext routeContext() {
    return new RouteContext(request, response);
}
 
Example #21
Source File: RouteHandler.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Route handler
 *
 * @param context the current request context instance
 */
void handle(RouteContext context);
 
Example #22
Source File: WebHook.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * In the route calls after execution
 *
 * @param context the current route context
 * @return return true then execute next route, else interrupt the current request. default is true
 */
default boolean after(RouteContext context) {
    return true;
}
 
Example #23
Source File: WebHook.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * In the route calls before execution
 *
 * @param context the current route context
 * @return return true then execute next route, else interrupt the current request
 */
boolean before(RouteContext context);