List of usage examples for io.netty.handler.codec.http QueryStringDecoder parameters
public Map<String, List<String>> parameters()
From source file:com.springapp.mvc.netty.example.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 (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/*from w w w. ja v a2 s . c o m*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); 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 (String name : trailer.trailingHeaders().names()) { for (String 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.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { try {//from w ww . ja v a 2 s .c om if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); path = queryStringDecoder.path(); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); if (key.equalsIgnoreCase("db")) { dbName = p.getValue().get(0); } } } if (path != null && path.contains("query")) { Gson gson = new Gson(); JsonObject obj = new JsonObject(); JsonArray ary = new JsonArray(); ary.add(new JsonObject()); obj.add("results", ary); responseString.append(gson.toJson(obj)); } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf byteBuf = httpContent.content(); if (byteBuf.isReadable()) { requestBuffer.append(byteBuf.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // LastHttpContent lastHttpContent = (LastHttpContent) msg; // if (!lastHttpContent.trailingHeaders().isEmpty()) { // } if (dbName == null) { responseString.append("Invalid database null"); logger.severe("Invalid database null"); } else { String payload = requestBuffer.toString(); logger.fine("Request:" + payload); List<DataPoint> dps = dataPointsFromString(dbName, payload); for (DataPoint dp : dps) { try { engine.writeDataPoint(dp); logger.fine("Accepted:" + dp + "\t" + new Date(dp.getTimestamp())); } catch (IOException e) { logger.fine("Dropped:" + dp + "\t" + e.getMessage()); responseString.append("Dropped:" + dp); } } } if (writeResponse(request, ctx)) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.tongtech.tis.fsc.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()); System.out.println("uri upload: " + uri); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);/*from w w w . ja v a2 s . c om*/ return; } logger.info("write last reponse."); 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) { logger.info("upload, decoder!= null" + msg); 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 { logger.info("upload, decoder == null, writeResponse."); writeResponse(ctx.channel()); } }
From source file:com.topsec.bdc.platform.api.server.http.HttpSnoopServerHandler.java
License:Apache License
/** * ????.// ww w .j a va 2 s .co m * * @param message * @return * @throws Exception */ private String fireListenerSucceed(String message) throws Exception { this._serverReferent.requestTotal(); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this._request.getUri()); String path = queryStringDecoder.path(); //PATH/ if (Assert.isEmptyString(path) == true) { path = "/"; } Map<String, List<String>> parameterMap = queryStringDecoder.parameters(); Iterable<Map.Entry<String, String>> headerMap = this._request.headers(); IRequestListener listener = this._serverReferent.getResquestListener(path); if (listener != null) { Object[] parameterObject = new Object[] { headerMap, parameterMap, path, message }; return listener.fireSucceed(parameterObject); } else { this._responseStatus = HttpResponseStatus.NOT_FOUND; return null; } }
From source file:com.topsec.bdc.platform.api.test.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 (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);//from w w w . j a v 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.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); 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 (String name : trailer.trailingHeaders().names()) { for (String 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.topsec.bdc.platform.api.test.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.getUri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//from w w w.ja v a 2 s . 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.getProtocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.getUri() + "\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(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri()); 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 (request.getMethod().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; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.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.zhuowenfeng.devtool.hs_server.handler.HttpServiceHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { HSServerContext hsContext = new HSServerContext(); if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; hsContext.setRequest(request);/*w w w . j a v a 2 s.c om*/ String uri = request.getUri(); hsContext.setRequestUri(uri); if (is100ContinueExpected(request)) { send100Continue(ctx); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); JSONObject pathVariables = new JSONObject(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { pathVariables.put(key, val); } } } hsContext.setPathVariables(pathVariables); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); JSONObject requestContent = new JSONObject(); if (content.isReadable()) { requestContent = JSONObject.fromObject(content.toString(CharsetUtil.UTF_8)); } hsContext.setRequestContent(requestContent); if (msg instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) msg; JSONObject result = HttpServiceDispatcher.dispatch(hsContext); writeResponse(trailer, ctx, result); } } }
From source file:de.cubeisland.engine.core.webapi.HttpRequestHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception { InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress(); this.log.info("{} connected...", inetSocketAddress.getAddress().getHostAddress()); if (!this.server.isAddressAccepted(inetSocketAddress.getAddress())) { this.log.info("Access denied!"); ctx.channel().close();/*w ww. jav a 2s . c o m*/ } if (message.getDecoderResult().isFailure()) { this.error(ctx, UNKNOWN_ERROR); this.log.info(message.getDecoderResult().cause(), "The decoder failed on this request..."); return; } boolean authorized = this.server.isAuthorized(inetSocketAddress.getAddress()); QueryStringDecoder qsDecoder = new QueryStringDecoder(message.getUri(), this.UTF8, true, 100); final Parameters params = new Parameters(qsDecoder.parameters(), core.getCommandManager().getProviderManager()); User authUser = null; if (!authorized) { if (!core.getModuleManager().getServiceManager().isImplemented(Permission.class)) { this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Authentication deactivated", 200)); return; } String user = params.get("user", String.class); String pass = params.get("pass", String.class); if (user == null || pass == null) { this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200)); return; } User exactUser = core.getUserManager().findExactUser(user); if (exactUser == null || !exactUser.isPasswordSet() || !CubeEngine.getUserManager().checkPassword(exactUser, pass)) { this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200)); return; } authUser = exactUser; } String path = qsDecoder.path().trim(); if (path.length() == 0 || "/".equals(path)) { this.error(ctx, ROUTE_NOT_FOUND); return; } path = normalizePath(path); // is this request intended to initialize a websockets connection? if (WEBSOCKET_ROUTE.equals(path)) { WebSocketRequestHandler handler; if (!(ctx.pipeline().last() instanceof WebSocketRequestHandler)) { handler = new WebSocketRequestHandler(core, server, objectMapper, authUser); ctx.pipeline().addLast("wsEncoder", new TextWebSocketFrameEncoder(objectMapper)); ctx.pipeline().addLast("handler", handler); } else { handler = (WebSocketRequestHandler) ctx.pipeline().last(); } this.log.info("received a websocket request..."); handler.doHandshake(ctx, message); return; } this.handleHttpRequest(ctx, message, path, params, authUser); }
From source file:de.cubeisland.engine.core.webapi.WebSocketRequestHandler.java
License:Open Source License
private void handleTextWebSocketFrame(final ChannelHandlerContext ctx, TextWebSocketFrame frame) { // TODO log exceptions!!! JsonNode jsonNode;/*w w w . j a va2 s .co m*/ try { jsonNode = objectMapper.readTree(frame.text()); } catch (IOException e) { this.log.info("the frame data was no valid json!"); return; } JsonNode action = jsonNode.get("action"); JsonNode msgid = jsonNode.get("msgid"); ObjectNode responseNode = objectMapper.createObjectNode(); if (action == null) { responseNode.put("response", "No action"); } else { JsonNode data = jsonNode.get("data"); switch (action.asText()) { case "http": QueryStringDecoder qsDecoder = new QueryStringDecoder(normalizePath(data.get("uri").asText()), this.UTF8, true, 100); JsonNode reqMethod = data.get("method"); RequestMethod method = reqMethod != null ? getByName(reqMethod.asText()) : GET; JsonNode reqdata = data.get("body"); ApiHandler handler = this.server.getApiHandler(normalizePath(qsDecoder.path())); if (handler == null) { responseNode.put("response", "Unknown route"); break; } Parameters params = new Parameters(qsDecoder.parameters(), core.getCommandManager().getProviderManager()); ApiRequest request = new ApiRequest((InetSocketAddress) ctx.channel().remoteAddress(), method, params, EMPTY_HEADERS, reqdata, authUser); ApiResponse response = handler.execute(request); if (msgid != null) { responseNode.set("response", objectMapper.valueToTree(response.getContent())); } break; case "subscribe": this.server.subscribe(data.asText().trim(), this); break; case "unsubscribe": this.server.unsubscribe(data.asText().trim(), this); break; default: responseNode.put("response", action.asText() + " -- " + data.asText()); } } if (msgid != null && responseNode.elements().hasNext()) { responseNode.put("msgid", msgid); ctx.writeAndFlush(responseNode); } }
From source file:divconq.web.Request.java
License:Open Source License
public void load(ChannelHandlerContext ctx, HttpRequest req) { this.method = req.getMethod(); this.headers = req.headers(); String value = req.headers().get(Names.COOKIE); if (StringUtil.isNotEmpty(value)) { Set<Cookie> cset = CookieDecoder.decode(value); for (Cookie cookie : cset) this.cookies.put(cookie.getName(), cookie); }/*from ww w .j a v a 2 s . c om*/ QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri()); this.parameters = decoderQuery.parameters(); // TODO decode this.path = new CommonPath(QueryStringDecoder.decodeComponent(decoderQuery.path())); this.orgpath = this.path; this.contentType = new ContentTypeParser(this.headers.get(Names.CONTENT_TYPE)); }