com.blade.mvc.http.Response Java Examples

The following examples show how to use com.blade.mvc.http.Response. 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: IndexController.java    License: MIT License 6 votes vote down vote up
/**
 * feed页
 *
 * @return
 */
@GetRoute(value = {"feed", "feed.xml", "atom.xml"})
public void feed(Response response) {

    List<Contents> articles = new Contents().where("type", Types.ARTICLE).and("status", Types.PUBLISH)
            .and("allow_feed", true)
            .findAll(OrderBy.desc("created"));

    try {
        String xml = TaleUtils.getRssXml(articles);
        response.contentType("text/xml; charset=utf-8");
        response.body(xml);
    } catch (Exception e) {
        log.error("生成 rss 失败", e);
    }
}
 
Example #2
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 #3
Source Project: blade   Author: lets-blade   File: CorsMiddleware.java    License: Apache License 2.0 6 votes vote down vote up
private CorsMiddleware allowHeads(Response response) {
    boolean isDefaultAllowHeads = corsConfig == null || corsConfig.getAllowedHeaders() == null
            || corsConfig.getAllowedHeaders().size() == 0;

    if (isDefaultAllowHeads) {
        response.header("Access-Control-Allow-Headers", CorsConfiger.ALL);
        return this;
    }

    String heads = corsConfig.getAllowedHeaders().stream()
            .collect(Collector.of(
                    () -> new StringJoiner(","),
                    StringJoiner::add,
                    StringJoiner::merge,
                    StringJoiner::toString
            ));

    response.header("Access-Control-Allow-Headers", heads);
    return this;
}
 
Example #4
Source Project: blade   Author: lets-blade   File: CorsMiddleware.java    License: Apache License 2.0 6 votes vote down vote up
private CorsMiddleware allowMethods(Response response) {
    boolean isDefaultAllowMethods = corsConfig == null || corsConfig.getAllowedMethods() == null
            || corsConfig.getAllowedMethods().size() == 0;

    if (isDefaultAllowMethods) {
        response.header("Access-Control-Allow-Methods",
                CorsConfiger.DEFAULT_ALLOWED_METHODS);
        return this;
    }

    String methods = corsConfig.getAllowedMethods().stream().collect(Collector.of(
            () -> new StringJoiner(", "),
            (j, method) -> j.add(method.toUpperCase()),
            StringJoiner::merge,
            StringJoiner::toString
    ));

    response.header("Access-Control-Allow-Methods", methods);
    return this;
}
 
Example #5
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 #6
Source Project: tale   Author: tfssweb   File: TaleUtils.java    License: MIT License 5 votes vote down vote up
/**
     * 设置记住密码cookie
     *
     * @param response
     * @param uid
     */
    public static void setCookie(Response response, Integer uid) {
        try {
            HASH_PREFIX[0] = uid;
            String val = HASH_IDS.encode(HASH_PREFIX);
            HASH_PREFIX[0] = -1;
//            String  val   = new String(EncrypKit.encryptAES(uid.toString().getBytes(), TaleConst.AES_SALT.getBytes()));
            boolean isSSL = Commons.site_url().startsWith("https");
            response.cookie("/", TaleConst.USER_IN_COOKIE, val, ONE_MONTH, isSSL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example #7
Source Project: tale   Author: tfssweb   File: AuthController.java    License: MIT License 5 votes vote down vote up
@Route(value = "login", method = HttpMethod.GET)
public String login(Response response) {
    if (null != this.user()) {
        response.redirect("/admin/index");
        return null;
    }
    return "admin/login";
}
 
Example #8
Source Project: tale   Author: tfssweb   File: TemplateController.java    License: MIT License 5 votes vote down vote up
@GetRoute("content")
public void getContent(@Param String fileName, Response response) {
    try {
        String themePath = Const.CLASSPATH + File.separatorChar + "templates" + File.separatorChar + "themes" + File.separatorChar + Commons.site_theme();
        String filePath  = themePath + File.separatorChar + fileName;
        String content   = Files.readAllLines(Paths.get(filePath)).stream().collect(Collectors.joining("\n"));
        response.text(content);
    } catch (IOException e) {
        log.error("获取模板文件失败", e);
    }
}
 
Example #9
Source Project: tale   Author: tfssweb   File: IndexController.java    License: MIT License 5 votes vote down vote up
/**
 * sitemap 站点地图
 *
 * @return
 */
@GetRoute(value = {"sitemap", "sitemap.xml"})
public void sitemap(Response response) {
    List<Contents> articles = new Contents().where("type", Types.ARTICLE).and("status", Types.PUBLISH)
            .and("allow_feed", true)
            .findAll(OrderBy.desc("created"));

    try {
        String xml = TaleUtils.getSitemapXml(articles);
        response.contentType("text/xml; charset=utf-8");
        response.body(xml);
    } catch (Exception e) {
        log.error("生成 sitemap 失败", e);
    }
}
 
Example #10
Source Project: tale   Author: tfssweb   File: BaseWebHook.java    License: MIT License 5 votes vote down vote up
@Override
public boolean before(Signature signature) {
    Request  request  = signature.request();
    Response response = signature.response();

    String uri = request.uri();
    String ip  = request.address();

    // 禁止该ip访问
    if (TaleConst.BLOCK_IPS.contains(ip)) {
        response.text("You have been banned, brother");
        return false;
    }

    log.info("UserAgent: {}", request.userAgent());
    log.info("用户访问地址: {}, 来路地址: {}", uri, ip);

    if (uri.startsWith(TaleConst.STATIC_URI)) {
        return true;
    }

    if (!TaleConst.INSTALLED && !uri.startsWith(TaleConst.INSTALL_URI)) {
        response.redirect(TaleConst.INSTALL_URI);
        return false;
    }

    if (TaleConst.INSTALLED) {
        return isRedirect(request, response);
    }
    return true;
}
 
Example #11
Source Project: blade   Author: lets-blade   File: CorsMiddleware.java    License: Apache License 2.0 5 votes vote down vote up
private CorsMiddleware allowCredentials(Response response) {
    boolean isDefaultAllowCredentials = corsConfig == null || corsConfig.getAllowCredentials() == null;

    if (isDefaultAllowCredentials) {
        response.header("Access-Control-Allow-Credentials",
                CorsConfiger.DEFAULT_ALLOW_CREDENTIALS);
        return this;
    }
    response.header("Access-Control-Allow-Credentials",
            corsConfig.getAllowCredentials().toString());
    return this;
}
 
Example #12
Source Project: blade   Author: lets-blade   File: CorsMiddleware.java    License: Apache License 2.0 5 votes vote down vote up
private CorsMiddleware setMaxAge(Response response) {
    boolean isDefaultMaxAge = corsConfig == null || corsConfig.getMaxAge() == null;
    if (isDefaultMaxAge) {
        response.header("Access-Control-Max-Age",
                CorsConfiger.DEFAULT_MAX_AGE.toString());
        return this;
    }
    response.header("Access-Control-Max-Age", corsConfig.getMaxAge().toString());
    return this;
}
 
Example #13
Source Project: blade   Author: lets-blade   File: DefaultExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void handleValidators(ValidatorException validatorException, Request request, Response response) {
    var code = Optional.ofNullable(validatorException.getCode()).orElse(500);
    if (request.isAjax() || request.contentType().toLowerCase().contains("json")) {
        response.json(RestResponse.fail(code, validatorException.getMessage()));
    } else {
        this.handleException(validatorException, request, response);
    }
}
 
Example #14
Source Project: blade   Author: lets-blade   File: DefaultExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void handleException(Exception e, Request request, Response response) {
    log.error("", e);
    if (null == response) {
        return;
    }
    response.status(500);
    request.attribute("title", "500 Internal Server Error");
    request.attribute("message", e.getMessage());
    request.attribute("stackTrace", getStackTrace(e));
    this.render500(request, response);
}
 
Example #15
Source Project: blade   Author: lets-blade   File: DefaultExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void renderPage(Response response, ModelAndView modelAndView) {
    var sw = new StringWriter();
    try {
        WebContext.blade().templateEngine().render(modelAndView, sw);
        ByteBuf          buffer           = Unpooled.wrappedBuffer(sw.toString().getBytes("utf-8"));
        FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.statusCode()), buffer);
        response.body(new RawBody(fullHttpResponse));
    } catch (Exception e) {
        log.error("Render view error", e);
    }
}
 
Example #16
Source Project: blade   Author: lets-blade   File: WebContext.java    License: 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 #17
Source Project: blade   Author: lets-blade   File: WebContext.java    License: Apache License 2.0 5 votes vote down vote up
public static WebContext create(Request request, Response response, ChannelHandlerContext ctx) {
    WebContext webContext = new WebContext();
    webContext.request = request;
    webContext.response = response;
    webContext.channelHandlerContext = ctx;
    WEB_CONTEXT_THREAD_LOCAL.set(webContext);
    return webContext;
}
 
Example #18
Source Project: blade   Author: lets-blade   File: BasicAuthMiddlewareTest.java    License: 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 #19
Source Project: blade   Author: lets-blade   File: BasicAuthMiddlewareTest.java    License: 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 #20
Source Project: blade   Author: lets-blade   File: ExceptionHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    request = mock(Request.class);
    when(request.header("Accept")).thenReturn("text/html");
    response = mock(Response.class);

    WebContext.init(Blade.me(), "/");
    WebContext.set(new WebContext(request, response, null));
}
 
Example #21
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBadRequest() {
    Response mockResponse = mockHttpResponse(200);
    Response response = new HttpResponse(mockResponse);
    response.badRequest();

    assertEquals(400, response.statusCode());
}
 
Example #22
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUnauthorized() {
    Response mockResponse = mockHttpResponse(200);
    Response response = new HttpResponse(mockResponse);
    response.unauthorized();

    assertEquals(401, response.statusCode());
}
 
Example #23
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNotFound() {
    Response mockResponse = mockHttpResponse(200);
    Response response = new HttpResponse(mockResponse);
    response.notFound();

    assertEquals(404, response.statusCode());
}
 
Example #24
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testContentType() {
    Response mockResponse = mockHttpResponse(200);

    Response response = new HttpResponse(mockResponse);
    response.contentType(Const.CONTENT_TYPE_HTML);

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

    response.contentType("hello.world");
    assertEquals("hello.world", response.contentType());
}
 
Example #25
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaders() {
    Response mockResponse = mockHttpResponse(200);

    when(mockResponse.headers()).thenReturn(new HashMap<>());

    Response response = new HttpResponse(mockResponse);
    assertEquals(0, response.headers().size());

    response.header("a", "123");
    assertEquals(1, response.headers().size());
}
 
Example #26
Source Project: blade   Author: lets-blade   File: HttpResponseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHeader() {

    Response mockResponse = mockHttpResponse(200);

    when(mockResponse.headers()).thenReturn(Collections.singletonMap("Server", "Nginx"));

    Response response = new HttpResponse(mockResponse);
    assertEquals(1, response.headers().size());
    assertEquals("Nginx", response.headers().get("Server"));
}
 
Example #27
Source Project: tutorials   Author: eugenp   File: RouteExampleController.java    License: MIT License 5 votes vote down vote up
@GetRoute("/load-configuration-in-a-route")
public void loadConfigurationInARoute(Response response) {
    String authors = WebContext.blade()
        .env("app.authors", "Unknown authors");
    log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
    response.render("index.html");
}
 
Example #28
Source Project: tutorials   Author: eugenp   File: AttributesExampleController.java    License: MIT License 5 votes vote down vote up
@GetRoute("/session-attribute-example")
public void getSessionAttribute(Request request, Response response) {
    Session session = request.session();
    session.attribute("session-val", SESSION_VALUE);
    String sessionVal = session.attribute("session-val");
    response.text(sessionVal);
}
 
Example #29
Source Project: tutorials   Author: eugenp   File: LogExampleController.java    License: MIT License 5 votes vote down vote up
@Route(value = "/test-logs")
public void testLogs(Response response) {
    log.trace("This is a TRACE Message");
    log.debug("This is a DEBUG Message");
    log.info("This is an INFO Message");
    log.warn("This is a WARN Message");
    log.error("This is an ERROR Message");
    response.text("Check in ./logs");
}
 
Example #30
Source Project: tale   Author: tfssweb   File: AuthController.java    License: MIT License 4 votes vote down vote up
@Route(value = "login", method = HttpMethod.POST)
@JSON
public RestResponse doLogin(LoginParam loginParam, Request request,
                            Session session, Response response) {

    Integer error_count = cache.get("login_error_count");
    try {
        error_count = null == error_count ? 0 : error_count;
        if (null != error_count && error_count > 3) {
            return RestResponse.fail("您输入密码已经错误超过3次,请10分钟后尝试");
        }

        long count = new Users().where("username", loginParam.getUsername()).count();
        if (count < 1) {
            return RestResponse.fail("不存在该用户");
        }
        String pwd = EncryptKit.md5(loginParam.getUsername(), loginParam.getPassword());

        Users user = new Users().where("username", loginParam.getUsername()).and("password", pwd).find();
        if (null == user) {
            return RestResponse.fail("用户名或密码错误");
        }
        session.attribute(TaleConst.LOGIN_SESSION_KEY, user);
        if (StringKit.isNotBlank(loginParam.getRemeberMe())) {
            TaleUtils.setCookie(response, user.getUid());
        }

        Users temp = new Users();
        temp.setLogged(DateKit.nowUnix());
        temp.update(user.getUid());
        log.info("登录成功:{}", loginParam.getUsername());
        cache.set("login_error_count", 0);

        new Logs(LogActions.LOGIN, loginParam.getUsername(), request.address(), user.getUid()).save();
    } catch (Exception e) {
        error_count += 1;
        cache.set("login_error_count", error_count, 10 * 60);
        String msg = "登录失败";
        if (e instanceof TipException) {
            msg = e.getMessage();
        } else {
            log.error(msg, e);
        }
        return RestResponse.fail(msg);
    }
    return RestResponse.ok();
}