List of usage examples for io.netty.channel.embedded EmbeddedChannel close
@Override
public final ChannelFuture close()
From source file:com.cloudera.livy.client.local.rpc.TestKryoMessageCodec.java
License:Apache License
@Test public void testEmbeddedChannel() throws Exception { EmbeddedChannel c = new EmbeddedChannel(new LoggingHandler(getClass()), new KryoMessageCodec(0)); c.writeAndFlush(MESSAGE);/* www . ja va2 s . c o m*/ assertEquals(1, c.outboundMessages().size()); assertFalse(MESSAGE.getClass().equals(c.outboundMessages().peek().getClass())); c.writeInbound(c.readOutbound()); assertEquals(1, c.inboundMessages().size()); assertEquals(MESSAGE, c.readInbound()); c.close(); }
From source file:com.couchbase.client.core.endpoint.view.ViewHandlerTest.java
License:Apache License
@Test public void shouldFireKeepAlive() throws Exception { final AtomicInteger keepAliveEventCounter = new AtomicInteger(); final AtomicReference<ChannelHandlerContext> ctxRef = new AtomicReference(); ViewHandler testHandler = new ViewHandler(endpoint, responseRingBuffer, queue, false) { @Override// w w w. ja va2s . com public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); ctxRef.compareAndSet(null, ctx); } @Override protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) { assertEquals(1, keepAliveEventCounter.incrementAndGet()); } @Override protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) { assertEquals(2, keepAliveEventCounter.incrementAndGet()); } }; EmbeddedChannel channel = new EmbeddedChannel(testHandler); //test idle event triggers a view keepAlive request and hook is called testHandler.userEventTriggered(ctxRef.get(), IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT); assertEquals(1, keepAliveEventCounter.get()); assertTrue(queue.peek() instanceof ViewHandler.KeepAliveRequest); ViewHandler.KeepAliveRequest keepAliveRequest = (ViewHandler.KeepAliveRequest) queue.peek(); //test responding to the request with http response is interpreted into a KeepAliveResponse and hook is called HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); channel.writeInbound(response); ViewHandler.KeepAliveResponse keepAliveResponse = keepAliveRequest.observable() .cast(ViewHandler.KeepAliveResponse.class).timeout(1, TimeUnit.SECONDS).toBlocking().single(); assertEquals(2, keepAliveEventCounter.get()); assertEquals(ResponseStatus.NOT_EXISTS, keepAliveResponse.status()); //different channel, needs to be closed to release the internal responseContent channel.close().awaitUninterruptibly(); }
From source file:com.ebay.jetstream.http.netty.client.HttpClient.java
License:MIT License
public void post(URI uri, Object content, Map<String, String> headers, ResponseFuture responsefuture) throws Exception { if (m_shutDown.get()) { throw new IOException("IO has been Shutdown = "); }// w ww. jav a 2 s .c o m if (uri == null) throw new NullPointerException("uri is null or incorrect"); if (!m_started.get()) { synchronized (this) { if (!m_started.get()) { start(); m_started.set(true); } } } ByteBuf byteBuf = Unpooled.buffer(m_config.getInitialRequestBufferSize()); ByteBufOutputStream outputStream = new ByteBufOutputStream(byteBuf); // transform to json try { m_mapper.writeValue(outputStream, content); } catch (JsonGenerationException e) { throw e; } catch (JsonMappingException e) { throw e; } catch (IOException e) { throw e; } finally { outputStream.close(); } EmbeddedChannel encoder; String contenteEncoding; if ("gzip".equals(m_config.getCompressEncoder())) { encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP, 1)); contenteEncoding = "gzip"; } else if ("deflate".equals(m_config.getCompressEncoder())) { encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB, 1)); contenteEncoding = "deflate"; } else { encoder = null; contenteEncoding = null; } if (encoder != null) { encoder.config().setAllocator(UnpooledByteBufAllocator.DEFAULT); encoder.writeOutbound(byteBuf); encoder.finish(); byteBuf = (ByteBuf) encoder.readOutbound(); encoder.close(); } DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toString(), byteBuf); if (contenteEncoding != null) { HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_ENCODING, contenteEncoding); } HttpHeaders.setHeader(request, HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate"); HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json"); HttpHeaders.setContentLength(request, byteBuf.readableBytes()); if (isKeepAlive()) HttpHeaders.setHeader(request, HttpHeaders.Names.CONNECTION, "keep-alive"); if (headers != null) { @SuppressWarnings("rawtypes") Iterator it = headers.entrySet().iterator(); while (it.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) it.next(); HttpHeaders.setHeader(request, (String) pairs.getKey(), pairs.getValue()); } } if (responsefuture != null) { RequestId reqid = RequestId.newRequestId(); m_responseDispatcher.add(reqid, responsefuture); HttpHeaders.setHeader(request, "X_EBAY_REQ_ID", reqid.toString()); // we expect this to be echoed in the response used for correlation. } if (m_dataQueue.size() < m_workQueueCapacity) { ProcessHttpWorkRequest workRequest = new ProcessHttpWorkRequest(this, uri, request); if (!m_dataQueue.offer(workRequest)) { if (responsefuture != null) { responsefuture.setFailure(); m_responseDispatcher.remove(request.headers().get("X_EBAY_REQ_ID")); } } } else { throw new IOException("downstream Queue is full "); } }
From source file:com.github.ambry.rest.HealthCheckHandlerTest.java
License:Open Source License
/** * Does a test to see that a health check request results in expected response from the health check handler * @param httpMethod the {@link HttpMethod} for the request. * @param keepAlive true if keep alive has to be set in the request, false otherwise * @throws IOException// w ww .j av a2 s . c o m */ private void testHealthCheckRequest(HttpMethod httpMethod, boolean isServiceUp, boolean keepAlive) throws IOException { EmbeddedChannel channel = createChannel(); for (int i = 0; i < 2; i++) { if (isServiceUp) { restServerState.markServiceUp(); } HttpRequest request = RestTestUtils.createRequest(httpMethod, healthCheckUri, null); HttpHeaders.setKeepAlive(request, keepAlive); FullHttpResponse response = sendRequestAndGetResponse(channel, request); HttpResponseStatus httpResponseStatus = (isServiceUp) ? HttpResponseStatus.OK : HttpResponseStatus.SERVICE_UNAVAILABLE; assertEquals("Unexpected response status", httpResponseStatus, response.getStatus()); String expectedStr = (isServiceUp) ? goodStr : badStr; assertEquals("Unexpected content", expectedStr, RestTestUtils.getContentString(response)); restServerState.markServiceDown(); if (keepAlive && isServiceUp) { Assert.assertTrue("Channel should not be closed ", channel.isOpen()); } else { Assert.assertFalse("Channel should have been closed by now ", channel.isOpen()); channel = createChannel(); } } channel.close(); }
From source file:com.github.ambry.rest.HealthCheckHandlerTest.java
License:Open Source License
/** * Does a test to see that a non health check request results in expected responses * @param httpMethod the {@link HttpMethod} for the request. * @param uri Uri to be used during the request * @throws IOException/*from ww w . j a v a 2s .c om*/ */ private void testNonHealthCheckRequest(HttpMethod httpMethod, String uri) throws IOException { EmbeddedChannel channel = createChannel(); HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, null); FullHttpResponse response = sendRequestAndGetResponse(channel, request); assertEquals("Unexpected response status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected content", httpMethod.toString(), RestTestUtils.getContentString(response)); channel.close(); }
From source file:com.github.ambry.rest.NettyResponseChannelTest.java
License:Open Source License
/** * Tests that HEAD returns no body in error responses. *//*from w w w .j a v a2s. c o m*/ @Test public void noBodyForHeadTest() { EmbeddedChannel channel = createEmbeddedChannel(); for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS .entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils.createRequest(HttpMethod.HEAD, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (response instanceof FullHttpResponse) { // assert that there is no content assertEquals("The response should not contain content", 0, ((FullHttpResponse) response).content().readableBytes()); } else { HttpContent content = (HttpContent) channel.readOutbound(); assertTrue("End marker should be received", content instanceof LastHttpContent); } assertNull("There should be no more data in the channel", channel.readOutbound()); boolean shouldBeAlive = !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES .contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } channel.close(); }
From source file:com.github.ambry.rest.NettyResponseChannelTest.java
License:Open Source License
/** * Tests keep-alive for different HTTP methods and error statuses. *///from w w w.j a v a2 s . co m @Test public void keepAliveTest() { HttpMethod[] HTTP_METHODS = { HttpMethod.POST, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE }; EmbeddedChannel channel = createEmbeddedChannel(); for (HttpMethod httpMethod : HTTP_METHODS) { for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS .entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils.createRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (!(response instanceof FullHttpResponse)) { // empty the channel while (channel.readOutbound() != null) { } } boolean shouldBeAlive = !httpMethod.equals(HttpMethod.POST) && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } } channel.close(); }
From source file:com.github.ambry.rest.NettyResponseChannelTest.java
License:Open Source License
/** * Creates a channel and sends a request (that induces an exception) to the {@link EmbeddedChannel}. Checks the * response for the {@code expectedResponseStatus}. * @param restServiceErrorCode the {@link RestServiceErrorCode} to set in the header. If {@code null}, the testing uri * {@link TestingUri#OnResponseCompleteWithNonRestException} is used. Otherwise the * testing uri {@link TestingUri#OnResponseCompleteWithRestException} is used. * @param expectedResponseStatus the {@link HttpResponseStatus} that is expected in the response. * @param shouldClose {@code true} if the channel should have been closed on this exception. {@code false} if not. *//*from ww w. jav a 2 s . com*/ private void doOnResponseCompleteWithExceptionTest(RestServiceErrorCode restServiceErrorCode, HttpResponseStatus expectedResponseStatus, boolean shouldClose) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); TestingUri uri = TestingUri.OnResponseCompleteWithNonRestException; if (restServiceErrorCode != null) { uri = TestingUri.OnResponseCompleteWithRestException; httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, restServiceErrorCode); } EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(RestTestUtils.createRequest(HttpMethod.GET, uri.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status for " + restServiceErrorCode, expectedResponseStatus, response.getStatus()); assertEquals("Channel state (open/close) not as expected for " + restServiceErrorCode, shouldClose, !channel.isActive()); assertEquals("Connection header should be consistent with channel state for " + restServiceErrorCode, shouldClose, !HttpHeaders.isKeepAlive(response)); channel.close(); }
From source file:com.github.ambry.rest.PublicAccessLogHandlerTest.java
License:Open Source License
/** * Tests for the request handling flow with transfer encoding chunked *//* www .ja v a2s .c om*/ @Test public void doRequestHandleWithChunkedResponse() throws IOException { EmbeddedChannel channel = createChannel(); HttpHeaders headers = new DefaultHttpHeaders(); headers.add(EchoMethodHandler.IS_CHUNKED, "true"); HttpRequest request = RestTestUtils.createRequest(HttpMethod.POST, "POST", headers); HttpHeaders.setKeepAlive(request, true); sendRequestCheckResponse(channel, request, "POST", headers, false, true); Assert.assertTrue("Channel should not be closed ", channel.isOpen()); channel.close(); }
From source file:com.github.ambry.rest.PublicAccessLogHandlerTest.java
License:Open Source License
/** * Does a test to see that request handling results in expected entries in public access log * @param httpMethod the {@link HttpMethod} for the request. * @param uri Uri to be used during the request * @param testErrorCase true if error case has to be tested, false otherwise * @throws IOException//from w w w. j ava2 s . c o m */ private void doRequestHandleTest(HttpMethod httpMethod, String uri, boolean testErrorCase) throws IOException { EmbeddedChannel channel = createChannel(); List<HttpHeaders> httpHeadersList = getHeadersList(); for (HttpHeaders headers : httpHeadersList) { HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, headers); HttpHeaders.setKeepAlive(request, true); sendRequestCheckResponse(channel, request, uri, headers, testErrorCase, false); if (!testErrorCase) { Assert.assertTrue("Channel should not be closed ", channel.isOpen()); } else { Assert.assertFalse("Channel should have been closed ", channel.isOpen()); channel = createChannel(); } } channel.close(); }