List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
From source file:org.kaaproject.kaa.server.transports.http.transport.commands.AbstractHttpSyncCommand.java
License:Apache License
@Override public void parse() throws Exception { LOG.trace("CommandName: " + COMMAND_NAME + ": Parse.."); HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, getRequest()); if (decoder.isMultipart()) { LOG.trace("Chunked: " + HttpHeaders.isTransferEncodingChunked(getRequest())); LOG.trace(": Multipart.."); List<InterfaceHttpData> datas = decoder.getBodyHttpDatas(); if (!datas.isEmpty()) { for (InterfaceHttpData data : datas) { LOG.trace("Multipart1 name " + data.getName() + " type " + data.getHttpDataType().name()); if (data.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) data; if (CommonEpConstans.REQUEST_SIGNATURE_ATTR_NAME.equals(data.getName())) { requestSignature = attribute.get(); if (LOG.isTraceEnabled()) { LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " Signature set. size: " + requestSignature.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestSignature)); }//from ww w. j a v a 2s. co m } else if (CommonEpConstans.REQUEST_KEY_ATTR_NAME.equals(data.getName())) { requestKey = attribute.get(); if (LOG.isTraceEnabled()) { LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " requestKey set. size: " + requestKey.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestKey)); } } else if (CommonEpConstans.REQUEST_DATA_ATTR_NAME.equals(data.getName())) { requestData = attribute.get(); if (LOG.isTraceEnabled()) { LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " requestData set. size: " + requestData.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestData)); } } else if (CommonEpConstans.NEXT_PROTOCOL_ATTR_NAME.equals(data.getName())) { nextProtocol = ByteBuffer.wrap(attribute.get()).getInt(); LOG.trace("[{}] next protocol is {}", getSessionUuid(), nextProtocol); } } } } else { LOG.error("Multipart.. size 0"); throw new BadRequestException("HTTP Request inccorect, multiprat size is 0"); } } }
From source file:org.pidome.server.system.network.http.HttpRequestHandler.java
/** * Process the request made for http2/* w ww . java 2 s . c o m*/ * * @param chc The channel context. * @param request The url request. * @param writer The output writer of type HttpRequestWriterInterface. * @param streamId The stream Id in case of http2, when http1 leave null. */ protected static void processManagement(ChannelHandlerContext chc, FullHttpRequest request, HttpRequestWriterInterface writer, String streamId) { String plainIp = getPlainIp(chc.channel().remoteAddress()); String localIp = getPlainIp(chc.channel().localAddress()); int localPort = getPort(chc.channel().localAddress()); try { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); String fileRequest = queryStringDecoder.path(); if (fileRequest.equals("/")) { fileRequest = "/index.html"; } else if (fileRequest.endsWith("/")) { fileRequest = fileRequest + "index.html"; } String nakedfile = fileRequest.substring(1, fileRequest.lastIndexOf(".")); String fileType = fileRequest.substring(fileRequest.lastIndexOf(".") + 1); String loginError = ""; RemoteClientInterface client = null; RemoteClient remoteClient = null; WebRenderInterface renderClass = null; try { Set<Cookie> cookie = cookieParser(request); Map<RemoteClientInterface, RemoteClient> clientSet = getAuthorizedClient(request, plainIp, (cookie.isEmpty() ? "" : ((Cookie) cookie.toArray()[0]).getValue()), fileRequest); client = clientSet.keySet().iterator().next(); remoteClient = clientSet.get(client); } catch (Exception ex) { if (ex instanceof HttpClientNotAuthorizedException) { LOG.error("Not authorized at {}", plainIp, request.uri()); loginError = "Not authorized or bad username/password"; } else if (ex instanceof HttpClientLoggedInOnOtherLocationException) { LOG.error("Not authorized at {} (Logged in on other location: {}!)", plainIp, ex.getMessage()); loginError = "Client seems to be already logged in on another location"; } else { LOG.error("Not authorized at: {} (Cookie problem? ({}))", ex, ex.getMessage(), ex); loginError = "Problem getting authentication data, refer to log file"; } if (!request.uri().equals("/jsonrpc.json")) { fileType = "xhtml"; nakedfile = "login"; fileRequest = "/login.xhtml"; } } if (!fileType.isEmpty()) { switch (fileType) { case "xhtml": case "json": case "upload": case "xml": case "/": if (request.uri().startsWith("/jsonrpc.json")) { renderClass = getJSONRPCRenderer(request); } else if (request.uri().startsWith("/xmlapi/")) { /// This is a temp solution until the xml output has been transfered to the json rpc api. Class classToLoad = Class.forName( HttpServer.getXMLClassesRoot() + nakedfile.replace("xmlapi/", ".Webclient_")); renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance(); } else { Class classToLoad = Class .forName(HttpServer.getDocumentClassRoot() + nakedfile.replace("/", ".Webclient_")); renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance(); } renderClass.setHostData(localIp, localPort, plainIp); renderClass.setRequestData(queryStringDecoder.parameters()); Map<String, String> postData = new HashMap<>(); Map<String, byte[]> fileMap = new HashMap<>(); if (request.method().equals(HttpMethod.POST)) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), request); decoder.setDiscardThreshold(0); if (request instanceof HttpContent) { HttpContent chunk = (HttpContent) request; decoder.offer(chunk); try { while (decoder.hasNext()) { InterfaceHttpData data = decoder.next(); if (data != null) { if (data.getHttpDataType() .equals(InterfaceHttpData.HttpDataType.Attribute)) { postData.put(data.getName(), ((HttpData) data).getString()); } else if (data.getHttpDataType() .equals(InterfaceHttpData.HttpDataType.FileUpload)) { FileUpload fileUpload = (FileUpload) data; fileMap.put(fileUpload.getFilename(), fileUpload.get()); } } } } catch (HttpPostRequestDecoder.EndOfDataDecoderException e1) { } if (chunk instanceof LastHttpContent) { decoder.destroy(); decoder = null; } } } renderClass.setPostData(postData); renderClass.setFileData(fileMap); renderClass.setLoginData(client, remoteClient, loginError); renderClass.collect(); renderClass.setTemplate(fileRequest); ByteArrayOutputStream outputWriter = new ByteArrayOutputStream(); renderClass.setOutputStream(outputWriter); String output = renderClass.render(); outputWriter.close(); writer.writeResponse(chc, HttpResponseStatus.OK, output.getBytes(), fileType, streamId, false); break; default: sendStaticFile(chc, writer, fileRequest, queryStringDecoder, streamId); break; } } } catch (ClassNotFoundException | Webservice404Exception ex) { LOG.warn("404 error: {} - {} (by {})", ex.getMessage(), ex, plainIp); try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) { ex.printStackTrace(pw); writer.writeResponse(chc, HttpResponseStatus.NOT_FOUND, return404Error().getBytes(), "html", streamId, false); } catch (IOException exWriters) { LOG.error("Problem outputting 404 error: {}", exWriters.getMessage(), exWriters); } } catch (Exception ex) { LOG.error("500 error: {}", ex.getLocalizedMessage(), ex); try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) { ex.printStackTrace(pw); String errorOutput = sw.toString() + "\n\n" + getRandQuote(); writer.writeResponse(chc, HttpResponseStatus.INTERNAL_SERVER_ERROR, (errorOutput + "<br/><br/><p>" + getRandQuote() + "</p>").getBytes(), "", streamId, false); } catch (IOException exWriters) { LOG.error("Problem outputting 500 error: {}", exWriters.getMessage(), exWriters); } } }
From source file:org.vertx.java.core.http.impl.DefaultHttpServerRequest.java
License:Open Source License
@Override public HttpServerRequest expectMultiPart(boolean expect) { if (expect) { String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); if (contentType != null) { HttpMethod method = request.getMethod(); String lowerCaseContentType = contentType.toLowerCase(); 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))) { decoder = new HttpPostRequestDecoder(new DataFactory(), request); }//www. ja v a 2 s .c o m } } else { decoder = null; } return this; }
From source file:org.waarp.gateway.kernel.http.HttpRequestHandler.java
License:Open Source License
/** * Method that get post data//from w w w . java2 s . c om * * @param ctx * @throws HttpIncorrectRequestException */ protected void post(ChannelHandlerContext ctx) throws HttpIncorrectRequestException { try { decoder = new HttpPostRequestDecoder(HttpBusinessFactory.factory, request); } catch (ErrorDataDecoderException e1) { status = HttpResponseStatus.NOT_ACCEPTABLE; throw new HttpIncorrectRequestException(e1); } catch (Exception e1) { // GETDOWNLOAD Method: should not try to create a HttpPostRequestDecoder // So OK but stop here status = HttpResponseStatus.NOT_ACCEPTABLE; throw new HttpIncorrectRequestException(e1); } if (request instanceof FullHttpRequest) { // Not chunk version readHttpDataAllReceive(ctx); finalData(ctx); writeSimplePage(ctx); clean(); } }
From source file:org.waarp.gateway.kernel.rest.HttpRestHandler.java
License:Open Source License
/** * Create the decoder/* www .j a va 2 s. c om*/ * * @throws HttpIncorrectRequestException */ protected void createDecoder() throws HttpIncorrectRequestException { HttpMethod method = request.method(); if (!method.equals(HttpMethod.HEAD)) { // in order decoder allows to parse request.setMethod(HttpMethod.POST); } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { status = HttpResponseStatus.NOT_ACCEPTABLE; throw new HttpIncorrectRequestException(e1); } catch (Exception e1) { // GETDOWNLOAD Method: should not try to create a HttpPostRequestDecoder // So OK but stop here status = HttpResponseStatus.NOT_ACCEPTABLE; throw new HttpIncorrectRequestException(e1); } }
From source file:org.wisdom.engine.server.WisdomHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, HttpObject req) { if (req instanceof HttpRequest) { request = (HttpRequest) req;/*from w ww . j ava 2s . co m*/ context = new ContextFromNetty(accessor, ctx, request); switch (handshake(ctx)) { case HANDSHAKE_UNSUPPORTED: CommonResponses.sendUnsupportedWebSocketVersionResponse(ctx.channel()); return; case HANDSHAKE_ERROR: CommonResponses.sendWebSocketHandshakeErrorResponse(ctx.channel()); return; case HANDSHAKE_OK: // Handshake ok, just return return; case NO_HANDSHAKE: default: // No handshake attempted, continue. break; } } if (req instanceof HttpContent) { // Only valid for put and post. if (request.getMethod().equals(HttpMethod.POST) || request.getMethod().equals(HttpMethod.PUT)) { if (decoder == null) { decoder = new HttpPostRequestDecoder(DATA_FACTORY, request); } context.decodeContent(request, (HttpContent) req, decoder); } } if (req instanceof LastHttpContent) { // End of transmission. boolean isAsync = dispatch(context, ctx); if (!isAsync) { cleanup(); } } }
From source file:test.httpupload.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 w w w. j a v a 2 s .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(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"); 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 { System.out.println("=============================================" + count.incrementAndGet()); } } } }