private FullHttpResponse handleException(Throwable e) { Request request = WebContext.request(); Response response = WebContext.response(); String method = request.method(); String uri = request.uri(); Exception srcException = (Exception) e.getCause().getCause(); if (srcException instanceof BladeException) { } else { log500(log, method, uri); } if (null != WebContext.blade().exceptionHandler()) { WebContext.blade().exceptionHandler().handle(srcException); } else { log.error("", srcException); } return routeHandler.handleResponse( request, response, WebContext.get().getChannelHandlerContext() ); }
@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)); }
@Override public void stop() { if (isStop) { return; } isStop = true; System.out.println(); log.info("{}Blade shutdown ...", getStartedSymbol()); try { WebContext.clean(); if (this.bossGroup != null) { this.bossGroup.shutdownGracefully(); } if (this.workerGroup != null) { this.workerGroup.shutdownGracefully(); } log.info("{}Blade shutdown successful", getStartedSymbol()); } catch (Exception e) { log.error("Blade shutdown error", e); } }
private FullHttpResponse buildResponse(WebContext webContext) { WebContext.set(webContext); return routeHandler.handleResponse( webContext.getRequest(), webContext.getResponse(), webContext.getChannelHandlerContext() ); }
@Override public FullHttpResponse onView(ViewBody body) { try { var sw = new StringWriter(); WebContext.blade().templateEngine().render(body.modelAndView(), sw); WebContext.response().contentType(Const.CONTENT_TYPE_HTML); return this.onByteBuf(Unpooled.copiedBuffer(sw.toString().getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { log.error("Render view error", e); } return null; }
private WebContext executeLogic(WebContext webContext) { try { WebContext.set(webContext); Request request = webContext.getRequest(); String method = request.method(); String uri = request.uri(); staticFileHandler.handle(webContext); } else { if (HttpMethod.OPTIONS.name().equals(method) && null != WebContext.blade().corsMiddleware()) { WebContext.blade().corsMiddleware().handle(new RouteContext(webContext.getRequest(), webContext.getResponse())); } else { Route route = routeMatcher.lookupRoute(method, uri); if (null != route) { webContext.setRoute(route); } else { throw new NotFoundException(uri);
@Override public void close() throws IOException { try { this.flush(); FileChannel file = new FileInputStream(this.file).getChannel(); long fileLength = file.size(); HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength); httpResponse.headers().set(HttpConst.DATE, DateKit.gmtDate()); httpResponse.headers().set(HttpConst.SERVER, "blade/" + Const.VERSION); boolean keepAlive = WebContext.request().keepAlive(); if (keepAlive) { httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(httpResponse); ctx.write(new DefaultFileRegion(file, 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } finally { if(null != outputStream){ outputStream.close(); } } }
/** * Get application environment information. * * @param key environment key * @param defaultValue default value, if value is null * @return environment optional value */ public String env(String key, String defaultValue) { return blade().env(key, defaultValue); }
@Override public void handle(Exception e) { if (!ExceptionHandler.isResetByPeer(e)) { var response = WebContext.response(); var request = WebContext.request(); if (e instanceof BladeException) { this.handleBladeException((BladeException) e, request, response); } else if (ValidatorException.class.isInstance(e)) { this.handleValidators(ValidatorException.class.cast(e), request, response); } else { this.handleException(e, request, response); } } }
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; }
@Override public void start(Blade blade) throws Exception { this.blade = blade; this.environment = blade.environment(); this.processors = blade.processors(); this.loaders = blade.loaders(); long startMs = System.currentTimeMillis(); int padSize = 16; log.info("{} {}{}", StringKit.padRight("app.env", padSize), getPrefixSymbol(), environment.get(ENV_KEY_APP_ENV, "default")); log.info("{} {}{}", StringKit.padRight("app.pid", padSize), getPrefixSymbol(), BladeKit.getPID()); log.info("{} {}{}", StringKit.padRight("app.devMode", padSize), getPrefixSymbol(), blade.devMode()); log.info("{} {}{}", StringKit.padRight("jdk.version", padSize), getPrefixSymbol(), System.getProperty("java.version")); log.info("{} {}{}", StringKit.padRight("user.dir", padSize), getPrefixSymbol(), System.getProperty("user.dir")); log.info("{} {}{}", StringKit.padRight("java.io.tmpdir", padSize), getPrefixSymbol(), System.getProperty("java.io.tmpdir")); log.info("{} {}{}", StringKit.padRight("user.timezone", padSize), getPrefixSymbol(), System.getProperty("user.timezone")); log.info("{} {}{}", StringKit.padRight("file.encoding", padSize), getPrefixSymbol(), System.getProperty("file.encoding")); log.info("{} {}{}", StringKit.padRight("app.classpath", padSize), getPrefixSymbol(), CLASSPATH); this.initConfig(); String contextPath = environment.get(ENV_KEY_CONTEXT_PATH, "/"); WebContext.init(blade, contextPath); this.initIoc(); this.watchEnv(); this.startServer(startMs); this.sessionCleaner(); this.startTask(); this.shutdownHook(); }
/** * Get current thread context Request instance * * @return Request instance */ public static Request request() { var webContext = get(); return null != webContext ? webContext.request : null; }
@Override public void handle(Exception e) { if (e instanceof ValidateException) { ValidateException validateException = (ValidateException) e; String msg = validateException.getErrMsg(); WebContext.response().json(RestResponse.fail(msg)); } else { super.handle(e); } }
/** * Get current application contextPath, default is "/" * * @return Return contextPath */ default String contextPath() { return WebContext.contextPath(); }
private WebContext buildWebContext(ChannelHandlerContext ctx, HttpRequest req) { String remoteAddress = ctx.channel().remoteAddress().toString(); req.init(remoteAddress); return WebContext.create(req, new HttpResponse(), ctx); }
private WebContext executeLogic(WebContext webContext) { try { WebContext.set(webContext); Request request = webContext.getRequest(); String method = request.method(); String uri = request.uri(); staticFileHandler.handle(webContext); } else { if (HttpMethod.OPTIONS.name().equals(method) && null != WebContext.blade().corsMiddleware()) { WebContext.blade().corsMiddleware().handle(new RouteContext(webContext.getRequest(), webContext.getResponse())); } else { Route route = routeMatcher.lookupRoute(method, uri); if (null != route) { webContext.setRoute(route); } else { throw new NotFoundException(uri);
private FullHttpResponse buildResponse(WebContext webContext) { WebContext.set(webContext); return routeHandler.handleResponse( webContext.getRequest(), webContext.getResponse(), webContext.getChannelHandlerContext() ); }
@Override public void close() throws IOException { try { this.flush(); FileChannel file = new FileInputStream(this.file).getChannel(); long fileLength = file.size(); HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength); httpResponse.headers().set(HttpConst.DATE, DateKit.gmtDate()); httpResponse.headers().set(HttpConst.SERVER, "blade/" + Const.VERSION); boolean keepAlive = WebContext.request().keepAlive(); if (keepAlive) { httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(httpResponse); ctx.write(new DefaultFileRegion(file, 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } finally { if(null != outputStream){ outputStream.close(); } } }
/** * Get application environment information. * * @param key environment key * @param defaultValue default value, if value is null * @return environment optional value */ public String env(String key, String defaultValue) { return blade().env(key, defaultValue); }
@Override public void handle(Exception e) { if (!ExceptionHandler.isResetByPeer(e)) { var response = WebContext.response(); var request = WebContext.request(); if (e instanceof BladeException) { this.handleBladeException((BladeException) e, request, response); } else if (ValidatorException.class.isInstance(e)) { this.handleValidators(ValidatorException.class.cast(e), request, response); } else { this.handleException(e, request, response); } } }