List of usage examples for io.netty.handler.codec.http FullHttpRequest copy
@Override FullHttpRequest copy();
From source file:com.zank.websocket.server.ServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/* w w w . j a va 2 s . co m*/ } // Send the demo page and favicon.ico if ("/".equals(req.uri())) { ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaderUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); return; } if ("/favicon.ico".equals(req.uri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } ctx.fireChannelRead(req.copy()); }
From source file:etcd.client.HttpClient.java
License:Open Source License
private void send(Iterator<ServerList.Server> serverIterator, FullHttpRequest request, Consumer<Response> completionHandler) { final ServerList.Server server = serverIterator.next(); final URI address = server.getAddress(); final ChannelFuture connectFuture = bootstrap.connect(address.getHost(), address.getPort()); final FullHttpRequest requestCopy = request.copy(); requestCopy.retain();// w w w. j a v a 2 s. c om final Channel channel = connectFuture.channel(); channel.attr(REQUEST_KEY).set(requestCopy); channel.attr(ATTRIBUTE_KEY).set(completionHandler); connectFuture.addListener((future) -> { if (future.isSuccess()) { channel.writeAndFlush(request); } else { server.connectionFailed(); if (autoReconnect && serverIterator.hasNext()) { send(serverIterator, request, completionHandler); } else { invokeCompletionHandler(completionHandler, new Response(null, new EtcdException(future.cause()))); } } }); }
From source file:io.blobkeeper.server.handler.FileDeleteHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { setContext();/* w ww.ja v a 2 s. c o m*/ if (request.getMethod() == POST) { context.fireChannelRead(request.copy()); return; } addWriterBack(context); if (log.isTraceEnabled()) { log.trace("Request is: {}", request); } if (request.getUri().equals("/favicon.ico")) { sendError(context, NOT_FOUND, createError(INVALID_REQUEST, "No favorite icon here")); return; } if (!request.getDecoderResult().isSuccess()) { sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "Strange request given")); return; } if (request.getMethod() != DELETE) { sendError(context, METHOD_NOT_ALLOWED, createError(INVALID_REQUEST, "Only DELETE requests are acceptable")); return; } handleApiRequest(context, request); }
From source file:io.blobkeeper.server.handler.FileReaderHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { setContext();/*from w w w.j a va 2 s.c o m*/ if (request.getMethod() == POST) { context.fireChannelRead(request.copy()); return; } if (request.getMethod() == DELETE) { context.fireChannelRead(request.copy()); return; } addWriterBack(context); if (log.isTraceEnabled()) { log.trace("Request is: {}", request); } if (request.getUri().equals("/favicon.ico")) { sendError(context, HttpResponseStatus.NOT_FOUND, createError(INVALID_REQUEST, "No favorite icon here")); return; } if (!request.getDecoderResult().isSuccess()) { sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "Strange request given")); return; } if (request.getMethod() != GET) { sendError(context, METHOD_NOT_ALLOWED, createError(INVALID_REQUEST, "Only GET requests are acceptable")); return; } String uri = request.getUri(); final long fileId = getId(uri); final int typeId = getType(uri); if (NOT_FOUND == fileId) { if (tryHandleApiRequest(context, request)) { return; } else { log.error("No id"); sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No id")); return; } } if (NOT_FOUND == typeId) { log.error("No type id"); sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No type id")); return; } File readerFile = null; IndexElt indexElt; boolean modified; try { log.debug("Id {}", fileId); indexElt = indexService.getById(fileId, typeId); log.debug("Index elt is {}", indexElt); if (null != indexElt) { if (indexElt.isDeleted()) { sendError(context, GONE, createError(DELETED, "File was deleted")); return; } if (indexElt.isAuthRequired()) { String authToken = MetadataParser.getAuthToken(request); if (authToken == null || !indexElt.isAllowed(authToken)) { log.error("You have no permission to see this file {} : token {}", indexElt.getId(), authToken); sendError(context, HttpResponseStatus.FORBIDDEN, createError(ErrorCode.FORBIDDEN, "You have no permission to see this file")); return; } } modified = isModified(indexElt, request); if (modified) { readerFile = fileStorage.getFile(indexElt); } } else { log.error("Index elt not found"); sendError(context, HttpResponseStatus.NOT_FOUND, createError(INVALID_REQUEST, "Index elt not found")); return; } } catch (Exception e) { log.error("Unknown error", e); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "Unknown error")); return; } if (!modified) { sendNotModified(context, indexElt, request); return; } if (null == readerFile) { log.error("Can't find reader file"); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "No reader file")); return; } if (readerFile.getLength() - indexElt.getOffset() < indexElt.getLength()) { String errorMessage = String.format("Reader file length less than index elt %s < %s", readerFile.getLength() - indexElt.getOffset(), indexElt.getLength()); log.error(errorMessage); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage)); return; } if (FileUtils.isFileEmpty(readerFile, indexElt)) { String errorMessage = String.format("File %s is empty", indexElt); log.error(errorMessage); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage)); return; } HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); MetadataParser.copyMetadata(indexElt.getHeaders(), response); addCacheHeaders(response, indexElt); setContentLength(response, indexElt.getLength()); if (isKeepAlive(request)) { response.headers().set(CONNECTION, KEEP_ALIVE); } context.write(response); // Write the content. context.write( new UnClosableFileRegion(readerFile.getFileChannel(), indexElt.getOffset(), indexElt.getLength()), context.voidPromise()); // Write the end marker ChannelFuture lastContentFuture = context.writeAndFlush(EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(CLOSE); } }
From source file:org.ballerinalang.test.util.client.HttpClient.java
License:Open Source License
public LinkedList<FullHttpResponse> sendTwoInPipeline(FullHttpRequest httpRequest) { CountDownLatch latch = new CountDownLatch(2); this.waitForConnectionClosureLatch = new CountDownLatch(2); this.responseHandler.setLatch(latch); this.responseHandler.setWaitForConnectionClosureLatch(this.waitForConnectionClosureLatch); httpRequest.headers().set(HttpHeaderNames.HOST, host + ":" + port); this.connectedChannel.writeAndFlush(httpRequest.copy()); this.connectedChannel.writeAndFlush(httpRequest); try {// w ww.j a v a 2s. c om latch.await(); } catch (InterruptedException e) { log.warn("Interrupted before receiving the response"); } return this.responseHandler.getHttpFullResponses(); }
From source file:org.ebayopensource.scc.debug.DebugManager.java
License:Apache License
/** * Issue a debug request when debugging is enabled. * * @param httpObject Http request of client * @param m_ctx Netty context/*from www . j a va2s . c om*/ * @param fromDebugFilter Indicator shows if the request require to be forwarded * @return An indicator showing if debug manager consumes the request. If true, the caller needs to stop handling request. */ public void issueDebugRequest(FullHttpRequest httpObject, final ChannelHandlerContext m_ctx, boolean fromDebugFilter) { if (debugEnabled()) { final FullHttpRequest request = httpObject.copy(); if (fromDebugFilter) { try { if (ssl(request)) { Field field = ClientToProxyConnection.class.getDeclaredField("mitming"); field.setAccessible(true); field.set(m_ctx.handler(), true); } } catch (Exception e) { LOGGER.error(e.getMessage()); } String key = m_policyManager.generateCacheKey(request); FullHttpResponse cacheResponse = m_policyManager.getCacheManager().get(key); CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse); Attribute<CacheResultVerifier> debugging = m_ctx.attr(DEBUG_RESULT); debugging.set(verifier); } else { executor.execute(new Runnable() { @Override public void run() { forwardDebugRequest(request); } }); } } }
From source file:org.ebayopensource.scc.debug.DebugManagerTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") public void testIssueDebugRequest_fromDebugFilter() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpRequest request = Mockito.mock(FullHttpRequest.class); FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(request.copy()).thenReturn(request); Mockito.when(m_cacheManager.get("test_req")).thenReturn(cacheResponse); Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn("test_req"); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); debugManager.issueDebugRequest(request, ctx, true); CacheResultVerifier verifier = new CacheResultVerifier("test_req", request, cacheResponse); Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier)); }
From source file:org.ebayopensource.scc.debug.DebugManagerTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") public void testIssueDebugRequest_sslFromDebugFilter() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpRequest request = Mockito.mock(FullHttpRequest.class); FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.handler()).thenReturn(clientToProxyConnection); Mockito.when(request.copy()).thenReturn(request); String key = "https://serverHostAndPort=www.ebay.com:443"; Mockito.when(m_cacheManager.get(key)).thenReturn(cacheResponse); Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn(key); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); debugManager.issueDebugRequest(request, ctx, true); Assert.assertTrue((Boolean) readField(clientToProxyConnection, "mitming")); CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse); Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier)); }
From source file:org.ebayopensource.scc.debug.DebugManagerTest.java
License:Apache License
@Test public void testIssueDebugRequest_sslNotFromDebugFilter() { MockitoAnnotations.initMocks(this); Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(request.copy()).thenReturn(request); writeField(debugManager, "executor", executor); Mockito.doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Exception { writeField(debugManager, "m_policyManager", m_policyManager); Mockito.when(m_policyManager.generateCacheKey(Mockito.any(FullHttpRequest.class))) .thenReturn("https://serverHostAndPort=www.ebay.com:443"); ChannelFuture future = Mockito.mock(ChannelFuture.class); Mockito.when(debugSslChannel.closeFuture()).thenReturn(future); writeField(debugManager, "debugSslChannel", debugSslChannel); writeField(debugManager, "debugChannel", debugChannel); Object[] args = invocation.getArguments(); Runnable runnable = (Runnable) args[0]; runnable.run();/*from w w w .j a v a2 s. c om*/ Mockito.verify(debugSslChannel, Mockito.times(1)).writeAndFlush(request); Mockito.verify(debugChannel, Mockito.times(0)).writeAndFlush(request); return null; } }).when(executor).execute(Mockito.any(Runnable.class)); debugManager.issueDebugRequest(request, ctx, false); }
From source file:org.ebayopensource.scc.debug.DebugManagerTest.java
License:Apache License
@Test public void testIssueDebugRequest_notFromDebugFilter() { MockitoAnnotations.initMocks(this); Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); final FullHttpRequest request = Mockito.mock(FullHttpRequest.class); final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn("test_req"); Mockito.when(request.copy()).thenReturn(request); writeField(debugManager, "executor", executor); Mockito.doAnswer(new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Exception { writeField(debugManager, "m_policyManager", m_policyManager); Object[] args = invocation.getArguments(); Runnable runnable = (Runnable) args[0]; writeField(debugManager, "debugSslChannel", debugSslChannel); writeField(debugManager, "debugChannel", debugChannel); ChannelFuture future = Mockito.mock(ChannelFuture.class); Mockito.when(debugChannel.closeFuture()).thenReturn(future); runnable.run();/* ww w. ja va2 s. c o m*/ Mockito.verify(debugChannel, Mockito.times(1)).writeAndFlush(request); Mockito.verify(debugSslChannel, Mockito.times(0)).writeAndFlush(request); return null; } }).when(executor).execute(Mockito.any(Runnable.class)); debugManager.issueDebugRequest(request, ctx, false); }