List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:org.atmosphere.nettosphere.BridgeRuntime.java
License:Apache License
private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent) throws URISyntaxException, IOException { boolean skipClose = false; AtmosphereResponse response = null;//from w ww .j a va 2 s. co m AtmosphereRequest request = null; Action a = null; boolean resumeOnBroadcast = false; boolean keptOpen = false; ChannelWriter asyncWriter = null; String method = "GET"; boolean writeHeader = false; boolean forceSuspend = false; boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory(); try { if (messageEvent instanceof HttpRequest) { final HttpRequest hrequest = (HttpRequest) messageEvent; byte[] body = EMPTY; if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) { ByteBuf b = FullHttpRequest.class.cast(messageEvent).content(); if (b.isReadable()) { body = new byte[b.readableBytes()]; b.readBytes(body); } } // First let's try to see if it's a static resources if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) { try { hrequest.headers().add(STATIC_MAPPING, "true"); super.channelRead(ctx, messageEvent); if (HttpHeaders.getHeader(hrequest, SERVICED) != null) { return; } } catch (Exception e) { logger.debug("Unexpected State", e); } finally { hrequest.headers().set(STATIC_MAPPING, "false"); } } boolean ka = HttpHeaders.isKeepAlive(hrequest); asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka) : new StreamWriter(ctx.channel(), true, ka); method = hrequest.getMethod().name(); request = createAtmosphereRequest(ctx, hrequest, body); request.setAttribute(KEEP_ALIVE, new Boolean(ka)); // Hacky. Is the POST doesn't contains a body, we must not close the connection yet. AtmosphereRequestImpl.Body b = request.body(); if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty() && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) { forceSuspend = true; } } else { request = State.class.cast(ctx.attr(ATTACHMENT).get()).request; boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput(); Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE); asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka) : new StreamWriter(ctx.channel(), isLast, ka); method = request.getMethod(); ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content(); if (!aggregateBodyInMemory && internalBuffer.hasArray()) { request.body(internalBuffer.array()); } else { logger.trace("Unable to read in memory the request's bytes. Using stream"); request.body(new ByteBufInputStream(internalBuffer)); } if (!isLast) { forceSuspend = true; } } response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader) .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0") .request(request).build(); if (config.supportChunking()) { response.setHeader("Transfer-Encoding", "chunked"); } a = framework.doCometSupport(request, response); if (forceSuspend) { a.type(Action.TYPE.SUSPEND); // leave the stream open keptOpen = true; } String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE); if (transport == null) { transport = request.getHeader(X_ATMOSPHERE_TRANSPORT); } if (a.type() == Action.TYPE.SUSPEND) { if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT) || transport.equalsIgnoreCase(SSE_TRANSPORT))) { keptOpen = true; } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT) || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) { resumeOnBroadcast = true; } } final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND); final State state = new State(request, action == null ? Action.CONTINUE : action); ctx.attr(ATTACHMENT).set(state); if (action != null && action.type() == Action.TYPE.SUSPEND) { if (action.timeout() != -1) { final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter); final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>(); f.set(suspendTimer.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!w.get().isClosed() && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) { AtmosphereResourceImpl impl = state.resource(); if (impl != null) { asynchronousProcessor.endRequest(impl, false); f.get().cancel(true); } } } }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS)); } } else if (action != null && action.type() == Action.TYPE.RESUME) { resumeOnBroadcast = false; } } catch (AtmosphereMappingException ex) { if (method.equalsIgnoreCase("GET")) { logger.trace("Unable to map the request {}, trying static file", messageEvent); } } catch (Throwable e) { logger.error("Unable to process request", e); throw new IOException(e); } finally { try { if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) { if (!skipClose && response != null) { asyncWriter.close(response); } else { httpChannels.add(ctx.channel()); } } } finally { if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) { request.destroy(); response.destroy(); framework.notify(Action.TYPE.DESTROYED, request, response); } } } }
From source file:org.atmosphere.nettosphere.BridgeRuntime.java
License:Apache License
private String getWebSocketLocation(HttpRequest req) { return "ws://" + req.headers().get(HttpHeaders.Names.HOST) + req.getUri(); }
From source file:org.atmosphere.vibe.platform.bridge.netty4.NettyServerHttpExchangeTest.java
License:Apache License
@Override protected void startServer() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w .j a va2 s . c o m*/ public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()).addLast(new VibeServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals("/test"); } }.onhttp(performer.serverAction())); } }); channels.add(bootstrap.bind(port).channel()); }
From source file:org.atmosphere.vibe.platform.bridge.netty4.NettyServerWebSocketTest.java
License:Apache License
@Override protected void startServer() { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*w ww .j av a 2 s . co m*/ public void channelActive(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()).addLast(new VibeServerCodec() { @Override protected boolean accept(HttpRequest req) { return URI.create(req.getUri()).getPath().equals("/test"); } }.onwebsocket(performer.serverAction())); } }); channels.add(bootstrap.bind(port).channel()); }
From source file:org.bridje.http.impl.HttpServerChannelHandler.java
License:Apache License
private void readHeaders(ChannelHandlerContext ctx, HttpRequest msg) { if (req == null && context == null) { context = new HttpBridletContextImpl(); req = new HttpBridletRequestImpl(msg); QueryStringDecoder decoderQuery = new QueryStringDecoder(msg.getUri()); req.setQueryString(decoderQuery.parameters()); req.setCookies(parseCookies(msg.headers().get(COOKIE))); // new getMethod if (req.isForm()) { decoder = new HttpPostRequestDecoder(FACTORY, msg); }//from w w w.ja va 2 s . c o m } else { sendBadRequest(ctx); } }
From source file:org.ftccommunity.ftcxtensible.networking.http.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String page;//w w w. jav a2 s. co m if (req.getMethod() == HttpMethod.POST) { LinkedList<InterfaceHttpData> postData = new LinkedList<>(); HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), req); postRequestDecoder.getBodyHttpDatas(); for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { postData.add(data); } } context.addPostData(postData); } if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } HttpResponseStatus responseStatus = OK; String uri = (req.getUri().equals("/") ? context.getServerSettings().getIndex() : req.getUri()); if (uri.equals(context.getServerSettings().getHardwareMapJsonPage())) { GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization(); Gson gson = gsonBuilder.create(); HardwareMap hardwareMap = context.getHardwareMap(); page = gson.toJson(ImmutableSet.copyOf(hardwareMap.dcMotor)); } else if (uri.equals(context.getServerSettings().getLogPage())) { page = context.getStatus().getLog(); } else { if (cache.containsKey(uri)) { page = cache.get(uri); responseStatus = NOT_MODIFIED; } else { try { page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8); } catch (FileNotFoundException e) { Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri); page = "File Not Found!"; responseStatus = NOT_FOUND; } catch (IOException e) { page = "An Error Occurred!\n" + e.toString(); responseStatus = NOT_FOUND; Log.e("NET_OP_MODE::", e.toString(), e); } cache.put(uri, page); } } boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8))); String extension = MimeTypeMap.getFileExtensionFromUrl(uri); String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension)) + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8")); 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); } } }
From source file:org.ftccommunity.ftcxtensible.networking.http.RobotHttpServerHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; String page;//ww w .j a va 2 s . com if (req.getMethod() == HttpMethod.POST) { LinkedList<InterfaceHttpData> postData = new LinkedList<>(); HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder( new DefaultHttpDataFactory(false), req); postRequestDecoder.getBodyHttpDatas(); for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) { if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) { postData.add(data); } } context.addPostData(postData); } if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } HttpResponseStatus responseStatus = OK; String uri = (req.getUri().equals("/") ? context.serverSettings().getIndex() : req.getUri()); if (uri.equals(context.serverSettings().getHardwareMapJsonPage())) { GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization(); Gson gson = gsonBuilder.create(); ExtensibleHardwareMap hardwareMap = context.hardwareMap(); page = gson.toJson(hardwareMap.dcMotors()); } else if (uri.equals(context.serverSettings().getLogPage())) { page = context.status().getLog(); } else { if (cache.containsKey(uri)) { page = cache.get(uri); responseStatus = NOT_MODIFIED; } else { try { page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8); } catch (FileNotFoundException e) { Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri); page = "File Not Found!"; responseStatus = NOT_FOUND; } catch (IOException e) { page = "An Error Occurred!\n" + e.toString(); responseStatus = NOT_FOUND; Log.e("NET_OP_MODE::", e.toString(), e); } cache.put(uri, page); } } boolean keepAlive = HttpHeaders.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8))); String extension = MimeTypeMap.getFileExtensionFromUrl(uri); String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension)) + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8")); 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); } } }
From source file:org.glowroot.agent.plugin.netty.Http1ServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; @SuppressWarnings("deprecation") String uri = request.getUri(); if (uri.equals("/exception")) { throw new Exception("Test"); }//from ww w . j a v a 2 s .com if (uri.equals("/chunked")) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set("transfer-encoding", "chunked"); response.headers().set("content-type", "text/plain"); ctx.write(response); final File file = File.createTempFile("glowroot-netty-plugin-it-", ".txt"); final ChunkedFile chunkedFile = new ChunkedFile(file); Files.write(CONTENT, file); ctx.write(chunkedFile).addListener(ChannelFutureListener.CLOSE) .addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> arg0) throws Exception { chunkedFile.close(); if (!file.delete()) { throw new IllegalStateException("Could not delete file: " + file.getPath()); } } }); return; } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set("Content-Type", "text/plain"); response.headers().set("Content-Length", response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:org.glowroot.local.ui.TraceDetailHttpService.java
License:Apache License
@Override public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { QueryStringDecoder decoder = new QueryStringDecoder(request.getUri()); String path = decoder.path(); String traceComponent = path.substring(path.lastIndexOf('/') + 1); List<String> traceIds = decoder.parameters().get("trace-id"); checkNotNull(traceIds, "Missing trace id in query string: %s", request.getUri()); String traceId = traceIds.get(0); logger.debug("handleRequest(): traceComponent={}, traceId={}", traceComponent, traceId); CharSource charSource = getDetailCharSource(traceComponent, traceId); if (charSource == null) { return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); }/* ww w .java 2 s .com*/ HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); response.headers().set(Names.CONTENT_TYPE, "application/json; charset=UTF-8"); boolean keepAlive = HttpHeaders.isKeepAlive(request); if (keepAlive && !request.getProtocolVersion().isKeepAliveDefault()) { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); } HttpServices.preventCaching(response); ctx.write(response); ChannelFuture future = ctx.write(ChunkedInputs.fromReader(charSource.openStream())); HttpServices.addErrorListener(future); if (!keepAlive) { HttpServices.addCloseListener(future); } // return null to indicate streaming return null; }
From source file:org.glowroot.local.ui.TraceExportHttpService.java
License:Apache License
@Override public @Nullable FullHttpResponse handleRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { String uri = request.getUri(); String id = uri.substring(uri.lastIndexOf('/') + 1); logger.debug("handleRequest(): id={}", id); TraceExport export = traceCommonService.getExport(id); if (export == null) { logger.warn("no trace found for id: {}", id); return new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); }//from w ww .j a v a 2 s.c o m ChunkedInput<HttpContent> in = getExportChunkedInput(export); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); response.headers().set(CONTENT_TYPE, MediaType.ZIP.toString()); response.headers().set("Content-Disposition", "attachment; filename=" + getFilename(export.trace()) + ".zip"); boolean keepAlive = HttpHeaders.isKeepAlive(request); if (keepAlive && !request.getProtocolVersion().isKeepAliveDefault()) { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); } HttpServices.preventCaching(response); ctx.write(response); ChannelFuture future = ctx.write(in); HttpServices.addErrorListener(future); if (!keepAlive) { HttpServices.addCloseListener(future); } // return null to indicate streaming return null; }