List of usage examples for io.netty.channel.embedded EmbeddedChannel alloc
@Override
public ByteBufAllocator alloc()
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java
License:Open Source License
/** * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a * Content-Length header.//from ww w.j a v a 2s . co m */ @Test public void httpErrorsWithContentAreSupported() throws IOException { EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); ByteBuf errorMessage = ByteBufUtil.writeAscii(ch.alloc(), "Error message"); response.headers().set(HttpHeaders.HOST, "localhost"); response.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(errorMessage.readableBytes())); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); ch.writeInbound(response); // The promise must not be done because we haven't received the error message yet. assertThat(writePromise.isDone()).isFalse(); ch.writeInbound(new DefaultHttpContent(errorMessage)); ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); // No data should have been written to the OutputStream and it should have been closed. assertThat(out.size()).isEqualTo(0); // The caller is responsible for closing the stream. verify(out, never()).close(); assertThat(ch.isOpen()).isFalse(); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandlerTest.java
License:Open Source License
/** * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a * Content-Length header./*from w w w.ja v a2s . c o m*/ */ @Test public void httpErrorsWithContentAreSupported() { EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null)); ByteArrayInputStream data = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 }); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise); HttpRequest request = ch.readOutbound(); assertThat(request).isInstanceOf(HttpRequest.class); HttpChunkedInput content = ch.readOutbound(); assertThat(content).isInstanceOf(HttpChunkedInput.class); ByteBuf errorMsg = ByteBufUtil.writeAscii(ch.alloc(), "error message"); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, errorMsg); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ch.writeInbound(response); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); assertThat(ch.isOpen()).isTrue(); }
From source file:com.kixeye.kixmpp.KixmppCodecTest.java
License:Apache License
@Test public void testSampleXmppClientSessionPerLine() throws Exception { final AtomicReference<KixmppStreamStart> start = new AtomicReference<>(); final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>(); final ArrayList<Element> elements = new ArrayList<>(); ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() { @Override/*from ww w . ja va2s.c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof KixmppStreamStart) { start.set((KixmppStreamStart) msg); } else if (msg instanceof KixmppStreamEnd) { end.set((KixmppStreamEnd) msg); } else if (msg instanceof Element) { elements.add((Element) msg); } } }; EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler); // write a packer per line try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppClientSession.xml")) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { channel.writeInbound(channel.alloc().buffer().writeBytes(line.getBytes(StandardCharsets.UTF_8))); } } Assert.assertNotNull(start.get()); Assert.assertNotNull(end.get()); Assert.assertEquals(5, elements.size()); Assert.assertEquals("starttls", elements.get(0).getName()); Assert.assertEquals("auth", elements.get(1).getName()); Assert.assertEquals("iq", elements.get(2).getName()); Assert.assertEquals("iq", elements.get(3).getName()); Assert.assertEquals("iq", elements.get(4).getName()); }
From source file:com.kixeye.kixmpp.KixmppCodecTest.java
License:Apache License
@Test public void testSampleXmppClientSessionPer100Chars() throws Exception { final AtomicReference<KixmppStreamStart> start = new AtomicReference<>(); final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>(); final ArrayList<Element> elements = new ArrayList<>(); ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() { @Override// w ww . j av a2 s. com public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof KixmppStreamStart) { start.set((KixmppStreamStart) msg); } else if (msg instanceof KixmppStreamEnd) { end.set((KixmppStreamEnd) msg); } else if (msg instanceof Element) { elements.add((Element) msg); } } }; EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler); // write a packer per line try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppClientSession.xml")) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); int charsRead = 0; char[] chars = new char[100]; while ((charsRead = reader.read(chars)) != -1) { StringWriter writer = new StringWriter(); for (int i = 0; i < charsRead; i++) { writer.append(chars[i]); } channel.writeInbound( channel.alloc().buffer().writeBytes(writer.toString().getBytes(StandardCharsets.UTF_8))); } } Assert.assertNotNull(start.get()); Assert.assertNotNull(end.get()); Assert.assertEquals(5, elements.size()); Assert.assertEquals("starttls", elements.get(0).getName()); Assert.assertEquals("auth", elements.get(1).getName()); Assert.assertEquals("iq", elements.get(2).getName()); Assert.assertEquals("iq", elements.get(3).getName()); Assert.assertEquals("iq", elements.get(4).getName()); }
From source file:com.kixeye.kixmpp.KixmppCodecTest.java
License:Apache License
@Test public void testSampleXmppServerSession() throws Exception { final AtomicReference<KixmppStreamStart> start = new AtomicReference<>(); final AtomicReference<KixmppStreamEnd> end = new AtomicReference<>(); final ArrayList<Element> elements = new ArrayList<>(); ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() { @Override/*from ww w . j av a2 s .c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof KixmppStreamStart) { start.set((KixmppStreamStart) msg); } else if (msg instanceof KixmppStreamEnd) { end.set((KixmppStreamEnd) msg); } else if (msg instanceof Element) { elements.add((Element) msg); } } }; EmbeddedChannel channel = new EmbeddedChannel(new KixmppCodec(), handler); // write a packet per line try (InputStream inputStream = this.getClass().getResourceAsStream("/sampleXmppServerSession.xml")) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { channel.writeInbound(channel.alloc().buffer().writeBytes(line.getBytes(StandardCharsets.UTF_8))); } } Assert.assertNotNull(start.get()); Assert.assertNotNull(end.get()); Assert.assertEquals(6, elements.size()); Assert.assertEquals("features", elements.get(0).getName()); Assert.assertEquals("proceed", elements.get(1).getName()); Assert.assertEquals("success", elements.get(2).getName()); Assert.assertEquals("iq", elements.get(3).getName()); Assert.assertEquals("iq", elements.get(4).getName()); Assert.assertEquals("iq", elements.get(5).getName()); }
From source file:org.apache.flink.runtime.query.netty.KvStateClientHandlerTest.java
License:Apache License
/** * Tests that on reads the expected callback methods are called and read * buffers are recycled./* www. j a va 2s . c om*/ */ @Test public void testReadCallbacksAndBufferRecycling() throws Exception { KvStateClientHandlerCallback callback = mock(KvStateClientHandlerCallback.class); EmbeddedChannel channel = new EmbeddedChannel(new KvStateClientHandler(callback)); // // Request success // ByteBuf buf = KvStateRequestSerializer.serializeKvStateRequestResult(channel.alloc(), 1222112277, new byte[0]); buf.skipBytes(4); // skip frame length // Verify callback channel.writeInbound(buf); verify(callback, times(1)).onRequestResult(eq(1222112277L), any(byte[].class)); assertEquals("Buffer not recycled", 0, buf.refCnt()); // // Request failure // buf = KvStateRequestSerializer.serializeKvStateRequestFailure(channel.alloc(), 1222112278, new RuntimeException("Expected test Exception")); buf.skipBytes(4); // skip frame length // Verify callback channel.writeInbound(buf); verify(callback, times(1)).onRequestFailure(eq(1222112278L), any(RuntimeException.class)); assertEquals("Buffer not recycled", 0, buf.refCnt()); // // Server failure // buf = KvStateRequestSerializer.serializeServerFailure(channel.alloc(), new RuntimeException("Expected test Exception")); buf.skipBytes(4); // skip frame length // Verify callback channel.writeInbound(buf); verify(callback, times(1)).onFailure(any(RuntimeException.class)); // // Unexpected messages // buf = channel.alloc().buffer(4).writeInt(1223823); // Verify callback channel.writeInbound(buf); verify(callback, times(2)).onFailure(any(IllegalStateException.class)); assertEquals("Buffer not recycled", 0, buf.refCnt()); // // Exception caught // channel.pipeline().fireExceptionCaught(new RuntimeException("Expected test Exception")); verify(callback, times(3)).onFailure(any(RuntimeException.class)); // // Channel inactive // channel.pipeline().fireChannelInactive(); verify(callback, times(4)).onFailure(any(ClosedChannelException.class)); }
From source file:org.apache.flink.runtime.query.netty.KvStateServerHandlerTest.java
License:Apache License
/** * Tests a simple successful query via an EmbeddedChannel. *//* ww w .java 2 s . c om*/ @Test public void testSimpleQuery() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); KvStateServerHandler handler = new KvStateServerHandler(registry, TEST_THREAD_POOL, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new MemoryStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); AbstractKeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, new JobID(), "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), registry.createTaskRegistry(dummyEnv.getJobID(), dummyEnv.getJobVertexId())); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(registryListener); // Update the KvState and request it int expectedValue = 712828289; int key = 99812822; backend.setCurrentKey(key); ValueState<Integer> state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); state.update(expectedValue); byte[] serializedKeyAndNamespace = KvStateRequestSerializer.serializeKeyAndNamespace(key, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE); long requestId = Integer.MAX_VALUE + 182828L; assertTrue(registryListener.registrationName.equals("vanilla")); ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), requestId, registryListener.kvStateId, serializedKeyAndNamespace); // Write the request and wait for the response channel.writeInbound(request); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertEquals(KvStateRequestType.REQUEST_RESULT, KvStateRequestSerializer.deserializeHeader(buf)); KvStateRequestResult response = KvStateRequestSerializer.deserializeKvStateRequestResult(buf); assertEquals(requestId, response.getRequestId()); int actualValue = KvStateRequestSerializer.deserializeValue(response.getSerializedResult(), IntSerializer.INSTANCE); assertEquals(expectedValue, actualValue); assertEquals(stats.toString(), 1, stats.getNumRequests()); // Wait for async successful request report long deadline = System.nanoTime() + TimeUnit.NANOSECONDS.convert(30, TimeUnit.SECONDS); while (stats.getNumSuccessful() != 1 && System.nanoTime() <= deadline) { Thread.sleep(10); } assertEquals(stats.toString(), 1, stats.getNumSuccessful()); }
From source file:org.apache.flink.runtime.query.netty.KvStateServerHandlerTest.java
License:Apache License
/** * Tests the failure response with {@link UnknownKvStateID} as cause on * queries for unregistered KvStateIDs./*from w w w . j ava 2 s.c o m*/ */ @Test public void testQueryUnknownKvStateID() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); KvStateServerHandler handler = new KvStateServerHandler(registry, TEST_THREAD_POOL, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); long requestId = Integer.MAX_VALUE + 182828L; ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), requestId, new KvStateID(), new byte[0]); // Write the request and wait for the response channel.writeInbound(request); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertEquals(KvStateRequestType.REQUEST_FAILURE, KvStateRequestSerializer.deserializeHeader(buf)); KvStateRequestFailure response = KvStateRequestSerializer.deserializeKvStateRequestFailure(buf); assertEquals(requestId, response.getRequestId()); assertTrue("Did not respond with expected failure cause", response.getCause() instanceof UnknownKvStateID); assertEquals(1, stats.getNumRequests()); assertEquals(1, stats.getNumFailed()); }
From source file:org.apache.flink.runtime.query.netty.KvStateServerHandlerTest.java
License:Apache License
/** * Tests the failure response with {@link UnknownKeyOrNamespace} as cause * on queries for non-existing keys./* w w w .j a va 2 s . c o m*/ */ @Test public void testQueryUnknownKey() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); KvStateServerHandler handler = new KvStateServerHandler(registry, TEST_THREAD_POOL, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); int numKeyGroups = 1; AbstractStateBackend abstractBackend = new MemoryStateBackend(); DummyEnvironment dummyEnv = new DummyEnvironment("test", 1, 0); dummyEnv.setKvStateRegistry(registry); KeyedStateBackend<Integer> backend = abstractBackend.createKeyedStateBackend(dummyEnv, new JobID(), "test_op", IntSerializer.INSTANCE, numKeyGroups, new KeyGroupRange(0, 0), registry.createTaskRegistry(dummyEnv.getJobID(), dummyEnv.getJobVertexId())); final TestRegistryListener registryListener = new TestRegistryListener(); registry.registerListener(registryListener); // Register state ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("any", IntSerializer.INSTANCE); desc.setQueryable("vanilla"); backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, desc); byte[] serializedKeyAndNamespace = KvStateRequestSerializer.serializeKeyAndNamespace(1238283, IntSerializer.INSTANCE, VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE); long requestId = Integer.MAX_VALUE + 22982L; assertTrue(registryListener.registrationName.equals("vanilla")); ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), requestId, registryListener.kvStateId, serializedKeyAndNamespace); // Write the request and wait for the response channel.writeInbound(request); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertEquals(KvStateRequestType.REQUEST_FAILURE, KvStateRequestSerializer.deserializeHeader(buf)); KvStateRequestFailure response = KvStateRequestSerializer.deserializeKvStateRequestFailure(buf); assertEquals(requestId, response.getRequestId()); assertTrue("Did not respond with expected failure cause", response.getCause() instanceof UnknownKeyOrNamespace); assertEquals(1, stats.getNumRequests()); assertEquals(1, stats.getNumFailed()); }
From source file:org.apache.flink.runtime.query.netty.KvStateServerHandlerTest.java
License:Apache License
/** * Tests the failure response on a failure on the {@link InternalKvState#getSerializedValue(byte[])} * call.// w ww. j a v a2s. c o m */ @Test public void testFailureOnGetSerializedValue() throws Exception { KvStateRegistry registry = new KvStateRegistry(); AtomicKvStateRequestStats stats = new AtomicKvStateRequestStats(); KvStateServerHandler handler = new KvStateServerHandler(registry, TEST_THREAD_POOL, stats); EmbeddedChannel channel = new EmbeddedChannel(getFrameDecoder(), handler); // Failing KvState InternalKvState<?> kvState = mock(InternalKvState.class); when(kvState.getSerializedValue(any(byte[].class))) .thenThrow(new RuntimeException("Expected test Exception")); KvStateID kvStateId = registry.registerKvState(new JobID(), new JobVertexID(), new KeyGroupRange(0, 0), "vanilla", kvState); ByteBuf request = KvStateRequestSerializer.serializeKvStateRequest(channel.alloc(), 282872, kvStateId, new byte[0]); // Write the request and wait for the response channel.writeInbound(request); ByteBuf buf = (ByteBuf) readInboundBlocking(channel); buf.skipBytes(4); // skip frame length // Verify the response assertEquals(KvStateRequestType.REQUEST_FAILURE, KvStateRequestSerializer.deserializeHeader(buf)); KvStateRequestFailure response = KvStateRequestSerializer.deserializeKvStateRequestFailure(buf); assertTrue(response.getCause().getMessage().contains("Expected test Exception")); assertEquals(1, stats.getNumRequests()); assertEquals(1, stats.getNumFailed()); }