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());
}
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);
}
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);
}
}
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;
}
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);
}
Aggregations