static ChannelHandler forbiddenHttpRequestResponder() { return new SimpleChannelHandler() { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (!(e.getMessage() instanceof WebSocketFrame)) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN); ctx.getChannel().write(response); } else { ctx.sendUpstream(e); } } }; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (!(e.getMessage() instanceof WebSocketFrame)) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN); ctx.getChannel().write(response); } else { ctx.sendUpstream(e); } } };
public HttpResponse sendResponse(HttpResponseStatus responseCode, String responseBody) { String actualResponseBody = responseBody + "\n"; HttpResponse response = new DefaultHttpResponse(HTTP_1_1, responseCode); response.setHeader(CONTENT_LENGTH, actualResponseBody.length()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write(actualResponseBody.getBytes()); } catch(IOException e) { logger.error("IOException while trying to write the outputStream for an admin response", e); throw new RuntimeException(e); } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); response.setContent(responseContent); if (logger.isDebugEnabled()) { logger.debug("Sent " + response); } return response; }
@Override protected HttpMessage createMessage(String[] initialLine) { return new DefaultHttpResponse( HttpVersion.valueOf(initialLine[0]), new HttpResponseStatus(Integer.valueOf(initialLine[1]), initialLine[2])); }
@Override protected HttpMessage createMessage(String[] initialLine) throws Exception { return new DefaultHttpResponse( RtspVersions.valueOf(initialLine[0]), new HttpResponseStatus(Integer.valueOf(initialLine[1]), initialLine[2])); }
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) { // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NO_CONTENT); // Set the right headers response.setHeader(CONTENT_LENGTH, "0"); // Write the response to the Netty Channel if(logger.isDebugEnabled()) { String keyStr = RestUtils.getKeyHexString(key); debugLog("DELETE", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), 0); } this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.DELETE); } } }
/** * Return that we need cannot not support the web socket version * * @param channel * Channel */ public ChannelFuture sendUnsupportedWebSocketVersionResponse(Channel channel) { HttpResponse res = new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS); res.setStatus(HttpResponseStatus.UPGRADE_REQUIRED); res.headers().set(Names.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue()); return channel.write(res); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof WebSocketHandshakeException) { DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); response.setContent(ChannelBuffers.wrappedBuffer(e.getCause().getMessage().getBytes())); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } else { ctx.getChannel().close(); } }
HttpResponse httpResponse = new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse, null);
HttpResponse httpResponse = new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse, null);
@Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { String base64Key = RestUtils.encodeVoldemortKey(key.get()); String contentLocationKey = "/" + this.storeName + "/" + base64Key; List<VectorClock> vectorClocks = new ArrayList<VectorClock>(); for(Version versionedValue: versionedValues) { VectorClock vectorClock = (VectorClock) versionedValue; vectorClocks.add(vectorClock); numVectorClockEntries += vectorClock.getVersionMap().size(); } String eTags = RestUtils.getSerializedVectorClocks(vectorClocks); byte[] responseContent = eTags.getBytes(); ChannelBuffer responseContentBuffer = ChannelBuffers.dynamicBuffer(responseContent.length); responseContentBuffer.writeBytes(responseContent); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); response.setHeader(CONTENT_LOCATION, contentLocationKey); // Copy the data into the payload response.setContent(responseContentBuffer); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel this.messageEvent.getChannel().write(response); }
protected void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.headers().add(CONTENT_TYPE, "text/plain; charset=UTF-8"); // Put shuffle version into http header response.headers().add(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); response.headers().add(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }
/** * Writes all error responses to the client. * * TODO REST-Server 1. collect error stats * * @param messageEvent - for retrieving the channel details * @param status - error code * @param message - error message */ public static void writeErrorResponse(MessageEvent messageEvent, HttpResponseStatus status, String message) { // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer("Failure: " + status.toString() + ". " + message + "\r\n", CharsetUtil.UTF_8)); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel messageEvent.getChannel().write(response); } }
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); httpResponse.setContent(ChannelBuffers.buffer(0)); httpResponseHandler.handleResponse(httpResponse, null);
final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setChunked(true); ClientResponse<InputStream> clientResponse = responseHandler.handleResponse(response, null);
@Test public void retryOnChannelException() throws IOException { final HttpClient httpClient = EasyMock.createNiceMock(HttpClient.class); EasyMock.expect(httpClient.go(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject())) .andReturn(Futures.immediateFailedFuture(new ChannelException("IndexTaskClientTest"))) .times(2); EasyMock.expect(httpClient.go(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject())) .andReturn( Futures.immediateFuture( new FullResponseHolder( HttpResponseStatus.OK, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new StringBuilder() ) ) ) .once(); EasyMock.replay(httpClient); try (IndexTaskClient indexTaskClient = buildIndexTaskClient(httpClient, id -> TaskLocation.create(id, 8000, -1))) { final FullResponseHolder response = indexTaskClient.submitRequestWithEmptyContent( "taskId", HttpMethod.GET, "test", null, true ); Assert.assertEquals(HttpResponseStatus.OK, response.getStatus()); } }
@Test public void simpleMultiStreamTest() throws IOException { Iterator<byte[]> it = BYTE_LIST.iterator(); SequenceInputStreamResponseHandler responseHandler = new SequenceInputStreamResponseHandler(); final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setChunked(true); ClientResponse<InputStream> clientResponse = responseHandler.handleResponse(response, null); long chunkNum = 0; while (it.hasNext()) { final DefaultHttpChunk chunk = new DefaultHttpChunk(new BigEndianHeapChannelBuffer(it.next())); clientResponse = responseHandler.handleChunk(clientResponse, chunk, ++chunkNum); } clientResponse = responseHandler.done(clientResponse); final InputStream stream = clientResponse.getObj(); final InputStream expectedStream = new ByteArrayInputStream(allBytes); int read = 0; while (read < allBytes.length) { final byte[] expectedBytes = new byte[Math.min(RANDOM.nextInt(128), allBytes.length - read)]; final byte[] actualBytes = new byte[expectedBytes.length]; fillBuff(stream, actualBytes); fillBuff(expectedStream, expectedBytes); Assert.assertArrayEquals(expectedBytes, actualBytes); read += expectedBytes.length; } Assert.assertEquals(allBytes.length, responseHandler.getByteCount()); }
@Test public void simpleSingleStreamTest() throws IOException { SequenceInputStreamResponseHandler responseHandler = new SequenceInputStreamResponseHandler(); final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setChunked(false); response.setContent(new BigEndianHeapChannelBuffer(allBytes)); ClientResponse<InputStream> clientResponse = responseHandler.handleResponse(response, null); clientResponse = responseHandler.done(clientResponse); final InputStream stream = clientResponse.getObj(); final InputStream expectedStream = new ByteArrayInputStream(allBytes); int read = 0; while (read < allBytes.length) { final byte[] expectedBytes = new byte[Math.min(RANDOM.nextInt(128), allBytes.length - read)]; final byte[] actualBytes = new byte[expectedBytes.length]; fillBuff(stream, actualBytes); fillBuff(expectedStream, expectedBytes); Assert.assertArrayEquals(expectedBytes, actualBytes); read += expectedBytes.length; } Assert.assertEquals(allBytes.length, responseHandler.getByteCount()); }
@Test public void alignedMultiStreamTest() throws IOException { Iterator<byte[]> it = BYTE_LIST.iterator(); SequenceInputStreamResponseHandler responseHandler = new SequenceInputStreamResponseHandler(); final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setChunked(true); ClientResponse<InputStream> clientResponse = responseHandler.handleResponse(response, null); long chunkNum = 0; while (it.hasNext()) { final DefaultHttpChunk chunk = new DefaultHttpChunk(new BigEndianHeapChannelBuffer(it.next())); clientResponse = responseHandler.handleChunk(clientResponse, chunk, ++chunkNum); } clientResponse = responseHandler.done(clientResponse); final InputStream stream = clientResponse.getObj(); final InputStream expectedStream = new ByteArrayInputStream(allBytes); for (byte[] bytes : BYTE_LIST) { final byte[] expectedBytes = new byte[bytes.length]; final byte[] actualBytes = new byte[expectedBytes.length]; fillBuff(stream, actualBytes); fillBuff(expectedStream, expectedBytes); Assert.assertArrayEquals(expectedBytes, actualBytes); Assert.assertArrayEquals(expectedBytes, bytes); } Assert.assertEquals(allBytes.length, responseHandler.getByteCount()); }
@Test(expected = TesterException.class) public void testExceptionalSingleStream() throws IOException { SequenceInputStreamResponseHandler responseHandler = new SequenceInputStreamResponseHandler(); final HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setChunked(false); response.setContent( new BigEndianHeapChannelBuffer(allBytes) { @Override public void getBytes(int index, byte[] dst, int dstIndex, int length) { if (dstIndex + length >= allBytes.length) { throw new TesterException(); } super.getBytes(index, dst, dstIndex, length); } } ); ClientResponse<InputStream> clientResponse = responseHandler.handleResponse(response, null); clientResponse = responseHandler.done(clientResponse); final InputStream stream = clientResponse.getObj(); final byte[] buff = new byte[allBytes.length]; fillBuff(stream, buff); }