List of usage examples for io.netty.handler.codec.http QueryStringDecoder parameters
public Map<String, List<String>> parameters()
From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { this.httprequest = (HttpRequest) msg; requestBuilder = new Request.Builder(); requestBuilder.requestMethod(RequestMethod.valueOf(httprequest.method().name())).uri(httprequest.uri()); try {/*from w w w. ja va 2s. c o m*/ // Decode URI GET query parameters QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httprequest.uri()); requestBuilder.path(queryStringDecoder.path()).query(queryStringDecoder.parameters()); // Process cookies List<Cookie> cookies = new ArrayList<>(); String cookieString = httprequest.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { ServerCookieDecoder.STRICT.decode(cookieString).stream().forEach((cookie) -> { cookies.add(NettyCookieConverter.convertToFuga(cookie)); }); } requestBuilder.cookies(cookies); // Process headers Map<String, String> headers = new HashMap<>(); httprequest.headers().entries().stream().forEach((e) -> { headers.put(e.getKey(), e.getValue()); }); requestBuilder.headers(headers); // Get real parameters from frontend HTTP server boolean isSecure = false; SocketAddress remoteAddress = ctx.channel().remoteAddress(); if (forwarded == 1) { // RFC7239 if (headers.containsKey("Forwarded")) { String fwdStr = headers.get("Forwarded"); List<String> fwdparams = Stream.of(fwdStr.split("; ")).map((s) -> s.trim()) .collect(Collectors.toList()); for (String f : fwdparams) { String p[] = f.split("="); switch (p[0]) { case "for": remoteAddress = parseAddress(p[1]); break; case "proto": isSecure = p[1].equals("https"); break; } } } } else if (forwarded == 0) { // X-Forwarded if (headers.containsKey("X-Forwarded-Proto")) { if (headers.get("X-Forwarded-Proto").equalsIgnoreCase("https")) { isSecure = true; } } if (headers.containsKey("X-Forwarded-For")) { String fwdfor = headers.get("X-Forwarded-For"); remoteAddress = parseAddress( fwdfor.contains(",") ? fwdfor.substring(0, fwdfor.indexOf(',')) : fwdfor); } else if (headers.containsKey("X-Real-IP")) { remoteAddress = parseAddress(headers.get("X-Real-IP")); } } requestBuilder.remoteAddress(remoteAddress).isSecure(isSecure); if (headers.containsKey("Accept-Language")) { String acceptLanguage = headers.get("Accept-Language"); List<Locale> acceptLocales = Stream.of(acceptLanguage.split(",")) .map((s) -> s.contains(";") ? s.substring(0, s.indexOf(";")).trim() : s.trim()) .map((s) -> s.contains("-") ? new Locale(s.split("-")[0], s.split("-")[0]) : new Locale(s)) .collect(Collectors.toList()); requestBuilder.acceptLocales(acceptLocales); } // if (httprequest.method().equals(HttpMethod.GET)) { processResponse(ctx); return; } decoder = true; } catch (Exception e) { processClientError(ctx, requestBuilder.build(), 400); return; } } if (msg instanceof HttpContent && decoder) { HttpContent httpContent = (HttpContent) msg; contentBuffer.writeBytes(httpContent.content()); if (httpContent instanceof LastHttpContent) { requestBuilder.content(new BufferedContent(contentBuffer.nioBuffer())); processResponse(ctx); } } }
From source file:com.chiorichan.http.HttpRequestWrapper.java
License:Mozilla Public License
HttpRequestWrapper(Channel channel, HttpRequest http, HttpHandler handler, boolean ssl, LogEvent log) throws IOException { this.channel = channel; this.http = http; this.handler = handler; this.ssl = ssl; this.log = log; putRequest(this); // Set Time of this Request requestTime = Timings.epoch();//from w w w . j a v a 2s . com // Create a matching HttpResponseWrapper response = new HttpResponseWrapper(this, log); String host = getHostDomain(); if (host == null || host.length() == 0) { parentDomain = ""; site = SiteManager.instance().getDefaultSite(); } else if (NetworkFunc.isValidIPv4(host) || NetworkFunc.isValidIPv6(host)) { parentDomain = host; site = SiteManager.instance().getSiteByIp(host).get(0); } else { Pair<String, SiteMapping> match = SiteMapping.get(host); if (match == null) { parentDomain = host; site = SiteManager.instance().getDefaultSite(); } else { parentDomain = match.getKey(); Namespace hostNamespace = new Namespace(host); Namespace parentNamespace = new Namespace(parentDomain); Namespace childNamespace = hostNamespace.subNamespace(0, hostNamespace.getNodeCount() - parentNamespace.getNodeCount()); assert hostNamespace.getNodeCount() - parentNamespace.getNodeCount() == childNamespace .getNodeCount(); childDomain = childNamespace.getNamespace(); site = match.getValue().getSite(); } } if (site == null) site = SiteManager.instance().getDefaultSite(); if (site == SiteManager.instance().getDefaultSite() && getUri().startsWith("/~")) { List<String> uris = Splitter.on("/").omitEmptyStrings().splitToList(getUri()); String siteId = uris.get(0).substring(1); Site siteTmp = SiteManager.instance().getSiteById(siteId); if (!siteId.equals("wisp") && siteTmp != null) { site = siteTmp; uri = "/" + Joiner.on("/").join(uris.subList(1, uris.size())); // TODO Implement both a virtual and real URI for use in redirects and url_to() String[] domains = site.getDomains().keySet().toArray(new String[0]); parentDomain = domains.length == 0 ? host : domains[0]; } } // log.log( Level.INFO, "SiteId: " + site.getSiteId() + ", ParentDomain: " + parentDomain + ", ChildDomain: " + childDomain ); try { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(http.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) for (Entry<String, List<String>> p : params.entrySet()) { // XXX This is overriding the key, why would their there be multiple values??? String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) getMap.put(key, val); } } catch (IllegalStateException e) { log.log(Level.SEVERE, "Failed to decode the GET map because " + e.getMessage()); } // Decode Cookies // String var1 = URLDecoder.decode( http.headers().getAndConvert( "Cookie" ), Charsets.UTF_8.displayName() ); String var1 = http.headers().getAndConvert("Cookie"); // TODO Find a way to fix missing invalid stuff if (var1 != null) try { Set<Cookie> var2 = CookieDecoder.decode(var1); for (Cookie cookie : var2) if (cookie.name().startsWith("_ws")) serverCookies.add(new HttpCookie(cookie)); else cookies.add(new HttpCookie(cookie)); } catch (IllegalArgumentException | NullPointerException e) { //NetworkManager.getLogger().debug( var1 ); NetworkManager.getLogger().severe("Failed to parse cookie for reason: " + e.getMessage()); // NetworkManager.getLogger().warning( "There was a problem decoding the request cookie.", e ); // NetworkManager.getLogger().debug( "Cookie: " + var1 ); // NetworkManager.getLogger().debug( "Headers: " + Joiner.on( "," ).withKeyValueSeparator( "=" ).join( http.headers() ) ); } initServerVars(); }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx);//from ww w .j av a 2 s . c om } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(request.headers().get(HttpHeaderNames.HOST, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } 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"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.cmz.http.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. j a va 2s . c o m 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(); // 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.company.product.test.http.HttpServerHandler.java
License:Apache License
protected void messageReceived(ChannelHandlerContext ctx, Object msg) { FullHttpResponse response = null;/*from www. jav a 2s . c o m*/ try { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); validateQueryString(params); compileAndSendMessage(params); // no need to provide a response, we did what was expected of us. response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); } } catch (IllegalArgumentException iae) { response = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); throw iae; } catch (InvalidTopicException ite) { response = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); throw ite; } finally { ctx.write(response); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(msg); } }
From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { SchedulerKey key = new SchedulerKey(Type.PING_TIMEOUT, ctx.channel()); disconnectScheduler.cancel(key);//w w w . j a va2 s.c o m if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; Channel channel = ctx.channel(); QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); if (!configuration.isAllowCustomRequests() && !queryDecoder.path().startsWith(connectPath)) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); req.release(); log.warn("Blocked wrong request! url: {}, ip: {}", queryDecoder.path(), channel.remoteAddress()); return; } List<String> sid = queryDecoder.parameters().get("sid"); if (queryDecoder.path().equals(connectPath) && sid == null) { String origin = req.headers().get(HttpHeaders.Names.ORIGIN); if (!authorize(ctx, channel, origin, queryDecoder.parameters(), req)) { req.release(); return; } // forward message to polling or websocket handler to bind channel } } ctx.fireChannelRead(msg); }
From source file:com.corundumstudio.socketio.handler.WrongUrlHandler.java
License:Apache License
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; Channel channel = ctx.channel(); QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); ChannelFuture f = channel.writeAndFlush(res); f.addListener(ChannelFutureListener.CLOSE); req.release();//from w w w . ja va 2 s . c om log.warn("Blocked wrong socket.io-context request! url: {}, params: {}, ip: {}", queryDecoder.path(), queryDecoder.parameters(), channel.remoteAddress()); } }
From source file:com.corundumstudio.socketio.transport.PollingTransport.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); List<String> transport = queryDecoder.parameters().get("transport"); if (transport != null && NAME.equals(transport.get(0))) { List<String> sid = queryDecoder.parameters().get("sid"); List<String> j = queryDecoder.parameters().get("j"); List<String> b64 = queryDecoder.parameters().get("b64"); String origin = req.headers().get(HttpHeaders.Names.ORIGIN); ctx.channel().attr(EncoderHandler.ORIGIN).set(origin); String userAgent = req.headers().get(HttpHeaders.Names.USER_AGENT); ctx.channel().attr(EncoderHandler.USER_AGENT).set(userAgent); if (j != null && j.get(0) != null) { Integer index = Integer.valueOf(j.get(0)); ctx.channel().attr(EncoderHandler.JSONP_INDEX).set(index); }//from w ww . j av a 2s . co m if (b64 != null && b64.get(0) != null) { Integer enable = Integer.valueOf(b64.get(0)); ctx.channel().attr(EncoderHandler.B64).set(enable == 1); } try { if (sid != null && sid.get(0) != null) { final UUID sessionId = UUID.fromString(sid.get(0)); handleMessage(req, sessionId, queryDecoder, ctx); } else { // first connection ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get(); handleMessage(req, client.getSessionId(), queryDecoder, ctx); } } finally { req.release(); } return; } } ctx.fireChannelRead(msg); }
From source file:com.corundumstudio.socketio.transport.PollingTransport.java
License:Apache License
private void handleMessage(FullHttpRequest req, UUID sessionId, QueryStringDecoder queryDecoder, ChannelHandlerContext ctx) throws IOException { String origin = req.headers().get(HttpHeaders.Names.ORIGIN); if (queryDecoder.parameters().containsKey("disconnect")) { ClientHead client = clientsBox.get(sessionId); client.onChannelDisconnect();//w w w .j a va 2s .c om ctx.channel().writeAndFlush(new XHRPostMessage(origin, sessionId)); } else if (HttpMethod.POST.equals(req.getMethod())) { onPost(sessionId, ctx, origin, req.content()); } else if (HttpMethod.GET.equals(req.getMethod())) { onGet(sessionId, ctx, origin); } else if (HttpMethod.OPTIONS.equals(req.getMethod())) { onOptions(sessionId, ctx, origin); } else { log.error("Wrong {} method invocation for {}", req.getMethod(), sessionId); sendError(ctx); } }
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CloseWebSocketFrame) { ctx.channel().close();// w ww . j a va2 s. c o m ReferenceCountUtil.release(msg); } else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) { ByteBufHolder frame = (ByteBufHolder) msg; ClientHead client = clientsBox.get(ctx.channel()); if (client == null) { log.debug("Client with was already disconnected. Channel closed!"); ctx.channel().close(); frame.release(); return; } ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET)); frame.release(); } else if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String path = queryDecoder.path(); List<String> transport = queryDecoder.parameters().get("transport"); List<String> sid = queryDecoder.parameters().get("sid"); if (transport != null && NAME.equals(transport.get(0))) { try { if (!configuration.getTransports().contains(Transport.WEBSOCKET)) { log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET); ctx.channel().close(); return; } if (sid != null && sid.get(0) != null) { final UUID sessionId = UUID.fromString(sid.get(0)); handshake(ctx, sessionId, path, req); } else { ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get(); // first connection handshake(ctx, client.getSessionId(), path, req); } } finally { req.release(); } } else { ctx.fireChannelRead(msg); } } else { ctx.fireChannelRead(msg); } }