List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
From source file:fileShare.ShareHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }// w w w . j a va2 s .co m //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { System.out.println( "==================================HttpContent=================================="); //? System.out.println(new String(((DefaultHttpContent) chunk).content().array())); blockingFile.put(chunk.copy()); decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; send = false; reset(); } } } }
From source file:gribbit.http.request.decoder.HttpRequestDecoder.java
License:Open Source License
/** Decode an HTTP message. */ @Override/*from w w w. j a v a 2 s. c o m*/ public void messageReceived(ChannelHandlerContext ctx, Object msg) { try { Log.info("Got message of type " + msg.getClass().getName()); if (msg instanceof HttpRequest) { // Got a new HTTP request -- decode HTTP headers HttpRequest httpReq = (HttpRequest) msg; if (!httpReq.decoderResult().isSuccess()) { throw new BadRequestException(null); } // Free resources to avoid DoS attack by sending repeated unterminated requests freeResources(); // Parse the HttpRequest fields. request = new Request(ctx, httpReq); // Handle expect-100-continue List<CharSequence> allExpectHeaders = httpReq.headers().getAll(EXPECT); for (int i = 0; i < allExpectHeaders.size(); i++) { String h = allExpectHeaders.get(i).toString(); if (h.equalsIgnoreCase("100-continue")) { ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE, Unpooled.EMPTY_BUFFER)); return; } } if (httpReq.method() == HttpMethod.POST) { // Start decoding HttpContent chunks. freeResources(); postRequestDecoder = new HttpPostRequestDecoder(httpDataFactory, httpReq); } } if (msg instanceof LastHttpContent || msg instanceof FullHttpRequest) { // Reached end of HTTP request if (request != null) { // Check for WebSocket upgrade request if (!tryWebSocketHandlers(ctx, request.getHttpRequest())) { // This is a regular HTTP request -- find a handler for the request tryHttpRequestHandlers(ctx); } // After the last content message has been processed, free resources freeResources(); } } else if (msg instanceof HttpContent) { // Decode HTTP POST body HttpContent chunk = (HttpContent) msg; if (!chunk.decoderResult().isSuccess()) { throw new BadRequestException(null); } handlePOSTChunk(chunk); } else if (msg instanceof WebSocketFrame) { // Handle WebSocket frame if (webSocketHandler == null) { // Connection was never upgraded to websocket throw new BadRequestException(); } WebSocketFrame frame = (WebSocketFrame) msg; handleWebSocketFrame(ctx, frame); } } catch (Exception e) { exceptionCaught(ctx, e); } }
From source file:holon.internal.http.netty.HttpUploadServerHandlerTempl.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);/*from www.ja v a 2s . c o m*/ return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); if (request.getMethod().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:holon.internal.http.netty.NettyServerHandler.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (request.getMethod().equals(HttpMethod.GET)) { // No more work to do here, we will get a follow-up message which will trigger the else branch // at the bottom of this method. return; }/*from ww w . j a v a2 s. co m*/ try { formParams = new HashMap<>(); decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); ctx.channel().close(); return; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); ctx.channel().close(); return; } // example of reading chunk by chunk (minimize memory usage due to Factory) readFormUploadChunked(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { ringBuffer.publishEvent(NettyServerHandler::translate, request, ctx.channel(), formParams); reset(); } } } else { ringBuffer.publishEvent(NettyServerHandler::translate, request, ctx.channel(), formParams); } }
From source file:io.advantageous.conekt.http.impl.HttpServerRequestImpl.java
License:Open Source License
@Override public HttpServerRequest setExpectMultipart(boolean expect) { synchronized (conn) { checkEnded();/*from ww w.j a va2 s. c o m*/ if (expect) { if (decoder == null) { String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); if (contentType != null) { HttpMethod method = request.getMethod(); String lowerCaseContentType = contentType.toLowerCase(); boolean isURLEncoded = lowerCaseContentType .startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); if ((lowerCaseContentType.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA) || isURLEncoded) && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH) || method.equals(HttpMethod.DELETE))) { decoder = new HttpPostRequestDecoder(new DataFactory(), request); } } } } else { decoder = null; } return this; } }
From source file:io.aos.netty5.http.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);/*from w w w .ja v a 2 s .c o m*/ return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpHeaderUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:io.jsync.http.impl.DefaultHttpServerRequest.java
License:Open Source License
@Override public HttpServerRequest expectMultiPart(boolean expect) { if (expect) { String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE); if (contentType != null) { HttpMethod method = request.method(); AsciiString lowerCaseContentType = new AsciiString(contentType.toLowerCase()); boolean isURLEncoded = lowerCaseContentType .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED); if ((lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA) || isURLEncoded) && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH))) { decoder = new HttpPostRequestDecoder(new DataFactory(), request); }/*from ww w. j a v a 2s . c om*/ } } else { decoder = null; } return this; }
From source file:io.nebo.container.ServletContentHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; log.info("uri" + request.getUri()); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false); NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response); servletRequest = new NettyHttpServletRequest(ctx, servletContext, request, inputStream, servletResponse);//w w w . j a va 2 s . c o m if (HttpMethod.GET.equals(request.getMethod())) { HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE), ctx.voidPromise()); } ctx.fireChannelRead(servletRequest); } else if (HttpMethod.POST.equals(request.getMethod())) { decoder = new HttpPostRequestDecoder(factory, request); } } if (decoder != null && msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; log.info("HttpContent" + chunk.content().readableBytes()); inputStream.addContent(chunk); List<InterfaceHttpData> interfaceHttpDatas = decoder.getBodyHttpDatas(); for (InterfaceHttpData data : interfaceHttpDatas) { try { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) data; Map<String, String[]> params = servletRequest.getParameterMap(); HttpRequestUtils.setParamMap(attribute.getName(), attribute.getValue(), params); } } finally { // data.release(); } } } if (decoder != null && msg instanceof LastHttpContent) { ctx.fireChannelRead(servletRequest); reset(); } }
From source file:io.netty.example.http.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//from ww w. jav a 2s. co m return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create an HttpPostRequestDecoder if (HttpMethod.GET.equals(request.method())) { // GET Method: should not try to create an HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel(), true); return; } boolean readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel(), true); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:io.vertx.core.http.impl.Http2ServerRequestImpl.java
License:Open Source License
@Override public HttpServerRequest setExpectMultipart(boolean expect) { synchronized (conn) { checkEnded();//from w w w .j av a 2 s . c o m if (expect) { if (postRequestDecoder == null) { CharSequence contentType = headers.get(HttpHeaderNames.CONTENT_TYPE); if (contentType != null) { io.netty.handler.codec.http.HttpMethod method = io.netty.handler.codec.http.HttpMethod .valueOf(headers.method().toString()); String lowerCaseContentType = contentType.toString().toLowerCase(); boolean isURLEncoded = lowerCaseContentType .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()); if ((lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()) || isURLEncoded) && (method == io.netty.handler.codec.http.HttpMethod.POST || method == io.netty.handler.codec.http.HttpMethod.PUT || method == io.netty.handler.codec.http.HttpMethod.PATCH || method == io.netty.handler.codec.http.HttpMethod.DELETE)) { HttpRequest req = new DefaultHttpRequest( io.netty.handler.codec.http.HttpVersion.HTTP_1_1, method, headers.path().toString()); req.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType); postRequestDecoder = new HttpPostRequestDecoder( new NettyFileUploadDataFactory(vertx, this, () -> uploadHandler), req); } } } } else { postRequestDecoder = null; } } return this; }