Search in sources :

Example 16 with Request

use of com.blade.mvc.http.Request in project blade by biezhi.

the class HttpRequestTest method testIsSecure.

@Test
public void testIsSecure() {
    Request mockRequest = mockHttpRequest("GET");
    when(mockRequest.isSecure()).thenReturn(false);
    assertEquals(Boolean.FALSE, mockRequest.isSecure());
}
Also used : HttpRequest(com.blade.mvc.http.HttpRequest) Request(com.blade.mvc.http.Request) Test(org.junit.Test)

Example 17 with Request

use of com.blade.mvc.http.Request in project blade by biezhi.

the class StaticFileHandler method handle.

/**
 * print static file to client
 *
 * @param webContext web context
 * @throws Exception
 */
@Override
public void handle(WebContext webContext) throws Exception {
    Request request = webContext.getRequest();
    ChannelHandlerContext ctx = webContext.getChannelHandlerContext();
    if (!HttpConst.METHOD_GET.equals(request.method())) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    Instant start = Instant.now();
    String uri = URLDecoder.decode(request.uri(), "UTF-8");
    String method = StringKit.padRight(request.method(), 6);
    String cleanURL = getCleanURL(request, uri);
    // webjars
    if (cleanURL.startsWith(Const.WEB_JARS)) {
        InputStream input = getResourceStreamFromJar(uri);
        writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
        return;
    }
    // jar file
    if (BladeKit.runtimeIsJAR()) {
        InputStream input = StaticFileHandler.class.getResourceAsStream(cleanURL);
        writeWithJarFile(request, ctx, uri, start, cleanURL, method, input);
        return;
    }
    // disk file
    final String path = sanitizeUri(cleanURL);
    if (path == null) {
        log403(log, method, uri);
        throw new ForbiddenException();
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        // gradle resources path
        File resourcesDirectory = getGradleResourcesDirectory();
        if (resourcesDirectory.isDirectory()) {
            file = new File(resourcesDirectory.getPath() + "/" + cleanURL.substring(1));
            if (file.isHidden() || !file.exists()) {
                throw new NotFoundException(uri);
            }
        } else {
            throw new NotFoundException(uri);
        }
    }
    if (file.isDirectory() && showFileList) {
        sendListing(ctx, uri, getFileMetas(file), cleanURL);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    // Cache Validation
    if (isHttp304(ctx, request, file.length(), file.lastModified())) {
        log304(log, method, uri);
        return;
    }
    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    setContentTypeHeader(httpResponse, file);
    setDateAndCacheHeaders(httpResponse, file);
    if (request.useGZIP()) {
        File output = new File(file.getPath() + ".gz");
        IOKit.compressGZIP(file, output);
        file = output;
        setGzip(httpResponse);
    }
    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();
    httpResponse.headers().set(HttpConst.CONTENT_LENGTH, fileLength);
    if (request.keepAlive()) {
        httpResponse.headers().set(HttpConst.CONNECTION, HttpConst.KEEP_ALIVE);
    }
    // Write the initial line and the header.
    ctx.write(httpResponse);
    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }
    sendFileFuture.addListener(ProgressiveFutureListener.build(raf));
    // Decide whether to close the connection or not.
    if (!request.keepAlive()) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
    log200AndCost(log, start, method, uri);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ForbiddenException(com.blade.exception.ForbiddenException) Instant(java.time.Instant) ChunkedFile(io.netty.handler.stream.ChunkedFile) Request(com.blade.mvc.http.Request) NotFoundException(com.blade.exception.NotFoundException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultFileRegion(io.netty.channel.DefaultFileRegion) SslHandler(io.netty.handler.ssl.SslHandler) ChunkedFile(io.netty.handler.stream.ChunkedFile) JarFile(java.util.jar.JarFile)

Example 18 with Request

use of com.blade.mvc.http.Request in project blade by biezhi.

the class DefaultEngine method render.

@Override
public void render(ModelAndView modelAndView, Writer writer) throws TemplateException {
    String view = modelAndView.getView();
    String body;
    String viewPath;
    if (Const.CLASSPATH.endsWith(PATH_SEPARATOR)) {
        viewPath = Const.CLASSPATH + TEMPLATE_PATH + PATH_SEPARATOR + view;
    } else {
        viewPath = Const.CLASSPATH + PATH_SEPARATOR + TEMPLATE_PATH + PATH_SEPARATOR + view;
    }
    try {
        if (view.startsWith("jar:")) {
            String jarPath = view.substring(4);
            InputStream input = DefaultEngine.class.getResourceAsStream(jarPath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            body = IOKit.readToString(reader);
        } else {
            if (BladeKit.runtimeIsJAR()) {
                viewPath = PATH_SEPARATOR + TEMPLATE_PATH + PATH_SEPARATOR + view;
                InputStream in = getClass().getResourceAsStream(viewPath);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                body = IOKit.readToString(reader);
            } else {
                body = IOKit.readToString(viewPath);
            }
        }
        Request request = WebContext.request();
        Map<String, Object> attributes = new HashMap<>();
        Map<String, Object> reqAttrs = request.attributes();
        attributes.putAll(reqAttrs);
        attributes.putAll(modelAndView.getModel());
        Session session = request.session();
        if (null != session) {
            attributes.putAll(session.attributes());
        }
        String result = BladeTemplate.template(body, attributes).fmt();
        writer.write(result);
    } catch (Exception e) {
        log.warn("View path is: {}", viewPath);
        throw new TemplateException(e);
    } finally {
        IOKit.closeQuietly(writer);
    }
}
Also used : HashMap(java.util.HashMap) TemplateException(com.blade.exception.TemplateException) Request(com.blade.mvc.http.Request) TemplateException(com.blade.exception.TemplateException) Session(com.blade.mvc.http.Session)

Example 19 with Request

use of com.blade.mvc.http.Request in project blade by biezhi.

the class ServletResponse method json.

@Override
public Response json(String json) {
    Request request = WebContextHolder.request();
    String userAgent = request.userAgent();
    if (userAgent.contains("MSIE")) {
        this.contentType("text/html;charset=utf-8");
    } else {
        this.contentType("application/json;charset=utf-8");
    }
    try {
        this.header("Cache-Control", "no-cache");
        DispatchKit.print(json, response.getWriter());
        this.written = true;
        return this;
    } catch (UnsupportedEncodingException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : Request(com.blade.mvc.http.Request) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 20 with Request

use of com.blade.mvc.http.Request in project blade by biezhi.

the class RouteActionArguments method getHeader.

private static Object getHeader(ParamStruct paramStruct) throws BladeException {
    Type argType = paramStruct.argType;
    HeaderParam headerParam = paramStruct.headerParam;
    String paramName = paramStruct.paramName;
    Request request = paramStruct.request;
    String key = StringKit.isEmpty(headerParam.value()) ? paramName : headerParam.value();
    String val = request.header(key);
    if (StringKit.isBlank(val)) {
        val = headerParam.defaultValue();
    }
    return ReflectKit.convert(argType, val);
}
Also used : Request(com.blade.mvc.http.Request)

Aggregations

Request (com.blade.mvc.http.Request)29 HttpRequest (com.blade.mvc.http.HttpRequest)18 Test (org.junit.Test)18 HashMap (java.util.HashMap)7 CaseInsensitiveHashMap (com.blade.kit.CaseInsensitiveHashMap)5 WebContext (com.blade.mvc.WebContext)3 Response (com.blade.mvc.http.Response)3 RouteContext (com.blade.mvc.RouteContext)2 AuthOption (com.blade.security.web.auth.AuthOption)2 BasicAuthMiddleware (com.blade.security.web.auth.BasicAuthMiddleware)2 ForbiddenException (com.blade.exception.ForbiddenException)1 NotFoundException (com.blade.exception.NotFoundException)1 TemplateException (com.blade.exception.TemplateException)1 Session (com.blade.mvc.http.Session)1 FileItem (com.blade.mvc.multipart.FileItem)1 Contents (com.tale.model.entity.Contents)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 DefaultFileRegion (io.netty.channel.DefaultFileRegion)1 SslHandler (io.netty.handler.ssl.SslHandler)1