List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder getBodyHttpDatas
@Override
public List<InterfaceHttpData> getBodyHttpDatas()
From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java
License:Apache License
private Map<String, List<String>> initParametersByPost(Map<String, List<String>> params, HttpPostRequestDecoder httpPostRequestDecoder) { if (AssertUtil.isNull(httpPostRequestDecoder)) { return params; }//from w ww . ja va 2s .co m try { List<InterfaceHttpData> datas = httpPostRequestDecoder.getBodyHttpDatas(); if (AssertUtil.isNotEmptyCollection(datas)) { for (InterfaceHttpData data : datas) { if (data instanceof Attribute) { Attribute attribute = (Attribute) data; try { String key = attribute.getName(); String value = attribute.getValue(); List<String> ori = params.get(key); if (AssertUtil.isEmptyCollection(ori)) { ori = new ArrayList<>(1); params.put(key, ori); } ori.add(value); } catch (IOException e) { log.error("cant init attribute,req:{},attribute:{}", new Object[] { this, attribute, e }); } } } } } catch (HttpPostRequestDecoder.NotEnoughDataDecoderException e) { log.error("req:{}", this, e); } return params; }
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 w w . j ava2 s . c o 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 ww. java 2 s .c o m 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.bay1ts.bay.core.Request.java
License:Apache License
public Set<String> postBodyNames() { Set<String> set = new HashSet<>(); HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), this.fullHttpRequest); for (InterfaceHttpData data : httpPostRequestDecoder.getBodyHttpDatas()) { data = httpPostRequestDecoder.next(); set.add(data.getName());// w ww. j ava2 s.co m data.release(); // if (data!=null){ // try { // Attribute attribute=(Attribute) data; // set.add(attribute.getName()); // }finally { // data.release(); // } // } } return set; }
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 w w w . j av a 2 s.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:itlab.teleport.HttpServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws SQLException, IOException { if (msg instanceof FullHttpRequest) { HttpRequest req = (HttpRequest) msg; final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);/* ww w .j a va 2s.co m*/ List<InterfaceHttpData> data = decoder.getBodyHttpDatas(); for (InterfaceHttpData entry : data) { Attribute attr = (Attribute) entry; try { System.out.println(String.format("name: %s value: %s", attr.getName(), attr.getValue())); } catch (IOException e) { e.printStackTrace(); } } } if (msg instanceof HttpContent) { String json_input = ""; HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { json_input = content.toString(CharsetUtil.UTF_8); buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (CharSequence name : trailer.trailingHeaders().names()) { for (CharSequence value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } System.out.println(buf); try { Statement st = BD_Connect.c.createStatement();// ? ResultSet rs = st.executeQuery("Select 1"); } catch (Exception e) { new BD_Connect().BD_Connection_open(); // } String json_output = new JSON_Handler().Parse_JSON(json_input); // JSON ? ByteBuf response_content = Unpooled.wrappedBuffer(json_output.getBytes(CharsetUtil.UTF_8)); HttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, OK, response_content); ctx.writeAndFlush(resp); ctx.close(); new BD_Connect().BD_Connection_close(); // ?? ? } } }
From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java
License:Open Source License
/** * Create method for the raw signature base for post requests * @see net.mms_projects.copy_it.api.oauth.HeaderVerifier#checkSignature(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder, boolean) *//* w ww .j a v a 2 s .c o m*/ private String createRaw(HttpPostRequestDecoder post, boolean https) throws UnsupportedEncodingException, URISyntaxException { final StringBuilder rawbuilder = new StringBuilder(); rawbuilder.append(request.getMethod().toString()); rawbuilder.append('&'); rawbuilder.append(HTTP); if (https) rawbuilder.append('s'); rawbuilder.append(COLON_SLASH_SLASH); rawbuilder.append(URLEncoder.encode(request.headers().get(HOST), UTF_8)); rawbuilder.append(URLEncoder.encode(uri.getPath(), UTF_8)); rawbuilder.append('&'); if (uri.getQuery() == null && request.getMethod() == HttpMethod.GET) { String[] loop_through = OAuthParameters.KEYS; if ((flags & Flags.REQUIRES_VERIFIER) == Flags.REQUIRES_VERIFIER) loop_through = OAuthParameters.VERIFIER_KEYS; for (int i = 0; i < loop_through.length; i++) { rawbuilder.append(loop_through[i]); rawbuilder.append(EQUALS); rawbuilder.append(URLEncoder.encode(oauth_params.get(loop_through[i]), UTF_8)); if (i != (loop_through.length - 1)) rawbuilder.append(AND); } } else { final List<String> keys = new ArrayList<String>(); final Map<String, String> parameters = new HashMap<String, String>(); if (request.getMethod() == HttpMethod.GET) { final QueryStringDecoder querydecoder = new QueryStringDecoder(uri); final Map<String, List<String>> get_parameters = querydecoder.parameters(); final Set<String> keyset = parameters.keySet(); final Iterator<String> iter = keyset.iterator(); while (iter.hasNext()) { final String key = iter.next(); keys.add(key); parameters.put(key, get_parameters.get(key).get(0)); } } else if (request.getMethod() == HttpMethod.POST) { final List<InterfaceHttpData> post_parameters = post.getBodyHttpDatas(); final Iterator<InterfaceHttpData> iter = post_parameters.iterator(); while (iter.hasNext()) { final InterfaceHttpData data = iter.next(); try { final HttpData httpData = (HttpData) data; parameters.put(httpData.getName(), URLEncoder.encode(httpData.getString(), UTF_8).replace(PLUS, PLUS_ENCODED)); keys.add(httpData.getName()); } catch (IOException e) { e.printStackTrace(); } } } for (int i = 0; i < OAuthParameters.KEYS.length; i++) keys.add(OAuthParameters.KEYS[i]); if ((flags & Flags.REQUIRES_VERIFIER) == Flags.REQUIRES_VERIFIER) keys.add(OAuthParameters.OAUTH_VERIFIER); Collections.sort(keys); final int length = keys.size(); for (int i = 0; i < length; i++) { final String key = keys.get(i); rawbuilder.append(key); rawbuilder.append(EQUALS); if (key.startsWith(OAUTH_)) rawbuilder.append(URLEncoder.encode(oauth_params.get(key), UTF_8)); else rawbuilder.append(URLEncoder.encode(parameters.get(key), UTF_8)); if (i != (length - 1)) rawbuilder.append(AND); } } System.err.println(rawbuilder.toString()); return rawbuilder.toString(); }
From source file:net.oebs.jalos.netty.HttpHandler.java
License:Open Source License
private FullHttpResponse handleRequest(HttpRequest request) { FullHttpResponse response = null;//from w w w . j a v a 2 s. c om String uri = request.getUri(); // lookup Handler class by URL Class cls = null; for (Route route : routes) { if (uri.matches(route.path)) { cls = route.handler; break; } } // no matching handler == 404 if (cls == null) { log.info("No handler match found for uri {}", uri); return notFound(); } Handler h; try { h = (Handler) cls.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { return internalError(); } Map<String, String> params = null; HttpMethod method = request.getMethod(); // dispatch based on request method try { if (method.equals(HttpMethod.POST)) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request); params = httpDataToStringMap(decoder.getBodyHttpDatas()); response = h.handlePost(uri, params); } else if (method.equals(HttpMethod.GET)) { params = new HashMap<>(); response = h.handleGet(uri, params); } else { response = badRequest(); } } catch (BadRequest ex) { response = badRequest(); } catch (NotFound ex) { response = notFound(); } catch (HandlerError ex) { response = internalError(); } return response; }
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 ww . j a v a2 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); }