List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:uk.co.thinkofdeath.thinkcraft.bukkit.web.ResourcesServer.java
License:Apache License
@Override public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception { File file = new File(plugin.getResourceDir(), uri.getPath().substring("/resources/".length())); if (!file.exists()) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); return;//from w ww. java2 s. c o m } String modified = request.headers().get(IF_MODIFIED_SINCE); if (modified != null && !modified.isEmpty()) { Date modifiedDate = format.parse(modified); if (modifiedDate.equals(plugin.getStartUpDate())) { sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED)); return; } } ByteBuf buffer; try (InputStream stream = new FileInputStream(file)) { ByteBufOutputStream out = new ByteBufOutputStream(context.alloc().buffer()); IOUtils.copy(stream, out); buffer = out.buffer(); out.close(); } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer); response.headers().set(DATE, format.format(new Date())); response.headers().set(LAST_MODIFIED, format.format(plugin.getStartUpDate())); if (uri.getPath().startsWith("/resources/assets")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.MONTH, 1); response.headers().set(EXPIRES, format.format(calendar.getTime())); response.headers().set(CACHE_CONTROL, "public, max-age=2592000"); } String path = uri.getPath(); String ext = path.substring(path.lastIndexOf('.') + 1); String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain"; if (type.startsWith("text/")) { type += "; charset=UTF-8"; } response.headers().set(CONTENT_TYPE, type); response.headers().add("Access-Control-Allow-Origin", "*"); sendHttpResponse(context, request, response); }