List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder offer
@Override
public InterfaceHttpPostRequestDecoder offer(HttpContent content)
From source file:firebats.http.server.exts.form.Form.java
License:Apache License
private static Form decodeWithContent(Context context, ByteBuf content) { //new DefaultHttpDataFactory(/*useDisk*/true)decoder? //Mix?16K???/* w w w . j a v a 2 s .c om*/ // final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(/*useDisk*/true),toNettyHttpRequest(context.request)); HttpServerRequest<ByteBuf> rxRequest = context.getRequest(); HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, rxRequest.getHttpMethod(), rxRequest.getUri()); for (Map.Entry<String, String> header : rxRequest.getHeaders().entries()) { nettyRequest.headers().add(header.getKey(), header.getValue()); } final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest); HttpContent httpContent = new DefaultHttpContent(content); decoder.offer(httpContent); decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT); Map<String, String> formParams = new LinkedHashMap<>(); Map<String, UploadedFile> files = new LinkedHashMap<>(); try { while (decoder.hasNext()) { InterfaceHttpData data = decoder.next(); if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) { try { Attribute attr = (Attribute) data; if (!formParams.containsKey(data.getName())) { formParams.put(attr.getName(), attr.getValue()); } } catch (IOException e) { Throwables.propagate(e); } finally { //? data.release(); } } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) { try { if (!files.containsKey(data.getName())) { final FileUpload nettyFileUpload = (FileUpload) data; final ByteBuf byteBuf = nettyFileUpload.content(); byteBuf.retain(); context.onComplete(new Action0() { @Override public void call() { if (log.isDebugEnabled()) { log.debug("form upload file release[" + data.getName() + ":" + nettyFileUpload.getFilename() + "]"); } byteBuf.release(); } }); UploadedFile fileUpload = new UploadedFile(nettyFileUpload.getFilename(), nettyFileUpload.getContentType(), byteBuf); files.put(data.getName(), fileUpload); } } finally { data.release(); } } } } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) { // ignore } finally { decoder.destroy(); } Map<String, String> query = Form.toFlatQueryParams(context.getRequest().getQueryParameters()); return fromAll(query, formParams, files); }
From source file:org.pidome.server.system.network.http.HttpRequestHandler.java
/** * Process the request made for http2/*from w ww. j ava 2 s . c om*/ * * @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.wisdom.engine.wrapper.ContextFromNetty.java
License:Apache License
/** * Decodes the content of the request. Notice that the content can be split in several chunk. * * @param req the request//from w w w. java 2 s. c o m * @param content the content * @param decoder the decoder. */ public void decodeContent(HttpRequest req, HttpContent content, HttpPostRequestDecoder decoder) { // Determine whether the content is chunked. boolean readingChunks = HttpHeaders.isTransferEncodingChunked(req); // Offer the content to the decoder. if (readingChunks) { // If needed, read content chunk by chunk. decoder.offer(content); readHttpDataChunkByChunk(decoder); } else { // Else, read content. if (content.content().isReadable()) { // We may have the content in different HTTP message, check if we already have a content. // Issue #257. // To avoid we run out of memory we cut the read body to 100Kb. This can be configured using the // "request.body.max.size" property. boolean exceeded = raw != null && raw.length >= services.getConfiguration() .getIntegerWithDefault("request.body.max.size", 100 * 1024); if (!exceeded) { if (this.raw == null) { this.raw = new byte[content.content().readableBytes()]; int readerIndex = content.content().readerIndex(); content.content().getBytes(readerIndex, this.raw); } else { byte[] bytes = new byte[content.content().readableBytes()]; int readerIndex = content.content().readerIndex(); content.content().getBytes(readerIndex, bytes); this.raw = Bytes.concat(this.raw, bytes); } } } decoder.offer(content); try { for (InterfaceHttpData data : decoder.getBodyHttpDatas()) { readAttributeOrFile(data); } } catch (HttpPostRequestDecoder.NotEnoughDataDecoderException e) { LOGGER.debug("Error when decoding content, not enough data", e); } } }
From source file:ratpack.form.internal.FormDecoder.java
License:Apache License
public static Form parseForm(Context context, TypedData requestBody, MultiValueMap<String, String> base) throws RuntimeException { Request request = context.getRequest(); HttpMethod method = io.netty.handler.codec.http.HttpMethod.valueOf(request.getMethod().getName()); HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri()); nettyRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, request.getBody().getContentType().toString()); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest); HttpContent content = new DefaultHttpContent(requestBody.getBuffer()); decoder.offer(content); decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT); Map<String, List<String>> attributes = new LinkedHashMap<>(base.getAll()); Map<String, List<UploadedFile>> files = new LinkedHashMap<>(); try {/*w ww . ja v a 2s . c o m*/ InterfaceHttpData data = decoder.next(); while (data != null) { if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) { List<String> values = attributes.get(data.getName()); if (values == null) { values = new ArrayList<>(1); attributes.put(data.getName(), values); } try { values.add(((Attribute) data).getValue()); } catch (IOException e) { throw uncheck(e); } finally { data.release(); } } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) { List<UploadedFile> values = files.get(data.getName()); if (values == null) { values = new ArrayList<>(1); files.put(data.getName(), values); } try { FileUpload nettyFileUpload = (FileUpload) data; final ByteBuf byteBuf = nettyFileUpload.getByteBuf(); byteBuf.retain(); context.onClose(new Action<RequestOutcome>() { @Override public void execute(RequestOutcome thing) throws Exception { byteBuf.release(); } }); MediaType contentType; String rawContentType = nettyFileUpload.getContentType(); if (rawContentType == null) { contentType = null; } else { Charset charset = nettyFileUpload.getCharset(); if (charset == null) { contentType = DefaultMediaType.get(rawContentType); } else { contentType = DefaultMediaType.get(rawContentType + ";charset=" + charset); } } UploadedFile fileUpload = new DefaultUploadedFile( new ByteBufBackedTypedData(byteBuf, contentType), nettyFileUpload.getFilename()); values.add(fileUpload); } catch (IOException e) { throw uncheck(e); } finally { data.release(); } } data = decoder.next(); } } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) { // ignore } finally { decoder.destroy(); } return new DefaultForm(new ImmutableDelegatingMultiValueMap<>(attributes), new ImmutableDelegatingMultiValueMap<>(files)); }