List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder
public HttpPostRequestDecoder(HttpRequest request)
From source file:com.alibaba.dubbo.qos.command.decoder.HttpCommandDecoder.java
License:Apache License
public static CommandContext decode(HttpRequest request) { CommandContext commandContext = null; if (request != null) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); String path = queryStringDecoder.path(); String[] array = path.split("/"); if (array.length == 2) { String name = array[1]; // process GET request and POST request separately. Check url for GET, and check body for POST if (request.getMethod() == HttpMethod.GET) { if (queryStringDecoder.parameters().isEmpty()) { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { List<String> valueList = new ArrayList<String>(); for (List<String> values : queryStringDecoder.parameters().values()) { valueList.addAll(values); }//from w ww . j a va 2 s.co m commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } else if (request.getMethod() == HttpMethod.POST) { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); List<String> valueList = new ArrayList<String>(); for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) { if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { Attribute attribute = (Attribute) interfaceHttpData; try { valueList.add(attribute.getValue()); } catch (IOException ex) { throw new RuntimeException(ex); } } } if (valueList.isEmpty()) { commandContext = CommandContextFactory.newInstance(name); commandContext.setHttp(true); } else { commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true); } } } } return commandContext; }
From source file:com.android.tools.idea.diagnostics.crash.GoogleCrashTest.java
License:Apache License
@Ignore @Test/*from w w w . ja v a2s . c om*/ public void checkServerReceivesPostedData() throws Exception { String expectedReportId = "deadcafe"; Map<String, String> attributes = new ConcurrentHashMap<>(); myTestServer.setResponseSupplier(httpRequest -> { if (httpRequest.method() != HttpMethod.POST) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } HttpPostRequestDecoder requestDecoder = new HttpPostRequestDecoder(httpRequest); try { for (InterfaceHttpData httpData : requestDecoder.getBodyHttpDatas()) { if (httpData instanceof Attribute) { Attribute attr = (Attribute) httpData; attributes.put(attr.getName(), attr.getValue()); } } } catch (IOException e) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } finally { requestDecoder.destroy(); } return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(expectedReportId.getBytes(UTF_8))); }); CrashReport report = CrashReport.Builder.createForException(ourIndexNotReadyException) .setProduct("AndroidStudioTestProduct").setVersion("1.2.3.4").build(); CompletableFuture<String> reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); // assert that the server get the expected data assertEquals("AndroidStudioTestProduct", attributes.get(GoogleCrash.KEY_PRODUCT_ID)); assertEquals("1.2.3.4", attributes.get(GoogleCrash.KEY_VERSION)); // Note: the exception message should have been elided assertEquals("com.intellij.openapi.project.IndexNotReadyException: <elided>\n" + STACK_TRACE, attributes.get(GoogleCrash.KEY_EXCEPTION_INFO)); List<String> descriptions = Arrays.asList("2.3.0.0\n1.8.0_73-b02", "2.3.0.1\n1.8.0_73-b02"); report = CrashReport.Builder.createForCrashes(descriptions).setProduct("AndroidStudioTestProduct") .setVersion("1.2.3.4").build(); attributes.clear(); reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); // check that the crash count and descriptions made through assertEquals(descriptions.size(), Integer.parseInt(attributes.get("numCrashes"))); assertEquals("2.3.0.0\n1.8.0_73-b02\n\n2.3.0.1\n1.8.0_73-b02", attributes.get("crashDesc")); Path testData = Paths.get(AndroidTestBase.getTestDataPath()); List<String> threadDump = Files.readAllLines(testData.resolve(Paths.get("threadDumps", "1.txt")), UTF_8); report = CrashReport.Builder.createForPerfReport("td.txt", Joiner.on('\n').join(threadDump)).build(); attributes.clear(); reportId = myReporter.submit(report); assertEquals(expectedReportId, reportId.get()); assertEquals(threadDump.stream().collect(Collectors.joining("\n")), attributes.get("td.txt")); }
From source file:com.cats.version.httpserver.VersionProtocolMessageHandler.java
License:Apache License
private String decodeMessage(FullHttpRequest request) throws IOException { HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request); InterfaceHttpData data = httpPostRequestDecoder.getBodyHttpData("msg"); if (data.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) data; String strMsg = attribute.getValue(); return strMsg; }/*from ww w . jav a2 s. c o m*/ return null; }
From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { LogMgr.debug("channelRead0()", "channelRead0"); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//from ww w. java 2 s .c o m } } if (msg instanceof HttpContent) { String type = request.getUri().split("/")[1]; if (type.equals("email_activate") == true) { // GET? String[] tmp = request.getUri().split("="); String acode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}"); return; } else if (type.equals("email_pwd_reset") == true) { //? String[] tmp = request.getUri().split("="); String vcode = tmp[tmp.length - 1]; LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode); ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}"); return; } //email_active email_pwd_reset, //??? HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); InterfaceHttpData postData = decoder.getBodyHttpData("val"); if (postData instanceof FileUpload == false) {//outerProxy???? ctx.close(); return; } FileUpload binData = (FileUpload) postData; ByteBuf content = null; try { content = binData.getByteBuf(); } catch (IOException e) { e.printStackTrace(); } //content??. , 0. ?(head)?id, json?, ?. ??, ???. //?content?head int index = content.bytesBefore((byte) 0); if (index < 0) { LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request."); ctx.channel().close(); return; } byte[] head = new byte[index]; content.readBytes(head); String strHead = new String(head); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead); JSONObject jo = JSONObject.parseObject(strHead); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version")); content.readByte();//0 //?content?tail byte[] tail = new byte[content.readableBytes()]; content.readBytes(tail); String sjsonmsg = null; if (jo.getString("version").equals("0")) { //?0 byte[] bjsonmsg = XXTEA.decrypt(tail, key); int data_len = bjsonmsg.length; for (int i = bjsonmsg.length - 1; i != 0; --i) { if (bjsonmsg[i] == 0) { data_len--; continue; } else { break; } } try { sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { //TODO?0, app_id. ??? LogMgr.error(OuterProxyHttpServerHandler.class.getName(), "?0, ??"); ctx.close(); return; } sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//? LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg); //debug code //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model")); /* debug code //b.getBytes(n+1, tail, 0, b.g-n-1); for(int i=0; i< tail.length; ++i) { System.out.print(String.format("%x ", tail[i])); } */ //debug code //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod()); //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type); LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg); // ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg); } }
From source file:com.soho.framework.server.servlet.impl.HttpServletRequestImpl.java
License:Apache License
public HttpServletRequestImpl(HttpRequest request, FilterChainImpl chain) { this.originalRequest = request; if (request instanceof FullHttpRequest) { this.inputStream = new ServletInputStreamImpl((FullHttpRequest) request); } else {//from w ww . j a v a 2s . c o m this.inputStream = new ServletInputStreamImpl(request); } this.reader = new BufferedReader(new InputStreamReader(inputStream)); this.queryStringDecoder = new QueryStringDecoder(request.uri()); // post if (HttpMethod.POST.name().equalsIgnoreCase(request.method().name())) { postRequestDecoder = new HttpPostRequestDecoder(request); } this.uriParser = new URIParser(chain); this.uriParser.parse(request.uri()); this.characterEncoding = Utils.getCharsetFromContentType(getContentType()); }
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???/*from w w w. ja v a 2 s.c o m*/ // 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:io.werval.server.netty.NettyHttpFactories.java
License:Apache License
static Request requestOf(Charset defaultCharset, HttpBuildersSPI builders, String remoteSocketAddress, String identity, FullHttpRequest request) throws HttpRequestParsingException { ensureNotEmpty("Request Identity", identity); ensureNotNull("Netty FullHttpRequest", request); try {//from ww w . jav a 2s . c o m RequestBuilder builder = builders.newRequestBuilder().identifiedBy(identity) .remoteSocketAddress(remoteSocketAddress) .version(ProtocolVersion.valueOf(request.getProtocolVersion().text())) .method(request.getMethod().name()).uri(request.getUri()) .headers(headersToMap(request.headers())); if (request.content().readableBytes() > 0 && (POST.equals(request.getMethod()) || PUT.equals(request.getMethod()) || PATCH.equals(request.getMethod()))) { Optional<String> contentType = Headers.extractContentMimeType(request.headers().get(CONTENT_TYPE)); if (contentType.isPresent()) { switch (contentType.get()) { case APPLICATION_X_WWW_FORM_URLENCODED: case MULTIPART_FORM_DATA: try { Map<String, List<String>> attributes = new LinkedHashMap<>(); Map<String, List<Upload>> uploads = new LinkedHashMap<>(); HttpPostRequestDecoder postDecoder = new HttpPostRequestDecoder(request); for (InterfaceHttpData data : postDecoder.getBodyHttpDatas()) { switch (data.getHttpDataType()) { case Attribute: Attribute attribute = (Attribute) data; if (!attributes.containsKey(attribute.getName())) { attributes.put(attribute.getName(), new ArrayList<>()); } attributes.get(attribute.getName()).add(attribute.getValue()); break; case FileUpload: FileUpload fileUpload = (FileUpload) data; if (!uploads.containsKey(fileUpload.getName())) { uploads.put(fileUpload.getName(), new ArrayList<>()); } Upload upload; if (fileUpload.isInMemory()) { upload = new UploadInstance(fileUpload.getContentType(), fileUpload.getCharset(), fileUpload.getFilename(), new ByteBufByteSource(fileUpload.getByteBuf()).asBytes(), defaultCharset); } else { upload = new UploadInstance(fileUpload.getContentType(), fileUpload.getCharset(), fileUpload.getFilename(), fileUpload.getFile(), defaultCharset); } uploads.get(fileUpload.getName()).add(upload); break; default: break; } } builder = builder.bodyForm(attributes, uploads); break; } catch (ErrorDataDecoderException | IncompatibleDataDecoderException | NotEnoughDataDecoderException | IOException ex) { throw new WervalException("Form or multipart parsing error", ex); } default: builder = builder.bodyBytes(new ByteBufByteSource(request.content())); break; } } else { builder = builder.bodyBytes(new ByteBufByteSource(request.content())); } } return builder.build(); } catch (Exception ex) { throw new HttpRequestParsingException(ex); } }
From source file:net.mms_projects.copy_it.api.http.Handler.java
License:Open Source License
/** * Internal message handler, this is where all the http requests come in. This is where most of the authorization * and page logic goes on.//w w w . j av a2 s. co m * @see net.mms_projects.copy_it.api.http.Page * @see net.mms_projects.copy_it.api.oauth.HeaderVerifier */ protected void messageReceived(final ChannelHandlerContext chx, final HttpObject o) throws Exception { if (o instanceof HttpRequest) { final HttpRequest http = (HttpRequest) o; this.request = http; final URI uri = new URI(request.getUri()); if ((page = Page.getNoAuthPage(uri.getPath())) != null) { database = DatabasePool.getDBConnection(); if (request.getMethod() == HttpMethod.GET) { try { final FullHttpResponse response = page.onGetRequest(request, database); HttpHeaders.setContentLength(response, response.content().readableBytes()); HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType()); if (isKeepAlive(request)) { HttpHeaders.setKeepAlive(response, true); chx.write(response); } else chx.write(response).addListener(ChannelFutureListener.CLOSE); } catch (ErrorException e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8)); HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); chx.write(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), INTERNAL_SERVER_ERROR); chx.write(response).addListener(ChannelFutureListener.CLOSE); } } else if (request.getMethod() == HttpMethod.POST) postRequestDecoder = new HttpPostRequestDecoder(request); } else if ((page = Page.getAuthPage(uri.getPath())) == null) { final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), NOT_FOUND, Unpooled.copiedBuffer("404", CharsetUtil.UTF_8)); chx.write(response).addListener(ChannelFutureListener.CLOSE); } else { try { headerVerifier = new HeaderVerifier(http, uri); database = DatabasePool.getDBConnection(); headerVerifier.verifyConsumer(database); headerVerifier.verifyOAuthToken(database); headerVerifier.verifyOAuthNonce(database); if (request.getMethod() == HttpMethod.GET) { headerVerifier.checkSignature(null, false); final FullHttpResponse response = ((AuthPage) page).onGetRequest(request, database, headerVerifier); HttpHeaders.setContentLength(response, response.content().readableBytes()); HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType()); if (isKeepAlive(request)) { HttpHeaders.setKeepAlive(response, true); chx.write(response); } else chx.write(response).addListener(ChannelFutureListener.CLOSE); } else if (request.getMethod() == HttpMethod.POST) postRequestDecoder = new HttpPostRequestDecoder(request); } catch (ErrorException e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8)); HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); chx.write(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), INTERNAL_SERVER_ERROR); chx.write(response).addListener(ChannelFutureListener.CLOSE); } } } else if (o instanceof HttpContent && request != null && request.getMethod() == HttpMethod.POST) { final HttpContent httpContent = (HttpContent) o; postRequestDecoder.offer(httpContent); if (o instanceof LastHttpContent && page != null) { try { FullHttpResponse response; if (headerVerifier != null && page instanceof AuthPage) { headerVerifier.checkSignature(postRequestDecoder, false); response = ((AuthPage) page).onPostRequest(request, postRequestDecoder, database, headerVerifier); } else response = page.onPostRequest(request, postRequestDecoder, database); HttpHeaders.setContentLength(response, response.content().readableBytes()); HttpHeaders.setHeader(response, CONTENT_TYPE, page.GetContentType()); if (isKeepAlive(request)) { HttpHeaders.setKeepAlive(response, true); chx.write(response); } else chx.write(response).addListener(ChannelFutureListener.CLOSE); } catch (ErrorException e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), e.getStatus(), Unpooled.copiedBuffer(e.toString(), CharsetUtil.UTF_8)); HttpHeaders.setHeader(response, CONTENT_TYPE, Page.ContentTypes.JSON_TYPE); chx.write(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception e) { e.printStackTrace(); final FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), INTERNAL_SERVER_ERROR); chx.write(response).addListener(ChannelFutureListener.CLOSE); } } } if (o instanceof LastHttpContent && database != null) database.free(); }
From source file:nikoladasm.aspark.server.ServerHandler.java
License:Open Source License
private Map<String, List<String>> getPostAttributes(HttpMethod requestMethod, FullHttpRequest request) { final Map<String, List<String>> map = new HashMap<String, List<String>>(); if (!requestMethod.equals(POST)) return map; if (!isDecodeableContent(request.headers().get(CONTENT_TYPE))) return map; final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); try {/* w w w. j a va2 s .c o m*/ for (InterfaceHttpData data : decoder.getBodyHttpDatas()) { if (data.getHttpDataType() == HttpDataType.Attribute) { Attribute attribute = (Attribute) data; List<String> list = map.get(attribute.getName()); if (list == null) { list = new LinkedList<String>(); map.put(attribute.getName(), list); } list.add(attribute.getValue()); } } } catch (IOException e) { throw new IllegalStateException("Cannot parse http request data", e); } finally { decoder.destroy(); } return Collections.unmodifiableMap(map); }
From source file:org.apache.hyracks.http.server.FormUrlEncodedRequest.java
License:Apache License
public static IServletRequest create(FullHttpRequest request) throws IOException { List<String> names = new ArrayList<>(); List<String> values = new ArrayList<>(); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); try {//from w w w.j a va2 s . c om List<InterfaceHttpData> bodyHttpDatas = decoder.getBodyHttpDatas(); for (InterfaceHttpData data : bodyHttpDatas) { if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) { Attribute attr = (MixedAttribute) data; names.add(data.getName()); values.add(attr.getValue()); } } } finally { decoder.destroy(); } return new FormUrlEncodedRequest(request, new QueryStringDecoder(request.uri()).parameters(), names, values); }