List of usage examples for io.netty.handler.codec.http HttpRequest uri
String uri();
From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.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);/*w w w .jav a2 s. c o m*/ } String uri = request.uri(); HttpMethod method = request.method(); Root root = Root.getInstance(); buf.setLength(0); contentBuf.setLength(0); if (method == HttpMethod.POST) { if (uri.equals("/chitchat")) { currentAction = "Add"; } } if (method == HttpMethod.GET) { if (uri.startsWith(LATEST)) { latestFromWho = decode(uri.substring(LATEST_SIZE)); currentAction = "Latest"; Message m = root.getLatest(latestFromWho); if (m != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(m.toJSON()); } } if (uri.startsWith(THREADCALL)) { currentAction = "Thread"; String threadId = uri.substring(THREADCALL_SIZE); MessageThread mt = root.getMessageThread(threadId); if (mt != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(mt.toJSON()); } } if (uri.startsWith(SEARCH)) { String stringToSearch = decode(uri.substring(SEARCH_SIZE)); currentAction = "search"; List<Message> lm = root.search(stringToSearch); //[{"author":"Loki", "text":"I have an army !", "thread":3, //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !", // "thread":3, "createdAt":1404736639715}] buf.append("["); if (!lm.isEmpty()) { Iterator<Message> it = lm.iterator(); Message m = it.next(); buf.append(m.toJSON()); while (it.hasNext()) { m = it.next(); buf.append(", "); buf.append(m.toJSON()); } } buf.append("]"); } } } if (msg instanceof HttpContent) { Root root = Root.getInstance(); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { contentBuf.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // buf.append("END OF CONTENT\r\n"); if (currentAction.equals("Add")) { addMessageFromContent(contentBuf.toString(), root); currentAction = "None"; } LastHttpContent trailer = (LastHttpContent) msg; 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:cc.blynk.core.http.handlers.OTAHandler.java
License:Apache License
@Override public boolean accept(ChannelHandlerContext ctx, HttpRequest req) { if (req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri)) { try {// w w w.j a va 2s .c o m User superAdmin = AuthHeadersBaseHttpHandler.validateAuth(userDao, req); if (superAdmin != null) { ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).set(superAdmin); queryStringDecoder = new QueryStringDecoder(req.uri()); return true; } } catch (IllegalAccessException e) { //return 403 and stop processing. ctx.writeAndFlush(Response.forbidden(e.getMessage())); return true; } } return false; }
From source file:cc.blynk.core.http.handlers.UploadHandler.java
License:Apache License
public boolean accept(ChannelHandlerContext ctx, HttpRequest req) { return req.method() == HttpMethod.POST && req.uri().startsWith(handlerUri); }
From source file:cc.blynk.core.http.handlers.UploadHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (!accept(ctx, req)) { ctx.fireChannelRead(msg);// w w w . j a va2s . c o m return; } try { log.debug("Incoming {} {}", req.method(), req.uri()); decoder = new HttpPostRequestDecoder(factory, req); } catch (ErrorDataDecoderException e) { log.error("Error creating http post request decoder.", e); ctx.writeAndFlush(badRequest(e.getMessage())); return; } } if (decoder != null && msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e) { log.error("Error creating http post offer.", e); ctx.writeAndFlush(badRequest(e.getMessage())); return; } finally { chunk.release(); } // example of reading only if at the end if (chunk instanceof LastHttpContent) { Response response; try { String path = finishUpload(); if (path != null) { response = afterUpload(ctx, path); } else { response = serverError("Can't find binary data in request."); } } catch (NoSuchFileException e) { log.error("Unable to copy uploaded file to static folder. Reason : {}", e.getMessage()); response = (serverError()); } catch (Exception e) { log.error("Error during file upload.", e); response = (serverError()); } ctx.writeAndFlush(response); } } }
From source file:ch07.handlers.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 ww . jav a 2 s . com*/ } 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(HttpHeaders.getHost(request, "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) { 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.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 (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.aerofs.baseline.http.HttpRequestHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (ctx.channel().closeFuture().isDone()) { LOGGER.warn("{}: drop http message - channel closed", Channels.getHexText(ctx)); return;/*from www .j av a 2 s . c o m*/ } if (!(msg instanceof HttpObject)) { super.channelRead(ctx, msg); } // // netty http decoding: // // 1. normal case: HttpRequest (headers), HttpContent (0+), LastHttpContent (trailing headers) // NOTE: with chunked transfer encoding or content-length non-zero you get an arbitrary number of HttpContent objects // 2. error case (failed to decode an HTTP message): HttpRequest with NETTY_HTTP_DECODING_FAILED_URI // if (msg instanceof HttpRequest) { // this is the first object netty generates: // an HttpRequest containing a number of headers // we should not have another request pending Preconditions.checkState(pendingRequest == null, "previous request pending:%s", pendingRequest); // cast it HttpRequest nettyRequest = (HttpRequest) msg; // get the request id String requestId = nettyRequest.headers().get(Headers.REQUEST_TRACING_HEADER); Preconditions.checkState(requestId != null, "http request on %s has no request id", Channels.getHexText(ctx)); // check if http decoding failed and if so, abort early if (nettyRequest.uri().equals(NETTY_HTTP_DECODING_FAILED_URI)) { LOGGER.warn("{}: [{}] fail http decoding", Channels.getHexText(ctx), requestId); ctx.read(); return; } // get a few headers we really care about HttpVersion httpVersion = nettyRequest.protocolVersion(); boolean keepAlive = HttpHeaders.isKeepAlive(nettyRequest); boolean transferEncodingChunked = HttpHeaders.isTransferEncodingChunked(nettyRequest); boolean continueExpected = HttpHeaders.is100ContinueExpected(nettyRequest); long contentLength = HttpHeaders.getContentLength(nettyRequest, ZERO_CONTENT_LENGTH); boolean hasContent = transferEncodingChunked || contentLength > ZERO_CONTENT_LENGTH; LOGGER.trace("{}: [{}] rq:{} ka:{} ck:{} ce:{} cl:{}", Channels.getHexText(ctx), requestId, nettyRequest, keepAlive, transferEncodingChunked, continueExpected, contentLength); // create the input stream used to read content ContentInputStream entityInputStream; if (hasContent) { entityInputStream = new EntityInputStream(httpVersion, continueExpected, ctx); } else { entityInputStream = EmptyEntityInputStream.EMPTY_ENTITY_INPUT_STREAM; } // create the object with which to write the response body PendingRequest pendingRequest = new PendingRequest(requestId, httpVersion, keepAlive, entityInputStream, ctx); // create the jersey request object final ContainerRequest jerseyRequest = new ContainerRequest(baseUri, URI.create(nettyRequest.uri()), nettyRequest.method().name(), DEFAULT_SECURITY_CONTEXT, PROPERTIES_DELEGATE); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_CHANNEL_ID_PROPERTY, new ChannelId(Channels.getHexText(ctx))); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_REQUEST_ID_PROPERTY, new RequestId(requestId)); jerseyRequest.header(Headers.REQUEST_TRACING_HEADER, requestId); // add request id to headers copyHeaders(nettyRequest.headers(), jerseyRequest); // copy headers from message jerseyRequest.setEntityStream(entityInputStream); jerseyRequest.setWriter(pendingRequest); // now we've got all the initial headers and are waiting for the entity this.pendingRequest = pendingRequest; // store the runnable that we want jersey to execute saveRequestRunnable(() -> { // all throwables caught by jersey internally - // handled by the ResponseWriter below // if, for some reason there's some weird error it'll be handled // by the default exception handler, which kills the process applicationHandler.handle(jerseyRequest); }); // IMPORTANT: // we pass this request up to be processed by // jersey before we've read any content. This allows // the resource to read from the InputStream // directly, OR, to use an @Consumes annotation with an // input objectType to invoke the appropriate parser // // since the request is consumed *before* the content // has been received readers may block. to prevent the // IO thread from blocking we have to execute all // request processing in an application threadpool if (hasContent) { submitPendingRunnable(); } // indicate that we want to keep reading // this is always the case when we receive headers // because we want to receive everything until // LastHttpContent ctx.read(); } else { // after receiving the http headers we get // a series of HttpContent objects that represent // the entity or a set of chunks // we should have received the headers already Preconditions.checkState(pendingRequest != null, "no pending request"); // we're not expecting anything other than content objects right now Preconditions.checkArgument(msg instanceof HttpContent, "HttpContent expected, not %s", msg.getClass().getSimpleName()); // handle the content HttpContent content = (HttpContent) msg; boolean last = msg instanceof LastHttpContent; LOGGER.trace("{}: [{}] handling content:{} last:{}", Channels.getHexText(ctx), pendingRequest.requestId, content.content().readableBytes(), last); pendingRequest.entityInputStream.addBuffer(content.content(), last); // transfers ownership to the HttpContentInputStream // FIXME (AG): support trailing headers // if it's the last piece of content, then we're done if (last) { // submit the request to jersey if we haven't yet if (savedRequestRunnable != null) { submitPendingRunnable(); } } } }
From source file:com.artigile.homestats.HomeStatsHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; byte responseBody[]; final String uri = req.uri(); if (uri.startsWith("/getCurrentHumidity")) { responseBody = getHumidity(); } else if (uri.startsWith("/getCurrentTemp")) { responseBody = getTemperature(); } else if (uri.startsWith("/getCurrentPressure")) { responseBody = getPressure(); } else if (uri.startsWith("/getData")) { responseBody = readDataFromDb(); } else {// w ww.j a va 2 s. c o m responseBody = "404".getBytes(); } if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseBody)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
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();/* w w w.java 2 s .c om*/ // 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);/* w w w . ja va 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 www .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()); } }