com.blade.mvc.http.Request Java Examples

The following examples show how to use com.blade.mvc.http.Request. 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: BaseWebHook.java    From tale with MIT License 6 votes vote down vote up
private boolean isRedirect(Request request, Response response) {
    Users  user = TaleUtils.getLoginUser();
    String uri  = request.uri();
    if (null == user) {
        Integer uid = TaleUtils.getCookieUid(request);
        if (null != uid) {
            user = new Users().find(uid);
            request.session().attribute(TaleConst.LOGIN_SESSION_KEY, user);
        }
    }
    if (uri.startsWith(TaleConst.ADMIN_URI) && !uri.startsWith(TaleConst.LOGIN_URI)) {
        if (null == user) {
            response.redirect(TaleConst.LOGIN_URI);
            return false;
        }
        request.attribute(TaleConst.PLUGINS_MENU_NAME, TaleConst.PLUGIN_MENUS);
    }
    return true;
}
 
Example #2
Source File: IndexController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 仪表盘
 */
@Route(value = {"/", "index"}, method = HttpMethod.GET)
public String index(Request request) {
    List<Comments> comments   = siteService.recentComments(5);
    List<Contents> contents   = siteService.getContens(Types.RECENT_ARTICLE, 5);
    Statistics     statistics = siteService.getStatistics();
    // 取最新的20条日志
    Page<Logs> logsPage = new Logs().page(1, 20, "id desc");
    List<Logs> logs     = logsPage.getRows();

    request.attribute("comments", comments);
    request.attribute("articles", contents);
    request.attribute("statistics", statistics);
    request.attribute("logs", logs);
    return "admin/index";
}
 
Example #3
Source File: HttpRequestTest.java    From blade with Apache License 2.0 6 votes vote down vote up
@Test
public void testHeaders() {
    Request             mockRequest = mockHttpRequest("GET");
    Map<String, String> headers     = new CaseInsensitiveHashMap<>();
    headers.put("h1", "a1");
    headers.put("H2", "a2");

    when(mockRequest.headers()).thenReturn(headers);

    Request request = new HttpRequest(mockRequest);

    assertEquals("a1", request.header("h1"));
    assertEquals("a1", request.header("H1"));
    assertEquals("a2", request.header("h2"));
    assertEquals("a2", request.header("H2"));
    request.headers().forEach((key,val)-> System.out.println(key+"\t=\t"+val));
}
 
Example #4
Source File: ThemeController.java    From tale with MIT License 6 votes vote down vote up
@GetRoute(value = "")
public String index(Request request) {
    // 读取主题
    String         themesDir  = AttachController.CLASSPATH + "templates/themes";
    File[]         themesFile = new File(themesDir).listFiles();
    List<ThemeDto> themes     = new ArrayList<>(themesFile.length);
    for (File f : themesFile) {
        if (f.isDirectory()) {
            ThemeDto themeDto = new ThemeDto(f.getName());
            if (Files.exists(Paths.get(f.getPath() + "/setting.html"))) {
                themeDto.setHasSetting(true);
            }
            themes.add(themeDto);
            try {
                Blade.me().addStatics("/templates/themes/" + f.getName() + "/screenshot.png");
            } catch (Exception e) {
            }
        }
    }
    request.attribute("current_theme", Commons.site_theme());
    request.attribute("themes", themes);
    return "admin/themes";
}
 
Example #5
Source File: TaleUtils.java    From tale with MIT License 6 votes vote down vote up
/**
 * 获取cookie中的用户id
 *
 * @param request
 * @return
 */
public static Integer getCookieUid(Request request) {
    if (null != request) {
        Optional<String> c = request.cookie(TaleConst.USER_IN_COOKIE);
        if (c.isPresent()) {
            try {
                String value = c.get();
                long[] ids   = HASH_IDS.decode(value);
                if (null != ids && ids.length > 0) {
                    return Long.valueOf(ids[0]).intValue();
                }
            } catch (Exception e) {
            }
        }
    }
    return null;
}
 
Example #6
Source File: ThemeController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 主题设置页面
 *
 * @param request
 * @return
 */
@GetRoute(value = "setting")
public String setting(Request request) {
    String currentTheme = Commons.site_theme();
    String key          = "theme_" + currentTheme + "_options";

    String              option = optionsService.getOption(key);
    Map<String, Object> map    = new HashMap<>();
    try {
        if (StringKit.isNotBlank(option)) {
            map = JsonKit.toAson(option);
        }
        request.attribute("theme_options", map);
    } catch (Exception e) {
        log.error("解析主题设置出现异常", e);
    }
    request.attribute("theme_options", map);
    return this.render("setting");
}
 
Example #7
Source File: ArticleController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 删除文章操作
 *
 * @param cid
 * @param request
 * @return
 */
@Route(value = "delete")
@JSON
public RestResponse delete(@Param int cid, Request request) {
    try {
        contentsService.delete(cid);
        siteService.cleanCache(Types.C_STATISTICS);
        new Logs(LogActions.DEL_ARTICLE, cid + "", request.address(), this.getUid()).save();
    } catch (Exception e) {
        String msg = "文章删除失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
    return RestResponse.ok();
}
 
Example #8
Source File: IndexController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 保存系统设置
 */
@Route(value = "setting", method = HttpMethod.POST)
@JSON
public RestResponse saveSetting(@Param String site_theme, Request request) {
    try {
        Map<String, List<String>> querys = request.parameters();
        optionsService.saveOptions(querys);

        Environment config = Environment.of(optionsService.getOptions());
        TaleConst.OPTIONS = config;

        new Logs(LogActions.SYS_SETTING, JsonKit.toString(querys), request.address(), this.getUid()).save();
        return RestResponse.ok();
    } catch (Exception e) {
        String msg = "保存设置失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}
 
Example #9
Source File: DefaultExceptionHandler.java    From blade with Apache License 2.0 6 votes vote down vote up
protected void render500(Request request, Response response) {
    var blade   = WebContext.blade();
    var page500 = Optional.ofNullable(blade.environment().get(ENV_KEY_PAGE_500, null));

    if (page500.isPresent()) {
        this.renderPage(response, new ModelAndView(page500.get()));
    } else {
        if (blade.devMode()) {
            var htmlCreator = new HtmlCreator();
            htmlCreator.center("<h1>" + request.attribute("title") + "</h1>");
            htmlCreator.startP("message-header");
            htmlCreator.add("Request URI: " + request.uri());
            htmlCreator.startP("message-header");
            htmlCreator.add("Error Message: " + request.attribute("message"));
            htmlCreator.endP();
            if (null != request.attribute(VARIABLE_STACKTRACE)) {
                htmlCreator.startP("message-body");
                htmlCreator.add(request.attribute(VARIABLE_STACKTRACE).toString().replace("\n", "<br/>"));
                htmlCreator.endP();
            }
            response.html(htmlCreator.html());
        } else {
            response.html(INTERNAL_SERVER_ERROR_HTML);
        }
    }
}
 
Example #10
Source File: IndexController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 系统备份
 *
 * @return
 */
@Route(value = "backup", method = HttpMethod.POST)
@JSON
public RestResponse backup(@Param String bk_type, @Param String bk_path,
                           Request request) {
    if (StringKit.isBlank(bk_type)) {
        return RestResponse.fail("请确认信息输入完整");
    }

    try {
        BackResponse backResponse = siteService.backup(bk_type, bk_path, "yyyyMMddHHmm");
        new Logs(LogActions.SYS_BACKUP, null, request.address(), this.getUid()).save();
        return RestResponse.ok(backResponse);
    } catch (Exception e) {
        String msg = "备份失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}
 
Example #11
Source File: IndexController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 重启系统
 *
 * @param sleep
 * @return
 */
@Route(value = "reload", method = HttpMethod.GET)
public void reload(@Param(defaultValue = "0") int sleep, Request request) {
    if (sleep < 0 || sleep > 999) {
        sleep = 10;
    }
    try {
        // sh tale.sh reload 10
        String webHome = new File(AttachController.CLASSPATH).getParent();
        String cmd     = "sh " + webHome + "/bin tale.sh reload " + sleep;
        log.info("execute shell: {}", cmd);
        ShellUtils.shell(cmd);
        new Logs(LogActions.RELOAD_SYS, "", request.address(), this.getUid()).save();
        TimeUnit.SECONDS.sleep(sleep);
    } catch (Exception e) {
        log.error("重启系统失败", e);
    }
}
 
Example #12
Source File: CategoryController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 某个分类详情页分页
 */
@GetRoute(value = {"category/:keyword/:page", "category/:keyword/:page.html"})
public String categories(Request request, @PathParam String keyword,
                         @PathParam int page, @Param(defaultValue = "12") int limit) {
    page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
    Metas metaDto = metasService.getMeta(Types.CATEGORY, keyword);
    if (null == metaDto) {
        return this.render_404();
    }

    Page<Contents> contentsPage = contentsService.getArticles(metaDto.getMid(), page, limit);
    request.attribute("articles", contentsPage);
    request.attribute("meta", metaDto);
    request.attribute("type", "分类");
    request.attribute("keyword", keyword);
    request.attribute("is_category", true);
    request.attribute("page_prefix", "/category/" + keyword);

    return this.render("page-category");
}
 
Example #13
Source File: CategoryController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 标签下文章分页
 */
@GetRoute(value = {"tag/:name/:page", "tag/:name/:page.html"})
public String tags(Request request, @PathParam String name, @PathParam int page, @Param(defaultValue = "12") int limit) {
    page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
    Metas metaDto = metasService.getMeta(Types.TAG, name);
    if (null == metaDto) {
        return this.render_404();
    }

    Page<Contents> contentsPage = contentsService.getArticles(metaDto.getMid(), page, limit);
    request.attribute("articles", contentsPage);
    request.attribute("meta", metaDto);
    request.attribute("type", "标签");
    request.attribute("keyword", name);
    request.attribute("is_tag", true);
    request.attribute("page_prefix", "/tag/" + name);

    return this.render("page-category");
}
 
Example #14
Source File: IndexController.java    From tale with MIT License 6 votes vote down vote up
/**
 * 自定义页面
 */
@CsrfToken(newToken = true)
@GetRoute(value = {"/:cid", "/:cid.html"})
public String page(@PathParam String cid, Request request) {
    Optional<Contents> contentsOptional = contentsService.getContents(cid);
    if (!contentsOptional.isPresent()) {
        return this.render_404();
    }
    Contents contents = contentsOptional.get();
    if (contents.getAllowComment()) {
        int cp = request.queryInt("cp", 1);
        request.attribute("cp", cp);
    }
    request.attribute("article", contents);
    Contents temp = new Contents();
    temp.setHits(contents.getHits() + 1);
    temp.update(contents.getCid());
    if (Types.ARTICLE.equals(contents.getType())) {
        return this.render("post");
    }
    if (Types.PAGE.equals(contents.getType())) {
        return this.render("page");
    }
    return this.render_404();
}
 
Example #15
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 #16
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddress() {
    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.address()).thenReturn("127.0.0.1");

    assertEquals("127.0.0.1", mockRequest.address());
}
 
Example #17
Source File: WebContext.java    From blade with Apache License 2.0 5 votes vote down vote up
public WebContext(Request request, Response response,
                  ChannelHandlerContext channelHandlerContext) {

    this.request = request;
    this.response = response;
    this.channelHandlerContext = channelHandlerContext;
}
 
Example #18
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathParam() {
    Request mockRequest = mockHttpRequest("GET");

    Map<String, String> pathParams = new HashMap<>();
    pathParams.put("id", "6");
    pathParams.put("age", "24");
    pathParams.put("name", "jack");
    when(mockRequest.pathParams()).thenReturn(pathParams);

    Request request = new HttpRequest(mockRequest);
    assertEquals(Long.valueOf(6), request.pathLong("id"));
    assertEquals(Integer.valueOf(24), request.pathInt("age"));
    assertEquals("jack", request.pathString("name"));
}
 
Example #19
Source File: SessionHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private Session getSession(Request request) {
    String cookieHeader = request.cookie(WebContext.sessionKey());
    if (StringKit.isEmpty(cookieHeader)) {
        return null;
    }
    return sessionManager.getSession(cookieHeader);
}
 
Example #20
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserAgent() {
    Map<String, String> headers = Collections.singletonMap("User-Agent", firefoxUA);

    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.headers()).thenReturn(headers);

    Request request = new HttpRequest(mockRequest);
    assertEquals(firefoxUA, request.userAgent());
}
 
Example #21
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
public static <T> T parseModel(Class<T> argType, Request request, String name) {

        T obj = ReflectKit.newInstance(argType);

        List<Field> fields = ReflectKit.loopFields(argType);

        for (Field field : fields) {
            if ("serialVersionUID".equals(field.getName())) {
                continue;
            }
            Object value = null;

            Optional<String> fieldValue = request.query(field.getName());

            if (StringKit.isNotBlank(name)) {
                String fieldName = name + "[" + field.getName() + "]";
                fieldValue = request.query(fieldName);
            }

            if (fieldValue.isPresent() && StringKit.isNotBlank(fieldValue.get())) {
                value = ReflectKit.convert(field.getType(), fieldValue.get());
            }
            if (null != value) {
                ReflectKit.setFieldValue(field, obj, value);
            }
        }
        return obj;
    }
 
Example #22
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryString() {
    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.url()).thenReturn("/hello?name=q1");

    Request request = new HttpRequest(mockRequest);
    assertEquals("name=q1", request.queryString());
}
 
Example #23
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
private static Object getHeader(ParamStruct paramStruct) throws BladeException {
    Type        argType     = paramStruct.argType;
    HeaderParam headerParam = paramStruct.headerParam;
    String      paramName   = paramStruct.paramName;
    Request     request     = paramStruct.request;

    String key = StringKit.isEmpty(headerParam.value()) ? paramName : headerParam.value();
    String val = request.header(key);
    if (StringKit.isBlank(val)) {
        val = headerParam.defaultValue();
    }
    return ReflectKit.convert(argType, val);
}
 
Example #24
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
private static Object getCookie(ParamStruct paramStruct) throws BladeException {
    Type        argType     = paramStruct.argType;
    CookieParam cookieParam = paramStruct.cookieParam;
    String      paramName   = paramStruct.paramName;
    Request     request     = paramStruct.request;

    String cookieName = StringKit.isEmpty(cookieParam.value()) ? paramName : cookieParam.value();
    String val        = request.cookie(cookieName);
    if (null == val) {
        val = cookieParam.defaultValue();
    }
    return ReflectKit.convert(argType, val);
}
 
Example #25
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
private static Object getQueryParam(ParamStruct paramStruct) {
    Param   param     = paramStruct.param;
    String  paramName = paramStruct.paramName;
    Type    argType   = paramStruct.argType;
    Request request   = paramStruct.request;
    if (null == param) {
        return null;
    }

    String name = StringKit.isBlank(param.name()) ? paramName : param.name();

    if (ReflectKit.isBasicType(argType) || argType.equals(Date.class)
            || argType.equals(BigDecimal.class) || argType.equals(LocalDate.class)
            || argType.equals(LocalDateTime.class) || (argType instanceof Class && ((Class) argType).isEnum())) {

        String value = request.query(name).orElseGet(() -> getDefaultValue(param.defaultValue(), argType));

        return ReflectKit.convert(argType, value);
    } else {
        if (ParameterizedType.class.isInstance(argType)) {

            List<String> values = request.parameters().get(param.name());
            return getParameterizedTypeValues(values, argType);
        }
        return parseModel(ReflectKit.typeToClass(argType), request, param.name());
    }
}
 
Example #26
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsIE() {
    Request             mockRequest = mockHttpRequest("GET");
    Map<String, String> headers     = Collections.singletonMap("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
    when(mockRequest.headers()).thenReturn(headers);

    Request request = new HttpRequest(mockRequest);

    assertEquals(Boolean.TRUE, request.isIE());

    when(mockRequest.headers()).thenReturn(Collections.EMPTY_MAP);
    request = new HttpRequest(mockRequest);

    assertEquals(Boolean.FALSE, request.isIE());
}
 
Example #27
Source File: RouteActionArguments.java    From blade with Apache License 2.0 5 votes vote down vote up
private static Object getAnnotationParam(Parameter parameter, String paramName, Request request) {
    Type  argType = parameter.getParameterizedType();
    Param param   = parameter.getAnnotation(Param.class);

    ParamStruct.ParamStructBuilder structBuilder = ParamStruct.builder().argType(argType).request(request);

    if (null != param) {
        ParamStruct paramStruct = structBuilder.param(param).paramName(paramName).build();
        return getQueryParam(paramStruct);
    }
    BodyParam bodyParam = parameter.getAnnotation(BodyParam.class);
    if (null != bodyParam) {
        return getBodyParam(structBuilder.build());
    }
    PathParam pathParam = parameter.getAnnotation(PathParam.class);
    if (null != pathParam) {
        return getPathParam(structBuilder.pathParam(pathParam).paramName(paramName).build());
    }
    HeaderParam headerParam = parameter.getAnnotation(HeaderParam.class);
    if (null != headerParam) {
        return getHeader(structBuilder.headerParam(headerParam).paramName(paramName).build());
    }
    // cookie param
    CookieParam cookieParam = parameter.getAnnotation(CookieParam.class);
    if (null != cookieParam) {
        return getCookie(structBuilder.cookieParam(cookieParam).paramName(paramName).build());
    }
    // form multipart
    MultipartParam multipartParam = parameter.getAnnotation(MultipartParam.class);
    if (null != multipartParam && argType == FileItem.class) {
        String name = StringKit.isBlank(multipartParam.value()) ? paramName : multipartParam.value();
        return request.fileItem(name).orElse(null);
    }
    return null;
}
 
Example #28
Source File: HttpRequestTest.java    From blade with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsSecure() {
    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.isSecure()).thenReturn(false);

    assertEquals(Boolean.FALSE, mockRequest.isSecure());
}
 
Example #29
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 #30
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);
}