com.blade.mvc.WebContext Java Examples

The following examples show how to use com.blade.mvc.WebContext. 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: App.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) {

        Blade.of()
            .get("/", ctx -> ctx.render("index.html"))
            .get("/basic-route-example", ctx -> ctx.text("GET called"))
            .post("/basic-route-example", ctx -> ctx.text("POST called"))
            .put("/basic-route-example", ctx -> ctx.text("PUT called"))
            .delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
            .addStatics("/custom-static")
            // .showFileList(true)
            .enableCors(true)
            .before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
            .on(EventType.SERVER_STARTED, e -> {
                String version = WebContext.blade()
                    .env("app.version")
                    .orElse("N/D");
                log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
            })
            .on(EventType.SESSION_CREATED, e -> {
                Session session = (Session) e.attribute("session");
                session.attribute("mySessionValue", "Baeldung");
            })
            .use(new BaeldungMiddleware())
            .start(App.class, args);
    }
 
Example #2
Source File: NettyServer.java    From blade with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
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 #4
Source File: HttpServerHandler.java    From blade with Apache License 2.0 6 votes vote down vote up
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()
    );
}
 
Example #5
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 #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: 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 #8
Source File: NettyServer.java    From blade with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #9
Source File: RouteMethodHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private boolean invokeMiddleware(List<Route> middleware, RouteContext context) throws BladeException {
    if (BladeKit.isEmpty(middleware)) {
        return true;
    }
    for (Route route : middleware) {
        WebHook webHook = (WebHook) WebContext.blade().ioc().getBean(route.getTargetType());
        boolean flag    = webHook.before(context);
        if (!flag) return false;
    }
    return true;
}
 
Example #10
Source File: RouteMethodHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(WebContext webContext) throws Exception {
    RouteContext context = new RouteContext(webContext.getRequest(), webContext.getResponse());

    // if execution returns false then execution is interrupted
    String uri   = context.uri();
    Route  route = webContext.getRoute();
    if (null == route) {
        throw new NotFoundException(context.uri());
    }

    // init route, request parameters, route action method and parameter.
    context.initRoute(route);

    // execution middleware
    if (hasMiddleware && !invokeMiddleware(routeMatcher.getMiddleware(), context)) {
        return;
    }
    context.injectParameters();

    // web hook before
    if (hasBeforeHook && !invokeHook(routeMatcher.getBefore(uri), context)) {
        return;
    }

    // execute
    this.routeHandle(context);

    // webHook
    if (hasAfterHook) {
        this.invokeHook(routeMatcher.getAfter(uri), context);
    }
}
 
Example #11
Source File: HttpServerHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private boolean isStaticFile(String method, String uri) {
    if (HttpMethod.POST.name().equals(method) || notStaticUri.contains(uri)) {
        return false;
    }

    if (WebContext.blade().getStatics().stream().noneMatch(s -> s.equals(uri) || uri.startsWith(s))) {
        notStaticUri.add(uri);
        return false;
    }
    return true;
}
 
Example #12
Source File: GolbalExceptionHandler.java    From tale with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: HttpServerHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private FullHttpResponse buildResponse(WebContext webContext) {
    WebContext.set(webContext);
    return routeHandler.handleResponse(
            webContext.getRequest(), webContext.getResponse(),
            webContext.getChannelHandlerContext()
    );
}
 
Example #14
Source File: HttpServerHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private WebContext buildWebContext(ChannelHandlerContext ctx,
                                   HttpRequest req) {

    String remoteAddress = ctx.channel().remoteAddress().toString();
    req.init(remoteAddress);
    return WebContext.create(req, new HttpResponse(), ctx);
}
 
Example #15
Source File: OutputStreamWrapper.java    From blade with Apache License 2.0 5 votes vote down vote up
@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();
        }
    }
}
 
Example #16
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 #17
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 #18
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 #19
Source File: LoadConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void load(Blade blade) {
    String version = WebContext.blade()
        .env("app.version")
        .orElse("N/D");
    String authors = WebContext.blade()
        .env("app.authors", "Unknown authors");

    log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
}
 
Example #20
Source File: DefaultExceptionHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #21
Source File: GlobalExceptionHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handle(Exception e) {
    if (e instanceof BaeldungException) {
        Exception baeldungException = (BaeldungException) e;
        String msg = baeldungException.getMessage();
        log.error("[GlobalExceptionHandler] Intercepted an exception to threat with additional logic. Error message: " + msg);
        WebContext.response()
            .render("index.html");

    } else {
        super.handle(e);
    }
}
 
Example #22
Source File: SessionHandler.java    From blade with Apache License 2.0 5 votes vote down vote up
private Session getSession(Request request) {
    String cookieHeader = request.cookie(WebContext.sessionKey());
    if (StringKit.isEmpty(cookieHeader)) {
        return null;
    }
    return sessionManager.getSession(cookieHeader);
}
 
Example #23
Source File: SimpleIoc.java    From blade with Apache License 2.0 5 votes vote down vote up
@Override
public Object createBean(Class<?> type) {
    BeanDefine beanDefine = createBeanDefine(type, true);
    IocKit.initInjection(this, Objects.requireNonNull(beanDefine));
    IocKit.injectionValue(WebContext.blade().environment(), beanDefine);
    return beanDefine.getBean();
}
 
Example #24
Source File: HttpServerHandler.java    From blade with Apache License 2.0 4 votes vote down vote up
private WebContext executeLogic(WebContext webContext) {
    try {
        WebContext.set(webContext);
        Request request = webContext.getRequest();
        String method = request.method();
        String uri = request.uri();
        Instant start = null;

        if (ALLOW_COST && !PERFORMANCE) {
            start = Instant.now();
        }

        if (isStaticFile(method, 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);
                }
                routeHandler.handle(webContext);
            }

            if (PERFORMANCE) {
                return webContext;
            }

            if (ALLOW_COST) {
                long cost = log200AndCost(log, start, BladeCache.getPaddingMethod(method), uri);
                request.attribute(REQUEST_COST_TIME, cost);
            } else {
                log200(log, BladeCache.getPaddingMethod(method), uri);
            }
        }
        return webContext;
    } catch (Exception e) {
        throw BladeException.wrapper(e);
    }
}
 
Example #25
Source File: Event.java    From blade with Apache License 2.0 4 votes vote down vote up
public Environment environment() {
    return WebContext.blade().environment();
}
 
Example #26
Source File: HttpRequest.java    From blade with Apache License 2.0 4 votes vote down vote up
public void init(String remoteAddress) {
    this.remoteAddress = remoteAddress.substring(1);
    this.keepAlive = HttpUtil.isKeepAlive(nettyRequest);
    this.url = nettyRequest.uri();

    int pathEndPos = this.url().indexOf('?');
    this.uri = pathEndPos < 0 ? this.url() : this.url().substring(0, pathEndPos);
    this.protocol = nettyRequest.protocolVersion().text();
    this.method = nettyRequest.method().name();

    String cleanUri = this.uri;
    if (!"/".equals(this.contextPath())) {
        cleanUri = PathKit.cleanPath(cleanUri.replaceFirst(this.contextPath(), "/"));
        this.uri = cleanUri;
    }

    this.httpHeaders = nettyRequest.headers();

    if (!HttpServerHandler.PERFORMANCE) {
        SessionManager sessionManager = WebContext.blade().sessionManager();
        if (null != sessionManager) {
            this.session = SESSION_HANDLER.createSession(this);
        }
    }

    if ("GET".equals(this.method())) {
        return;
    }

    try {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, nettyRequest);
        this.isMultipart = decoder.isMultipart();

        List<ByteBuf> byteBuffs = new ArrayList<>(this.contents.size());

        for (HttpContent content : this.contents) {
            if (!isMultipart) {
                byteBuffs.add(content.content().copy());
            }

            decoder.offer(content);
            this.readHttpDataChunkByChunk(decoder);
            content.release();
        }
        if (!byteBuffs.isEmpty()) {
            this.body = Unpooled.copiedBuffer(byteBuffs.toArray(new ByteBuf[0]));
        }
    } catch (Exception e) {
        throw new HttpParseException("build decoder fail", e);
    }
}
 
Example #27
Source File: DefaultExceptionHandler.java    From blade with Apache License 2.0 4 votes vote down vote up
protected void handleBladeException(BladeException e, Request request, Response response) {
    var blade = WebContext.blade();
    response.status(e.getStatus());

    var modelAndView = new ModelAndView();
    modelAndView.add("title", e.getStatus() + " " + e.getName());
    modelAndView.add("message", e.getMessage());

    if (null != e.getCause()) {
        request.attribute(VARIABLE_STACKTRACE, getStackTrace(e));
    }

    if (e.getStatus() == InternalErrorException.STATUS) {
        log.error("", e);
        this.render500(request, response);
    }

    String paddingMethod = BladeCache.getPaddingMethod(request.method());

    if (e.getStatus() == NotFoundException.STATUS) {
        log404(log, paddingMethod, request.uri());

        if (request.isJsonRequest()) {
            response.json(RestResponse.fail(NotFoundException.STATUS, "Not Found [" + request.uri() + "]"));
        } else {
            var page404 = Optional.ofNullable(blade.environment().get(ENV_KEY_PAGE_404, null));
            if (page404.isPresent()) {
                modelAndView.setView(page404.get());
                renderPage(response, modelAndView);
                response.render(page404.get());
            } else {
                HtmlCreator htmlCreator = new HtmlCreator();
                htmlCreator.center("<h1>404 Not Found - " + request.uri() + "</h1>");
                htmlCreator.hr();
                response.html(htmlCreator.html());
            }
        }
    }

    if (e.getStatus() == MethodNotAllowedException.STATUS) {

        log405(log, paddingMethod, request.uri());

        if (request.isJsonRequest()) {
            response.json(RestResponse.fail(MethodNotAllowedException.STATUS, e.getMessage()));
        } else {
            response.text(e.getMessage());
        }
    }
}
 
Example #28
Source File: EnvironmentWatcher.java    From blade with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    if (Const.CLASSPATH.endsWith(".jar")) {
        return;
    }

    final Path path = Paths.get(Const.CLASSPATH);
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {

        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        // start an infinite loop
        while (true) {
            final WatchKey key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                final WatchEvent.Kind<?> kind = watchEvent.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }
                // get the filename for the event
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                final String           filename       = watchEventPath.context().toString();
                // print it out
                if (log.isDebugEnabled()) {
                    log.debug("⬢ {} -> {}", kind, filename);
                }
                if (kind == StandardWatchEventKinds.ENTRY_DELETE &&
                        filename.startsWith(".app") && filename.endsWith(".properties.swp")) {
                    // reload env
                    log.info("⬢ Reload environment");

                    Environment environment = Environment.of("classpath:" + filename.substring(1, filename.length() - 4));
                    WebContext.blade().environment(environment);
                    // notify
                    WebContext.blade().eventManager().fireEvent(EventType.ENVIRONMENT_CHANGED, new Event().attribute("environment", environment));
                }
            }
            // reset the keyf
            boolean valid = key.reset();
            // exit loop if the key is not valid (if the directory was
            // deleted, for
            if (!valid) {
                break;
            }
        }
    } catch (IOException | InterruptedException ex) {
        log.error("Environment watch error", ex);
    }
}
 
Example #29
Source File: Request.java    From blade with Apache License 2.0 2 votes vote down vote up
/**
 * Get current application contextPath, default is "/"
 *
 * @return Return contextPath
 */
default String contextPath() {
    return WebContext.contextPath();
}
 
Example #30
Source File: RequestHandler.java    From blade with Apache License 2.0 votes vote down vote up
void handle(WebContext webContext) throws Exception;