List of usage examples for io.netty.handler.codec.http.multipart HttpPostRequestDecoder HttpPostRequestDecoder
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
From source file:io.vertx.core.http.impl.HttpServerRequestImpl.java
License:Open Source License
@Override public HttpServerRequest setExpectMultipart(boolean expect) { synchronized (conn) { checkEnded();//from ww w . ja 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 NettyFileUploadDataFactory(conn.vertx(), this, () -> uploadHandler), request); } } } } else { decoder = null; } return this; } }
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);/*from w ww . j av a 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:me.hrps.rp.preview.chat.service.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/*from w w w . j av a 2 s . c o m*/ } //HttpObjectAggregator $ AggregatedFullHttpRequest if (req.method() == POST) { try { //TODO ??post? decoder = new HttpPostRequestDecoder(factory, req); List<InterfaceHttpData> data = decoder.getBodyHttpDatas(); for (InterfaceHttpData postData : data) { Attribute attr = (Attribute) postData; System.out.println(attr.getName() + " " + attr.getValue()); } } catch (Exception e1) { e1.printStackTrace(); ctx.channel().close(); return; } ByteBuf buffer = Unpooled.copiedBuffer("success", CharsetUtil.UTF_8); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); res.headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "*"); sendHttpResponse(ctx, req, res); return; } // Allow only GET methods. // if (req.method() != GET) { // sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); // return; // } // Send the demo page and favicon.ico if ("/".equals(req.uri())) { ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "*"); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaderUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.uri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
From source file:net.oebs.jalos.netty.HttpHandler.java
License:Open Source License
private FullHttpResponse handleRequest(HttpRequest request) { FullHttpResponse response = null;//from ww w. jav 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:org.apache.flink.runtime.webmonitor.HttpRequestHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { try {/*from w w w. ja v a 2s . c o m*/ if (msg instanceof HttpRequest) { currentRequest = (HttpRequest) msg; currentRequestPath = null; if (currentDecoder != null) { currentDecoder.destroy(); currentDecoder = null; } if (currentRequest.getMethod() == HttpMethod.GET || currentRequest.getMethod() == HttpMethod.DELETE) { // directly delegate to the router ctx.fireChannelRead(currentRequest); } else if (currentRequest.getMethod() == HttpMethod.POST) { // POST comes in multiple objects. First the request, then the contents // keep the request and path for the remaining objects of the POST request currentRequestPath = new QueryStringDecoder(currentRequest.getUri()).path(); currentDecoder = new HttpPostRequestDecoder(DATA_FACTORY, currentRequest); } else { throw new IOException("Unsupported HTTP method: " + currentRequest.getMethod().name()); } } else if (currentDecoder != null && msg instanceof HttpContent) { // received new chunk, give it to the current decoder HttpContent chunk = (HttpContent) msg; currentDecoder.offer(chunk); try { while (currentDecoder.hasNext()) { InterfaceHttpData data = currentDecoder.next(); // IF SOMETHING EVER NEEDS POST PARAMETERS, THIS WILL BE THE PLACE TO HANDLE IT // all fields values will be passed with type Attribute. if (data.getHttpDataType() == HttpDataType.FileUpload) { DiskFileUpload file = (DiskFileUpload) data; if (file.isCompleted()) { String name = file.getFilename(); File target = new File(tmpDir, UUID.randomUUID() + "_" + name); file.renameTo(target); QueryStringEncoder encoder = new QueryStringEncoder(currentRequestPath); encoder.addParam("filepath", target.getAbsolutePath()); encoder.addParam("filename", name); currentRequest.setUri(encoder.toString()); } } data.release(); } } catch (EndOfDataDecoderException ignored) { } if (chunk instanceof LastHttpContent) { HttpRequest request = currentRequest; currentRequest = null; currentRequestPath = null; currentDecoder.destroy(); currentDecoder = null; // fire next channel handler ctx.fireChannelRead(request); } } } catch (Throwable t) { currentRequest = null; currentRequestPath = null; if (currentDecoder != null) { currentDecoder.destroy(); currentDecoder = null; } if (ctx.channel().isActive()) { byte[] bytes = ExceptionUtils.stringifyException(t).getBytes(ENCODING); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes)); response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8"); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response); } } }
From source file:org.bridje.http.impl.HttpServerChannelHandler.java
License:Apache License
private void readHeaders(ChannelHandlerContext ctx, HttpRequest msg) { if (req == null && context == null) { context = new HttpBridletContextImpl(); req = new HttpBridletRequestImpl(msg); QueryStringDecoder decoderQuery = new QueryStringDecoder(msg.getUri()); req.setQueryString(decoderQuery.parameters()); req.setCookies(parseCookies(msg.headers().get(COOKIE))); // new getMethod if (req.isForm()) { decoder = new HttpPostRequestDecoder(FACTORY, msg); }/*from w w w . j ava2 s . c om*/ } else { sendBadRequest(ctx); } }
From source file:org.ftccommunity.ftcxtensible.networking.http.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String page;/*from ww w . j a va 2s. com*/ if (req.getMethod() == HttpMethod.POST) { LinkedList<InterfaceHttpData> postData = new LinkedList<>(); HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), req); postRequestDecoder.getBodyHttpDatas(); for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { postData.add(data); } } context.addPostData(postData); } if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } HttpResponseStatus responseStatus = OK; String uri = (req.getUri().equals("/") ? context.getServerSettings().getIndex() : req.getUri()); if (uri.equals(context.getServerSettings().getHardwareMapJsonPage())) { GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization(); Gson gson = gsonBuilder.create(); HardwareMap hardwareMap = context.getHardwareMap(); page = gson.toJson(ImmutableSet.copyOf(hardwareMap.dcMotor)); } else if (uri.equals(context.getServerSettings().getLogPage())) { page = context.getStatus().getLog(); } else { if (cache.containsKey(uri)) { page = cache.get(uri); responseStatus = NOT_MODIFIED; } else { try { page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8); } catch (FileNotFoundException e) { Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri); page = "File Not Found!"; responseStatus = NOT_FOUND; } catch (IOException e) { page = "An Error Occurred!\n" + e.toString(); responseStatus = NOT_FOUND; Log.e("NET_OP_MODE::", e.toString(), e); } cache.put(uri, page); } } boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8))); String extension = MimeTypeMap.getFileExtensionFromUrl(uri); String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension)) + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8")); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:org.ftccommunity.ftcxtensible.networking.http.RobotHttpServerHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String page;/*from w w w . j a v a 2s. c om*/ if (req.getMethod() == HttpMethod.POST) { LinkedList<InterfaceHttpData> postData = new LinkedList<>(); HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), req); postRequestDecoder.getBodyHttpDatas(); for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { postData.add(data); } } context.addPostData(postData); } if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } HttpResponseStatus responseStatus = OK; String uri = (req.getUri().equals("/") ? context.serverSettings().getIndex() : req.getUri()); if (uri.equals(context.serverSettings().getHardwareMapJsonPage())) { GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization(); Gson gson = gsonBuilder.create(); ExtensibleHardwareMap hardwareMap = context.hardwareMap(); page = gson.toJson(hardwareMap.dcMotors()); } else if (uri.equals(context.serverSettings().getLogPage())) { page = context.status().getLog(); } else { if (cache.containsKey(uri)) { page = cache.get(uri); responseStatus = NOT_MODIFIED; } else { try { page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8); } catch (FileNotFoundException e) { Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri); page = "File Not Found!"; responseStatus = NOT_FOUND; } catch (IOException e) { page = "An Error Occurred!\n" + e.toString(); responseStatus = NOT_FOUND; Log.e("NET_OP_MODE::", e.toString(), e); } cache.put(uri, page); } } boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8))); String extension = MimeTypeMap.getFileExtensionFromUrl(uri); String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension)) + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8")); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:org.jboss.arquillian.warp.impl.client.execution.HttpRequestWrapper.java
License:Apache License
@Override public Map<String, List<String>> getHttpDataAttributes() { if (!HttpMethod.POST.equals(getMethod())) { throw new IllegalArgumentException("Cannot parse HttpData for requests other than POST"); }// w w w .j ava 2 s. c o m try { if (httpDataAttributes == null) { final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request); final Map<String, List<String>> map = new HashMap<String, List<String>>(); try { 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()); } } } finally { decoder.destroy(); } httpDataAttributes = map; } return Collections.unmodifiableMap(httpDataAttributes); } catch (IOException e) { throw new IllegalStateException("Cannot parse http request data", e); } }
From source file:org.jooby.internal.netty.NettyRequest.java
License:Apache License
private Multimap<String, String> decodeParams() throws IOException { if (params == null) { params = ArrayListMultimap.create(); files = ArrayListMultimap.create(); query.parameters().forEach((name, values) -> values.forEach(value -> params.put(name, value))); HttpMethod method = req.method(); boolean hasBody = method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH); boolean formLike = false; if (req.headers().contains("Content-Type")) { String contentType = req.headers().get("Content-Type").toLowerCase(); formLike = (contentType.startsWith(MediaType.multipart.name()) || contentType.startsWith(MediaType.form.name())); }//w w w . j a va 2s . co m if (hasBody && formLike) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(), req); try { Function<HttpPostRequestDecoder, Boolean> hasNext = it -> { try { return it.hasNext(); } catch (HttpPostRequestDecoder.EndOfDataDecoderException ex) { return false; } }; while (hasNext.apply(decoder)) { HttpData field = (HttpData) decoder.next(); try { String name = field.getName(); if (field.getHttpDataType() == HttpDataType.FileUpload) { files.put(name, new NettyUpload((FileUpload) field, tmpdir)); } else { params.put(name, field.getString()); } } finally { field.release(); } } } finally { decoder.destroy(); } } } return params; }