Java Code Examples for com.blade.mvc.http.Request

The following examples show how to use com.blade.mvc.http.Request. These examples are extracted from open source projects. 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 Project: tale   Author: tfssweb   File: TaleUtils.java    License: 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 #2
Source Project: tale   Author: tfssweb   File: ThemeController.java    License: 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 #3
Source Project: tale   Author: tfssweb   File: ThemeController.java    License: 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 #4
Source Project: blade   Author: lets-blade   File: HttpRequestTest.java    License: 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 #5
Source Project: tale   Author: tfssweb   File: ArticleController.java    License: 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 #6
Source Project: tale   Author: tfssweb   File: IndexController.java    License: 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 #7
Source Project: tale   Author: tfssweb   File: IndexController.java    License: 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 #8
Source Project: tale   Author: tfssweb   File: IndexController.java    License: 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 #9
Source Project: tale   Author: tfssweb   File: IndexController.java    License: 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 #10
Source Project: tale   Author: tfssweb   File: CategoryController.java    License: 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 #11
Source Project: tale   Author: tfssweb   File: CategoryController.java    License: 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 #12
Source Project: tale   Author: tfssweb   File: IndexController.java    License: 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 #13
Source Project: tale   Author: tfssweb   File: BaseWebHook.java    License: 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 #14
Source Project: blade   Author: lets-blade   File: RouteActionArguments.java    License: 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 #15
Source Project: blade   Author: lets-blade   File: DefaultExceptionHandler.java    License: 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 #16
Source Project: tale   Author: tfssweb   File: PageController.java    License: MIT License 5 votes vote down vote up
@Route(value = "/:cid", method = HttpMethod.GET)
public String editPage(@PathParam String cid, Request request) {
    Optional<Contents> contents = contentsService.getContents(cid);
    if (!contents.isPresent()) {
        return render_404();
    }
    request.attribute("contents", contents.get());
    request.attribute(Types.ATTACH_URL, Commons.site_option(Types.ATTACH_URL, Commons.site_url()));
    return "admin/page_edit";
}
 
Example #17
Source Project: blade   Author: lets-blade   File: HttpRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFileItems() {

    Request mockRequest = mockHttpRequest("GET");

    Map<String, FileItem> attr     = new HashMap<>();
    FileItem              fileItem = new FileItem();
    fileItem.setName("file");
    fileItem.setFileName("hello.png");
    fileItem.setPath("/usr/hello.png");
    fileItem.setContentType("image/png");
    fileItem.setLength(20445L);

    attr.put("img", fileItem);

    when(mockRequest.fileItems()).thenReturn(attr);

    Request request = new HttpRequest(mockRequest);

    FileItem img = request.fileItem("img").get();

    assertNotNull(img);

    assertNull(img.getFile());

    assertEquals("file", img.getName());
    assertEquals("hello.png", img.getFileName());
    assertEquals("/usr/hello.png", img.getPath());
    assertEquals(Long.valueOf(20445), Optional.of(img.getLength()).get());
    assertEquals("image/png", img.getContentType());

}
 
Example #18
Source Project: tale   Author: tfssweb   File: ThemeController.java    License: MIT License 5 votes vote down vote up
/**
 * 保存主题配置项
 *
 * @param request
 * @return
 */
@PostRoute(value = "setting")
@JSON
public RestResponse saveSetting(Request request) {
    try {
        Map<String, List<String>> query = request.parameters();

        // theme_milk_options => {  }
        String currentTheme = Commons.site_theme();
        String key          = "theme_" + currentTheme + "_options";

        Map<String, String> options = new HashMap<>();
        query.forEach((k, v) -> options.put(k, v.get(0)));

        optionsService.saveOption(key, JsonKit.toString(options));

        TaleConst.OPTIONS = Environment.of(optionsService.getOptions());
        new Logs(LogActions.THEME_SETTING, JsonKit.toString(query), 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 #19
Source Project: tale   Author: tfssweb   File: CategoryController.java    License: MIT License 5 votes vote down vote up
@Route(value = "", method = HttpMethod.GET)
public String index(Request request) {
    List<Metas>   categories = siteService.getMetas(Types.RECENT_META, Types.CATEGORY, TaleConst.MAX_POSTS);
    List<Metas> tags       = siteService.getMetas(Types.RECENT_META, Types.TAG, TaleConst.MAX_POSTS);
    request.attribute("categories", categories);
    request.attribute("tags", tags);
    return "admin/category";
}
 
Example #20
Source Project: tale   Author: tfssweb   File: CommentController.java    License: MIT License 5 votes vote down vote up
@GetRoute(value = "")
public String index(@Param(defaultValue = "1") int page,
                    @Param(defaultValue = "15") int limit, Request request) {
    Users users = this.user();

    Page<Comments> commentPage = new Comments().where("author_id", "<>", users.getUid()).page(page, limit);
    request.attribute("comments", commentPage);
    return "admin/comment_list";
}
 
Example #21
Source Project: tale   Author: tfssweb   File: AttachController.java    License: MIT License 5 votes vote down vote up
/**
 * 附件页面
 *
 * @param request
 * @param page
 * @param limit
 * @return
 */
@Route(value = "", method = HttpMethod.GET)
public String index(Request request, @Param(defaultValue = "1") int page,
                    @Param(defaultValue = "12") int limit) {

    Attach       attach     = new Attach();
    Page<Attach> attachPage = attach.page(page, limit);
    request.attribute("attachs", attachPage);
    request.attribute(Types.ATTACH_URL, Commons.site_option(Types.ATTACH_URL, Commons.site_url()));
    request.attribute("max_file_size", TaleConst.MAX_FILE_SIZE / 1024);
    return "admin/attach";
}
 
Example #22
Source Project: tale   Author: tfssweb   File: AttachController.java    License: MIT License 5 votes vote down vote up
@Route(value = "delete")
@JSON
public RestResponse delete(@Param Integer id, Request request) {
    try {
        Attach attach = new Attach().find(id);
        if (null == attach) {
            return RestResponse.fail("不存在该附件");
        }
        String fkey = attach.getFkey();
        siteService.cleanCache(Types.C_STATISTICS);
        String             filePath = CLASSPATH.substring(0, CLASSPATH.length() - 1) + fkey;
        java.nio.file.Path path     = Paths.get(filePath);
        log.info("Delete attach: [{}]", filePath);
        if (Files.exists(path)) {
            Files.delete(path);
        }
        attach.delete(id);
        new Logs(LogActions.DEL_ATTACH, fkey, 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 #23
Source Project: tale   Author: tfssweb   File: ArticleController.java    License: MIT License 5 votes vote down vote up
/**
 * 文章管理首页
 *
 * @param page
 * @param limit
 * @param request
 * @return
 */
@GetRoute(value = "")
public String index(@Param(defaultValue = "1") int page, @Param(defaultValue = "15") int limit,
                    Request request) {

    Page<Contents> articles = new Contents().where("type", Types.ARTICLE).page(page, limit, "created desc");
    request.attribute("articles", articles);
    return "admin/article_list";
}
 
Example #24
Source Project: blade   Author: lets-blade   File: HttpRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAttribute() {
    Request mockRequest = mockHttpRequest("GET");

    Map<String, Object> attr = new HashMap<>();
    attr.put("name", "biezhi");

    when(mockRequest.attributes()).thenReturn(attr);

    Request request = new HttpRequest(mockRequest);
    assertEquals("biezhi", request.attribute("name"));
}
 
Example #25
Source Project: tale   Author: tfssweb   File: ArticleController.java    License: MIT License 5 votes vote down vote up
/**
 * 文章编辑页面
 *
 * @param cid
 * @param request
 * @return
 */
@GetRoute(value = "/:cid")
public String editArticle(@PathParam String cid, Request request) {
    Optional<Contents> contents = contentsService.getContents(cid);
    if (!contents.isPresent()) {
        return render_404();
    }
    request.attribute("contents", contents.get());
    List<Metas> categories = metasService.getMetas(Types.CATEGORY);
    request.attribute("categories", categories);
    request.attribute("active", "article");
    request.attribute(Types.ATTACH_URL, Commons.site_option(Types.ATTACH_URL, Commons.site_url()));
    return "admin/article_edit";
}
 
Example #26
Source Project: tale   Author: tfssweb   File: IndexController.java    License: MIT License 5 votes vote down vote up
/**
 * 系统设置
 */
@Route(value = "setting", method = HttpMethod.GET)
public String setting(Request request) {
    Map<String, String> options = optionsService.getOptions();
    request.attribute("options", options);
    return "admin/setting";
}
 
Example #27
Source Project: blade   Author: lets-blade   File: HttpRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testContentType() {

    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.contentType()).thenReturn(Const.CONTENT_TYPE_HTML);

    assertEquals(Const.CONTENT_TYPE_HTML, mockRequest.contentType());

    when(mockRequest.contentType()).thenReturn(Const.CONTENT_TYPE_JSON);
    assertEquals(Const.CONTENT_TYPE_JSON, mockRequest.contentType());
}
 
Example #28
Source Project: tale   Author: tfssweb   File: IndexController.java    License: MIT License 5 votes vote down vote up
/**
 * 首页分页
 *
 * @param request
 * @param page
 * @param limit
 * @return
 */
@GetRoute(value = {"page/:page", "page/:page.html"})
public String index(Request request, @PathParam int page, @Param(defaultValue = "12") int limit) {
    page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
    if (page > 1) {
        this.title(request, "第" + page + "页");
    }
    request.attribute("page_num", page);
    request.attribute("limit", limit);
    request.attribute("is_home", true);
    request.attribute("page_prefix", "/page");
    return this.render("index");
}
 
Example #29
Source Project: tale   Author: tfssweb   File: IndexController.java    License: MIT License 5 votes vote down vote up
@GetRoute(value = {"search/:keyword/:page", "search/:keyword/:page.html"})
public String search(Request request, @PathParam String keyword, @PathParam int page, @Param(defaultValue = "12") int limit) {

    page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;

    Page<Contents> articles = new Contents().where("type", Types.ARTICLE).and("status", Types.PUBLISH)
            .like("title", "%" + keyword + "%").page(page, limit, "created desc");

    request.attribute("articles", articles);

    request.attribute("type", "搜索");
    request.attribute("keyword", keyword);
    request.attribute("page_prefix", "/search/" + keyword);
    return this.render("page-category");
}
 
Example #30
Source Project: tale   Author: tfssweb   File: InstallController.java    License: MIT License 5 votes vote down vote up
/**
 * 安装页
 *
 * @return
 */
@Route(value = "/", method = HttpMethod.GET)
public String index(Request request) {
    boolean existInstall = Files.exists(Paths.get(AttachController.CLASSPATH + "install.lock"));
    int allow_reinstall = TaleConst.OPTIONS.getInt("allow_install", 0);

    if (allow_reinstall == 1) {
        request.attribute("is_install", false);
    } else {
        request.attribute("is_install", existInstall);
    }
    return "install";
}