List of usage examples for io.netty.handler.codec.http QueryStringDecoder parameters
public Map<String, List<String>> parameters()
From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java
License:Apache License
protected void captureQueryParameters(HttpRequest httpRequest, HarRequest harRequest) { // capture query parameters. it is safe to assume the query string is UTF-8, since it "should" be in US-ASCII (a subset of UTF-8), // but sometimes does include UTF-8 characters. QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri(), StandardCharsets.UTF_8); try {// w ww . j a va2 s .c o m for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) { for (String value : entry.getValue()) { harRequest.getQueryString().add(new HarNameValuePair(entry.getKey(), value)); } } } catch (IllegalArgumentException e) { // QueryStringDecoder will throw an IllegalArgumentException if it cannot interpret a query string. rather than cause the entire request to // fail by propagating the exception, simply skip the query parameter capture. log.info("Unable to decode query parameters on URI: " + httpRequest.getUri(), e); } }
From source file:com.github.mike10004.seleniumhelp.TrafficMonitorFilter.java
License:Apache License
protected void captureRequestContent(HttpRequest httpRequest, byte[] fullMessage, HarRequest harRequest) { if (fullMessage.length == 0) { return;/*from w ww . j a v a 2s . c om*/ } String contentType = HttpHeaders.getHeader(httpRequest, HttpHeaders.Names.CONTENT_TYPE); if (contentType == null) { log.warn("No content type specified in request to {}. Content will be treated as {}", httpRequest.getUri(), BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE); contentType = BrowserMobHttpUtil.UNKNOWN_CONTENT_TYPE; } HarPostData postData = new HarPostData(); harRequest.setPostData(postData); postData.setMimeType(contentType); final boolean urlEncoded = contentType.startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); Charset charset; try { charset = BrowserMobHttpUtil.readCharsetInContentTypeHeader(contentType); } catch (UnsupportedCharsetException e) { log.warn( "Found unsupported character set in Content-Type header '{}' in HTTP request to {}. Content will not be captured in HAR.", contentType, httpRequest.getUri(), e); return; } if (charset == null) { // no charset specified, so use the default -- but log a message since this might not encode the data correctly charset = BrowserMobHttpUtil.DEFAULT_HTTP_CHARSET; log.debug("No charset specified; using charset {} to decode contents to {}", charset, httpRequest.getUri()); } if (urlEncoded) { String textContents = BrowserMobHttpUtil.getContentAsString(fullMessage, charset); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(textContents, charset, false); ImmutableList.Builder<HarPostDataParam> paramBuilder = ImmutableList.builder(); for (Map.Entry<String, List<String>> entry : queryStringDecoder.parameters().entrySet()) { for (String value : entry.getValue()) { paramBuilder.add(new HarPostDataParam(entry.getKey(), value)); } } harRequest.getPostData().setParams(paramBuilder.build()); } else { //TODO: implement capture of files and multipart form data // not URL encoded, so let's grab the body of the POST and capture that String postBody = BrowserMobHttpUtil.getContentAsString(fullMessage, charset); harRequest.getPostData().setText(postBody); } }
From source file:com.github.wens.netty.web.impl.RequestImp.java
License:Apache License
private void readQueryString() { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri()); queryStringParams = queryStringDecoder.parameters(); }
From source file:com.imaginarycode.minecraft.bungeejson.impl.httpserver.HttpServerHandler.java
License:Open Source License
private HttpResponse getResponse(ChannelHandlerContext channelHandlerContext, HttpRequest hr) { QueryStringDecoder query = new QueryStringDecoder(hr.getUri()); Multimap<String, String> params = createMultimapFromMap(query.parameters()); Object reply;//from w ww . j a v a2s . c o m HttpResponseStatus hrs; final RequestHandler handler = BungeeJSONPlugin.getRequestManager().getHandlerForEndpoint(query.path()); if (handler == null) { reply = BungeeJSONUtilities.error("No such endpoint exists."); hrs = HttpResponseStatus.NOT_FOUND; } else { final ApiRequest ar = new HttpServerApiRequest( ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getAddress(), params, bodyBuilder.toString()); try { reply = handler.handle(ar); hrs = HttpResponseStatus.OK; } catch (Throwable throwable) { hrs = HttpResponseStatus.INTERNAL_SERVER_ERROR; reply = BungeeJSONUtilities .error("An internal error has occurred. Information has been logged to the console."); BungeeJSONPlugin.getPlugin().getLogger().log(Level.WARNING, "Error while handling " + hr.getUri() + " from " + ar.getRemoteIp(), throwable); } } String json = BungeeJSONPlugin.getPlugin().getGson().toJson(reply); DefaultFullHttpResponse hreply = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, hrs, Unpooled.wrappedBuffer(json.getBytes(CharsetUtil.UTF_8))); // Add a reminder that we're still running the show. hreply.headers().set("Content-Type", "application/json; charset=UTF-8"); hreply.headers().set("Access-Control-Allow-Origin", "*"); hreply.headers().set("Server", "BungeeJSON/0.1"); hreply.headers().set("Content-Length", json.length()); return hreply; }
From source file:com.intuit.karate.netty.FeatureServerHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) { long startTime = System.currentTimeMillis(); backend.getContext().logger.debug("handling method: {}, uri: {}", msg.method(), msg.uri()); FullHttpResponse nettyResponse;//from w w w . j a v a 2s . c o m if (msg.uri().startsWith(STOP_URI)) { backend.getContext().logger.info("stop uri invoked, shutting down"); ByteBuf responseBuf = Unpooled.copiedBuffer("stopped", CharsetUtil.UTF_8); nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBuf); stopFunction.run(); } else { StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri()); HttpRequest request = new HttpRequest(); if (url.left == null) { String requestScheme = ssl ? "https" : "http"; String host = msg.headers().get(HttpUtils.HEADER_HOST); request.setUrlBase(requestScheme + "://" + host); } else { request.setUrlBase(url.left); } request.setUri(url.right); request.setMethod(msg.method().name()); msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue())); QueryStringDecoder decoder = new QueryStringDecoder(url.right); decoder.parameters().forEach((k, v) -> request.putParam(k, v)); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { byte[] bytes = new byte[content.readableBytes()]; content.readBytes(bytes); request.setBody(bytes); } HttpResponse response = backend.buildResponse(request, startTime); HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(response.getStatus()); byte[] responseBody = response.getBody(); if (responseBody != null) { ByteBuf responseBuf = Unpooled.copiedBuffer(responseBody); nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, responseBuf); } else { nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus); } MultiValuedMap karateHeaders = response.getHeaders(); if (karateHeaders != null) { HttpHeaders nettyHeaders = nettyResponse.headers(); karateHeaders.forEach((k, v) -> nettyHeaders.add(k, v)); } } ctx.write(nettyResponse); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:com.look.netty.demo.upload.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 . ja v a 2s . c om 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(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.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"); // Not now: LastHttpContent will be sent 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 = HttpUtil.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(); System.err.println(new String(responseContent.toString().getBytes(), "UTF-8")); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.lyra.vertx.jersey.impl.DefaultJerseyHandler.java
License:Open Source License
protected URI getAbsoluteURI(HttpServerRequest vertxRequest) { URI absoluteUri;/* w ww . jav a 2 s. c om*/ String hostAndPort = vertxRequest.headers().get(HttpHeaders.HOST); try { absoluteUri = vertxRequest.absoluteURI(); if (hostAndPort != null && !hostAndPort.isEmpty()) { String[] parts = hostAndPort.split(":"); String host = parts[0]; int port = (parts.length > 1 ? Integer.valueOf(parts[1]) : -1); if (!host.equalsIgnoreCase(absoluteUri.getHost()) || port != absoluteUri.getPort()) { absoluteUri = UriBuilder.fromUri(absoluteUri).host(host).port(port).build(); } } return absoluteUri; } catch (IllegalArgumentException e) { String uri = vertxRequest.uri(); if (!uri.contains("?")) { throw e; } try { logger.warn("Invalid URI: " + uri + ". Attempting to parse query string.", e); QueryStringDecoder decoder = new QueryStringDecoder(uri); StringBuilder sb = builder(decoder.path() + "?"); for (Map.Entry<String, List<String>> p : decoder.parameters().entrySet()) { for (String value : p.getValue()) { sb.append(p.getKey()).append("=").append(URLEncoder.encode(value, "UTF-8")); } } return URI.create(sb.toString()); } catch (Exception e1) { throw new RuntimeException(e1); } } }
From source file:com.mapple.http.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/* w w w .j a v a 2s. c o m*/ QueryStringDecoder decoder = new QueryStringDecoder(req.uri()); List<String> close = decoder.parameters().get("close"); int pos = -1; if (close != null && close.size() > 0) { pos = Integer.valueOf(close.get(0)); } StringBuilder body = new StringBuilder(); ConcurrentSet<Channel> proxyList = ForwardLoginHandler.INSTANCE.proxyList(); int i = 0; AttributeKey<ForwardLogin> Session = AttributeKey.valueOf("Session"); Iterator<Channel> it = proxyList.iterator(); while (it.hasNext()) { Channel ch = it.next(); ForwardLogin p = ch.attr(Session).get(); body.append(i + 1); body.append(" "); body.append(p.getUserName()); body.append(" "); body.append( p.getProvince() + (p.getCity() == null ? "" : p.getCity()) + "[" + p.getProvince2() + "]"); body.append(" "); body.append(p.getRemoteAddr() + ":" + p.getRemotePort()); body.append(" "); body.append(p.getCarrier()); body.append(" "); if (ch instanceof SocketChannel) { body.append("TCP"); } else { body.append("UDT"); } if (i++ == pos) { body.append(" [CLOSED]"); ch.writeAndFlush(new ForwardForceClose()); } body.append("\n"); } String data = body.toString(); if (data.isEmpty()) { data = "?"; } // boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(data.getBytes(CharsetUtil.UTF_8))); response.headers().set(CONTENT_TYPE, "text/plain; charset=utf-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); // if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); // } else { // response.headers().set(CONNECTION, KEEP_ALIVE); // ctx.write(response); // } } }
From source file:com.mastfrog.acteur.server.EventImpl.java
License:Open Source License
@Override public synchronized Map<String, String> getParametersAsMap() { if (paramsMap == null) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); Map<String, String> result = new HashMap<>(); for (Map.Entry<String, List<String>> e : params.entrySet()) { if (e.getValue().isEmpty()) { continue; }/*from w ww . j a v a 2s . co m*/ result.put(e.getKey(), e.getValue().get(0)); } paramsMap = ImmutableSortedMap.copyOf(result); } return paramsMap; }
From source file:com.netty.file.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 ww . j a v a 2s. com 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"); System.out.println("Helllllllllllllllllloooooooooooooo"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.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"); // Not now: LastHttpContent will be sent 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 = HttpUtil.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 { writeResponse(ctx.channel()); } }