List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { FullHttpMessage currentMessage = this.currentMessage; if (msg instanceof HttpMessage) { tooLongFrameFound = false;/* w w w. j a v a2 s.c om*/ assert currentMessage == null; HttpMessage m = (HttpMessage) msg; // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (is100ContinueExpected(m)) { ByteBuf buf = CONTINUE_LINE.duplicate(); buf.retain(); ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.getDecoderResult().isSuccess()) { removeTransferEncodingChunked(m); out.add(toFullMessage(m)); this.currentMessage = null; return; } if (msg instanceof HttpRequest) { HttpRequest header = (HttpRequest) msg; this.currentMessage = currentMessage = new DefaultFullHttpRequest(header.getProtocolVersion(), header.getMethod(), header.getUri(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else if (msg instanceof HttpResponse) { HttpResponse header = (HttpResponse) msg; this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(), header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents)); } else { throw new Error(); } currentMessage.headers().set(m.headers()); // A streamed message - initialize the cumulative buffer, and wait for incoming chunks. removeTransferEncodingChunked(currentMessage); } else if (msg instanceof HttpContent) { if (tooLongFrameFound) { if (msg instanceof LastHttpContent) { this.currentMessage = null; } // already detect the too long frame so just discard the content return; } assert currentMessage != null; // Merge the received chunk into the content of the current message. HttpContent chunk = (HttpContent) msg; CompositeByteBuf content = (CompositeByteBuf) currentMessage.content(); if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) { tooLongFrameFound = true; // release current message to prevent leaks currentMessage.release(); this.currentMessage = null; throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes."); } // Append the content of the chunk if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } final boolean last; if (!chunk.getDecoderResult().isSuccess()) { currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause())); last = true; } else { last = chunk instanceof LastHttpContent; } if (last) { this.currentMessage = null; // Merge trailing headers into the message. if (chunk instanceof LastHttpContent) { LastHttpContent trailer = (LastHttpContent) chunk; currentMessage.headers().add(trailer.trailingHeaders()); } // Set the 'Content-Length' header. currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); // All done out.add(currentMessage); } } else { throw new Error(); } }
From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java
License:Open Source License
private static FullHttpMessage toFullMessage(HttpMessage msg) { if (msg instanceof FullHttpMessage) { return ((FullHttpMessage) msg).retain(); }//from w w w.jav a2 s. c om FullHttpMessage fullMsg; if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; fullMsg = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(), req.getUri(), Unpooled.EMPTY_BUFFER, false); } else if (msg instanceof HttpResponse) { HttpResponse res = (HttpResponse) msg; fullMsg = new DefaultFullHttpResponse(res.getProtocolVersion(), res.getStatus(), Unpooled.EMPTY_BUFFER, false); } else { throw new IllegalStateException(); } return fullMsg; }
From source file:com.mastfrog.netty.http.client.CookieStore.java
License:Open Source License
void decorate(HttpRequest req) { URL url;//from w w w .j a va 2s. c o m if (!req.getUri().contains("://")) { String host = req.headers().get(Headers.HOST.name()); url = URL.builder().setPath(req.getUri()).setHost(host).create(); } else { url = URL.parse(req.getUri()); } Lock readLock = lock.readLock(); readLock.lock(); try { List<Cookie> toSend = new ArrayList<>(); for (Cookie cookie : cookies) { if (checkDomain) { if (cookie.getDomain() != null && !cookie.getDomain().equals(url.getHost().toString())) { continue; } } if (checkPath) { String pth = cookie.getPath(); if (pth != null) { String compare = url.getPath().toStringWithLeadingSlash(); if (!"/".equals(pth) && !"".equals(pth) && !compare.equals(pth) && !compare.startsWith(pth)) { continue; } } } toSend.add(cookie); } if (!toSend.isEmpty()) { for (Cookie ck : toSend) { String headerValue = Headers.COOKIE.toString(new Cookie[] { ck }); req.headers().add(Headers.COOKIE.name(), headerValue); } } } finally { readLock.unlock(); } }
From source file:com.mastfrog.netty.http.client.HttpClient.java
License:Open Source License
private void submit(final URL url, HttpRequest rq, final AtomicBoolean cancelled, final ResponseFuture handle, final ResponseHandler<?> r, RequestInfo info, Duration timeout, boolean noAggregate) { if (info != null && info.isExpired()) { cancelled.set(true);/* w w w.java 2 s . co m*/ } if (cancelled.get()) { handle.event(new State.Cancelled()); return; } try { for (RequestInterceptor i : interceptors) { rq = i.intercept(rq); } final HttpRequest req = rq; Bootstrap bootstrap; if (url.getProtocol().isSecure()) { bootstrap = startSsl(url.getHostAndPort()); } else { bootstrap = start(url.getHostAndPort()); } if (!url.isValid()) { throw new IllegalArgumentException(url.getProblems() + ""); } TimeoutTimerTask tt = null; if (info == null) { info = new RequestInfo(url, req, cancelled, handle, r, timeout, tt, noAggregate); if (timeout != null) { tt = new TimeoutTimerTask(cancelled, handle, r, info); timer.schedule(tt, timeout.getMillis()); } info.timer = tt; } if (info.isExpired()) { handle.event(new State.Timeout(info.age())); return; } handle.event(new State.Connecting()); //XXX who is escaping this? req.setUri(req.getUri().replaceAll("%5f", "_")); ChannelFuture fut = bootstrap.connect(url.getHost().toString(), url.getPort().intValue()); if (tt != null) { fut.channel().closeFuture().addListener(tt); } fut.channel().attr(KEY).set(info); handle.setFuture(fut); if (!monitors.isEmpty()) { for (ActivityMonitor m : monitors) { m.onStartRequest(url); } fut.channel().closeFuture().addListener(new AdapterCloseNotifier(url)); } fut.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Throwable cause = future.cause(); if (cause == null) { cause = new ConnectException(url.getHost().toString()); } handle.event(new State.Error(cause)); if (r != null) { r.onError(cause); } cancelled.set(true); } if (cancelled.get()) { future.cancel(true); if (future.channel().isOpen()) { future.channel().close(); } for (ActivityMonitor m : monitors) { m.onEndRequest(url); } return; } handle.event(new State.Connected(future.channel())); handle.event(new State.SendRequest(req)); future = future.channel().writeAndFlush(req); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (cancelled.get()) { future.cancel(true); future.channel().close(); } handle.event(new State.AwaitingResponse()); } }); } }); } catch (Exception ex) { Exceptions.chuck(ex); } }
From source file:com.mycompany.nettyweb.HttpServerHandler.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { statistics.addUniqueRequest(getIP(ctx)); statistics.addNewRequestByIP(getIP(ctx)); statistics.addToAllRequests();/*from w w w .ja v a 2s .com*/ HttpRequest req = (HttpRequest) msg; trafficURL = req.getUri(); String uri; if (req.getUri().startsWith("/redirect?url=")) { uri = "/redirect"; } else { uri = req.getUri(); } switch (uri) { case "/hello": helloResponse(ctx, req); break; case "/status": statusResponse(ctx, req); break; case "/redirect": StringBuilder url = new StringBuilder( new QueryStringDecoder(req.getUri()).parameters().get("url").get(0)); if (!url.toString().startsWith("http://")) { url.insert(0, "http://"); } statistics.addRedirects(url.toString()); redirectResponse(ctx, url.toString()); break; default: defResponse(ctx, req); break; } } else { ctx.flush(); } setTraffic(ctx); }
From source file:com.netty.fileTest.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);/* w w w . j a v a2 s . com*/ 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.nettyhttpserver.server.util.HttpRequestHandler.java
public static void handle(ChannelHandlerContext ctx, HttpRequest req, DefaultChannelGroup channels) { allChannels = channels;/*from ww w . j a v a 2 s .c om*/ FullHttpResponse response = null; boolean keepAlive = isKeepAlive(req); String requestUri = req.getUri().toLowerCase(); /* * Write data about request to database */ ServerRequestDTO requestServiceDTO = new ServerRequestDTO(); requestServiceDTO.setIP(((InetSocketAddress) ctx.channel().remoteAddress()).getHostString()); requestServiceDTO.setLastTimestamp(new Timestamp(System.currentTimeMillis()).toString()); serverRequestService.setServerRequest(requestServiceDTO); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } /* * If request /hello */ if (Requests.HELLO.toString().equalsIgnoreCase(requestUri)) { content = Unpooled .unreleasableBuffer(Unpooled.copiedBuffer("<h1>Hello World!</h1>", CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); /* * Create timer for /hello page. */ timer.newTimeout(new ResponseTimerTask(ctx, response, keepAlive), 10, TimeUnit.SECONDS); writeToResponse(ctx, response, keepAlive); return; } /* * if request uri is /status */ if (Requests.STATUS.toString().equalsIgnoreCase(requestUri)) { content = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(generateStatus(), CharsetUtil.UTF_8)); response = new DefaultFullHttpResponse(HTTP_1_1, OK, content.duplicate()); writeToResponse(ctx, response, keepAlive); return; } /* * If redirect */ if (requestUri.matches(Requests.REDIRECT.toString())) { QueryStringDecoder qsd = new QueryStringDecoder(requestUri); List<String> redirectUrl = qsd.parameters().get("url"); response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, redirectUrl); /* * Redirect database routine * Write url to database */ RedirectRequestDTO requestRedirectDTO = new RedirectRequestDTO(); requestRedirectDTO.setUrl(redirectUrl.get(0)); redirectRequestService.setRedirectRequest(requestRedirectDTO); } else { /* * If request URI is not handled by server. */ response = new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN); } writeToResponse(ctx, response, keepAlive); }
From source file:com.pokersu.server.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from w w w. j a v a2 s.c o m } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); // HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.getUri())) { 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:com.qq.servlet.demo.netty.sample.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg);//from w ww.j a va 2 s . c o m System.out.println("\n\n\n\n============" + msg.getClass().getName() + "=================\n\n\n"); if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String uri = req.getUri(); System.out.println("uri--->>>" + uri); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("".getBytes())); response.headers().set(CONTENT_TYPE, "text/plain"); 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); } } else if (msg instanceof DefaultLastHttpContent) { DefaultLastHttpContent httpContent = (DefaultLastHttpContent) msg; String body = httpContent.content().toString(CharsetUtil.UTF_8); System.out.println("body===>>> " + body); } }
From source file:com.rackspacecloud.blueflood.tracker.Tracker.java
License:Apache License
public void track(HttpRequest request) { // check if tenantId is being tracked by JMX TenantTrackerMBean and log the request if it is if (request == null) return;/* w w w . java 2 s. c om*/ String tenantId = findTid(request.getUri()); if (isTracking(tenantId)) { // get headers String headers = EMPTY_STRING; for (String headerName : request.headers().names()) { headers += "\n" + headerName + "\t" + request.headers().get(headerName); } // get parameters String queryParams = getQueryParameters(request); // get request content String requestContent = EMPTY_STRING; if (request instanceof FullHttpRequest) { FullHttpRequest fullReq = (FullHttpRequest) request; requestContent = fullReq.content().toString(Constants.DEFAULT_CHARSET); if ((requestContent != null) && (!requestContent.isEmpty())) { requestContent = "\nREQUEST_CONTENT:\n" + requestContent; } } // log request String logMessage = "[TRACKER] " + request.getMethod() + " request for tenantId " + tenantId + ": " + request.getUri() + queryParams + "\n" + "HEADERS: " + headers + requestContent; if (doesMessageContainMetricNames(logMessage)) { log.info(logMessage); } } }