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 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 #2
Source File: IndexController.java    From tale with 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 #3
Source File: CorsMiddleware.java    From blade with 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 #4
Source File: CorsMiddleware.java    From blade with 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 #5
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 #6
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 #7
Source File: DefaultExceptionHandler.java    From blade with 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 #8
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 #9
Source File: WebContext.java    From blade with 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 #10
Source File: RouteExampleController.java    From tutorials with 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 #11
Source File: TaleUtils.java    From tale with 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 #12
Source File: HttpResponseTest.java    From blade with 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 #13
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 #14
Source File: ExceptionHandlerTest.java    From blade with 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 #15
Source File: HttpResponseTest.java    From blade with 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 #16
Source File: HttpResponseTest.java    From blade with 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 #17
Source File: HttpResponseTest.java    From blade with 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 #18
Source File: HttpResponseTest.java    From blade with 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 #19
Source File: HttpResponseTest.java    From blade with 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 #20
Source File: DefaultExceptionHandler.java    From blade with 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 #21
Source File: DefaultExceptionHandler.java    From blade with 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 #22
Source File: LogExampleController.java    From tutorials with 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 #23
Source File: AuthController.java    From tale with 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 #24
Source File: TemplateController.java    From tale with 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 #25
Source File: CorsMiddleware.java    From blade with 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 #26
Source File: CorsMiddleware.java    From blade with 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 #27
Source File: IndexController.java    From tale with 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 #28
Source File: BaseWebHook.java    From tale with 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 #29
Source File: AttributesExampleController.java    From tutorials with 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 #30
Source File: RouteMatcher.java    From blade with Apache License 2.0 4 votes vote down vote up
@Deprecated
private Route addRoute(HttpMethod httpMethod, String path, RouteHandler0 handler, String methodName) throws NoSuchMethodException {
    Class<?> handleType = handler.getClass();
    Method   method     = handleType.getMethod(methodName, Request.class, Response.class);
    return addRoute(httpMethod, path, handler, RouteHandler0.class, method);
}