com.blade.mvc.http.HttpMethod Java Examples

The following examples show how to use com.blade.mvc.http.HttpMethod. 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: CategoryController.java    From tale with MIT License 6 votes vote down vote up
@Route(value = "save", method = HttpMethod.POST)
@JSON
public RestResponse saveCategory(@Param String cname, @Param Integer mid) {
    try {
        metasService.saveMeta(Types.CATEGORY, cname, mid);
        siteService.cleanCache(Types.C_STATISTICS);
    } 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 #2
Source File: RouteMatcher.java    From blade with Apache License 2.0 6 votes vote down vote up
public void route(String path, Class<?> clazz, String methodName, HttpMethod httpMethod) {
    try {
        Assert.notNull(path, "Route path not is null!");
        Assert.notNull(clazz, "Route type not is null!");
        Assert.notNull(methodName, "Method name not is null");
        Assert.notNull(httpMethod, "Request Method not is null");

        Method[] methods = classMethodPool.computeIfAbsent(clazz.getName(), k -> clazz.getMethods());
        if (null == methods) {
            return;
        }
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Object controller = controllerPool.computeIfAbsent(clazz, k -> ReflectKit.newInstance(clazz));
                addRoute(httpMethod, path, controller, clazz, method);
            }
        }
    } catch (Exception e) {
        log.error("Add route method error", e);
    }
}
 
Example #3
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 #4
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 #5
Source File: RouteStruct.java    From blade with Apache License 2.0 6 votes vote down vote up
public HttpMethod getMethod() {
    if (null != mapping) {
        return mapping.method();
    }
    if (null != getRoute) {
        return HttpMethod.GET;
    }
    if (null != postRoute) {
        return HttpMethod.POST;
    }
    if (null != putRoute) {
        return HttpMethod.PUT;
    }
    if (null != deleteRoute) {
        return HttpMethod.DELETE;
    }
    return HttpMethod.ALL;
}
 
Example #6
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 #7
Source File: HttpRequestTest.java    From blade with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethod() {
    Assert.assertEquals(mockHttpRequest("GET").method(), "GET");
    Assert.assertEquals(mockHttpRequest("GET").httpMethod(), HttpMethod.GET);

    Assert.assertEquals(mockHttpRequest("POST").method(), "POST");
    Assert.assertEquals(mockHttpRequest("POST").httpMethod(), HttpMethod.POST);

    Assert.assertEquals(mockHttpRequest("PUT").method(), "PUT");
    Assert.assertEquals(mockHttpRequest("PUT").httpMethod(), HttpMethod.PUT);

    Assert.assertEquals(mockHttpRequest("DELETE").method(), "DELETE");
    Assert.assertEquals(mockHttpRequest("DELETE").httpMethod(), HttpMethod.DELETE);

    Assert.assertEquals(mockHttpRequest("BEFORE").method(), "BEFORE");
    Assert.assertEquals(mockHttpRequest("BEFORE").httpMethod(), HttpMethod.BEFORE);

    Assert.assertEquals(mockHttpRequest("AFTER").method(), "AFTER");
    Assert.assertEquals(mockHttpRequest("AFTER").httpMethod(), HttpMethod.AFTER);
}
 
Example #8
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 #9
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 #10
Source File: RouteBuilder.java    From blade with Apache License 2.0 6 votes vote down vote up
private void parseRoute(RouteStruct routeStruct) {
    // build multiple route
    HttpMethod methodType = routeStruct.getMethod();
    String[]   paths      = routeStruct.getPaths();
    if (paths.length > 0) {
        for (String path : paths) {
            String pathV = getRoutePath(path, routeStruct.nameSpace, routeStruct.suffix);

            routeMatcher.addRoute(com.blade.mvc.route.Route.builder()
                    .target(routeStruct.controller)
                    .targetType(routeStruct.routeType)
                    .action(routeStruct.method)
                    .path(pathV)
                    .httpMethod(methodType)
                    .build());
        }
    }
}
 
Example #11
Source File: PageController.java    From tale with MIT License 6 votes vote down vote up
@Route(value = "modify", method = HttpMethod.POST)
@JSON
public RestResponse modifyArticle(@Valid Contents contents) {
    if (null == contents || null == contents.getCid()) {
        return RestResponse.fail("缺少参数,请重试");
    }
    try {
        Integer cid = contents.getCid();
        contents.setType(Types.PAGE);
        contentsService.updateArticle(contents);
        return RestResponse.ok(cid);
    } catch (Exception e) {
        String msg = "页面编辑失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
}
 
Example #12
Source File: PageController.java    From tale with MIT License 6 votes vote down vote up
@Route(value = "publish", method = HttpMethod.POST)
@JSON
public RestResponse publishPage(@Valid Contents contents) {

    Users users = this.user();
    contents.setType(Types.PAGE);
    contents.setAllowPing(true);
    contents.setAuthorId(users.getUid());
    try {
        contentsService.publish(contents);
        siteService.cleanCache(Types.C_STATISTICS);
    } 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 #13
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
private void registerRoute(Route route) {
    String  path    = parsePath(route.getPath());
    Matcher matcher = null;
    if (path != null) {
        matcher = PATH_VARIABLE_PATTERN.matcher(path);
    }
    boolean      find             = false;
    List<String> uriVariableNames = new ArrayList<>();
    while (matcher != null && matcher.find()) {
        if (!find) {
            find = true;
        }
        String regexName  = matcher.group(1);
        String regexValue = matcher.group(2);

        // just a simple path param
        if (StringKit.isBlank(regexName)) {
            uriVariableNames.add(regexValue);
        } else {
            //regex path param
            uriVariableNames.add(regexName);
        }
    }
    HttpMethod httpMethod = route.getHttpMethod();
    if (find || BladeKit.isWebHook(httpMethod)) {
        regexMapping.addRoute(path, httpMethod, route, uriVariableNames);
    } else {
        staticMapping.addRoute(path, httpMethod, route);
    }
}
 
Example #14
Source File: RegexMapping.java    From blade with Apache License 2.0 5 votes vote down vote up
public void addRoute(String path, HttpMethod httpMethod, Route route, List<String> uriVariableNames) {
    if (regexRoutes.get(httpMethod) == null) {
        regexRoutes.put(httpMethod, new HashMap<>());
        patternBuilders.put(httpMethod, new StringBuilder("^"));
        indexes.put(httpMethod, 1);
    }
    int i = indexes.get(httpMethod);
    regexRoutes.get(httpMethod).put(i, new FastRouteMappingInfo(route, uriVariableNames));
    indexes.put(httpMethod, i + uriVariableNames.size() + 1);
    patternBuilders.get(httpMethod).append(new PathRegexBuilder().parsePath(path));
}
 
Example #15
Source File: CategoryController.java    From tale with 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 #16
Source File: TemplateController.java    From tale with MIT License 5 votes vote down vote up
@Route(value = "", method = HttpMethod.GET)
public String index(Request request) {
    String themePath = Const.CLASSPATH + File.separatorChar + "templates" + File.separatorChar + "themes" + File.separatorChar + Commons.site_theme();
    try {
        List<String> files = Files.list(Paths.get(themePath))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".html"))
                .collect(Collectors.toList());

        List<String> partial = Files.list(Paths.get(themePath + File.separatorChar + "partial"))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".html"))
                .map(fileName -> "partial/" + fileName)
                .collect(Collectors.toList());

        List<String> statics = Files.list(Paths.get(themePath + File.separatorChar + "static"))
                .map(path -> path.getFileName().toString())
                .filter(path -> path.endsWith(".js") || path.endsWith(".css"))
                .map(fileName -> "static/" + fileName)
                .collect(Collectors.toList());

        files.addAll(partial);
        files.addAll(statics);

        request.attribute("tpls", files);
    } catch (IOException e) {
        log.error("找不到模板路径");
    }
    return "admin/tpl_list";
}
 
Example #17
Source File: RegexMapping.java    From blade with Apache License 2.0 5 votes vote down vote up
private void registerRoutePatterns(HttpMethod httpMethod) {
    StringBuilder patternBuilder = patternBuilders.get(httpMethod);
    if (patternBuilder.length() > 1) {
        patternBuilder.setCharAt(patternBuilder.length() - 1, '$');
    }
    log.debug("Fast Route Method: {}, regex: {}", httpMethod, patternBuilder);
    regexRoutePatterns.put(httpMethod, Pattern.compile(patternBuilder.toString()));
}
 
Example #18
Source File: BaseTestCase.java    From blade with Apache License 2.0 5 votes vote down vote up
protected com.blade.mvc.http.HttpRequest mockHttpRequest(String methodName) {
    WebContext.init(Blade.of(),"/");
    com.blade.mvc.http.HttpRequest request = mock(com.blade.mvc.http.HttpRequest.class);
    when(request.method()).thenReturn(methodName);
    when(request.url()).thenReturn("/");
    when(request.uri()).thenReturn("/");
    when(request.httpMethod()).thenReturn(HttpMethod.valueOf(methodName));
    return request;
}
 
Example #19
Source File: AttachController.java    From tale with 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 #20
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
public void route(String path, Class<?> clazz, String methodName) {
    Assert.notNull(methodName, "Method name not is null");
    HttpMethod httpMethod = HttpMethod.ALL;
    if (methodName.contains(":")) {
        String[] methodArr = methodName.split(":");
        httpMethod = HttpMethod.valueOf(methodArr[0].toUpperCase());
        methodName = methodArr[1];
    }
    this.route(path, clazz, methodName, httpMethod);
}
 
Example #21
Source File: InstallController.java    From tale with 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";
}
 
Example #22
Source File: StaticMapping.java    From blade with Apache License 2.0 5 votes vote down vote up
public void addRoute(String path, HttpMethod httpMethod, Route route) {
    if (!mapping.containsKey(path)) {
        Map<String, Route> map = CollectionKit.newMap(8);
        map.put(httpMethod.name(), route);
        mapping.put(path, map);
    } else {
        mapping.get(path).put(httpMethod.name(), route);
    }
}
 
Example #23
Source File: Route.java    From blade with Apache License 2.0 5 votes vote down vote up
public Route(HttpMethod httpMethod, String path, Class<?> targetType, Method action) {
    super();
    this.httpMethod = httpMethod;
    this.path = PathKit.fixPath(path);
    this.targetType = targetType;
    this.action = action;
    this.sort = Integer.MAX_VALUE;
}
 
Example #24
Source File: Route.java    From blade with Apache License 2.0 5 votes vote down vote up
public Route(HttpMethod httpMethod, String path, Object target, Class<?> targetType, Method action) {
    super();
    this.httpMethod = httpMethod;
    this.path = PathKit.fixPath(path);
    this.target = target;
    this.targetType = targetType;
    this.action = action;
    sort = Integer.MAX_VALUE;
}
 
Example #25
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
/**
 * Find all in after of the hooks
 *
 * @param path request path
 */
public List<Route> getAfter(String path) {
    String cleanPath = parsePath(path);

    List<Route> afters = hooks.values().stream()
            .flatMap(Collection::stream)
            .sorted(Comparator.comparingInt(Route::getSort))
            .filter(route -> route.getHttpMethod() == HttpMethod.AFTER && matchesPath(route.getPath(), cleanPath))
            .collect(Collectors.toList());

    this.giveMatch(path, afters);
    return afters;
}
 
Example #26
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
/**
 * Find all in before of the hook
 *
 * @param path request path
 */
public List<Route> getBefore(String path) {
    String cleanPath = parsePath(path);
    List<Route> collect = hooks.values().stream()
            .flatMap(Collection::stream)
            .sorted(Comparator.comparingInt(Route::getSort))
            .filter(route -> route.getHttpMethod() == HttpMethod.BEFORE && matchesPath(route.getPath(), cleanPath))
            .collect(Collectors.toList());

    this.giveMatch(path, collect);
    return collect;
}
 
Example #27
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
public Route addRoute(String path, RouteHandler handler, HttpMethod httpMethod) {
    try {
        return addRoute(httpMethod, path, handler, METHOD_NAME);
    } catch (Exception e) {
        log.error("", e);
    }
    return null;
}
 
Example #28
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
Route addRoute(Route route) {
    String     path           = route.getPath();
    HttpMethod httpMethod     = route.getHttpMethod();
    Object     controller     = route.getTarget();
    Class<?>   controllerType = route.getTargetType();
    Method     method         = route.getAction();
    return addRoute(httpMethod, path, controller, controllerType, method);
}
 
Example #29
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
private Route addRoute(HttpMethod httpMethod, String path, Object controller, Class<?> controllerType, Method method) {

        // [/** | /*]
        path = "*".equals(path) ? "/.*" : path;
        path = path.replace("/**", "/.*").replace("/*", "/.*");

        String key = path + "#" + httpMethod.toString();

        // exist
        if (this.routes.containsKey(key)) {
            log.warn("\tRoute {} -> {} has exist", path, httpMethod.toString());
        }

        Route route = new Route(httpMethod, path, controller, controllerType, method);
        if (BladeKit.isWebHook(httpMethod)) {
            Order order = controllerType.getAnnotation(Order.class);
            if (null != order) {
                route.setSort(order.value());
            }
            if (this.hooks.containsKey(key)) {
                this.hooks.get(key).add(route);
            } else {
                List<Route> empty = new ArrayList<>();
                empty.add(route);
                this.hooks.put(key, empty);
            }
        } else {
            this.routes.put(key, route);
        }
        return route;
    }
 
Example #30
Source File: RouteMatcher.java    From blade with Apache License 2.0 5 votes vote down vote up
@Deprecated
public Route addRoute(String path, RouteHandler0 handler, HttpMethod httpMethod) {
    try {
        return addRoute(httpMethod, path, handler, METHOD_NAME);
    } catch (Exception e) {
        log.error("", e);
    }
    return null;
}