Example usage for io.netty.buffer ByteBufUtil getBytes

List of usage examples for io.netty.buffer ByteBufUtil getBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufUtil getBytes.

Prototype

public static byte[] getBytes(ByteBuf buf) 

Source Link

Document

Create a copy of the underlying storage from buf into a byte array.

Usage

From source file:io.datty.msgpack.test.MessageWriterTypedTest.java

License:Apache License

@Test
public void testPrimitives() {

    ByteBuf sink = Unpooled.buffer();/*from   w w  w  . j a va 2s.  co m*/

    MessageWriter writer = MapMessageWriter.INSTANCE;

    int headerIndex = writer.skipHeader(255, sink);

    int fields = 0;

    writer.writeKey("boolean", sink);
    writer.writeValue(typeOf(boolean.class), true, sink, true);
    fields++;

    writer.writeKey("Boolean", sink);
    writer.writeValue(typeOf(Boolean.class), true, sink, true);
    fields++;

    writer.writeKey("byte", sink);
    writer.writeValue(typeOf(byte.class), (byte) 1, sink, true);
    fields++;

    writer.writeKey("Byte", sink);
    writer.writeValue(typeOf(Byte.class), (byte) 1, sink, true);
    fields++;

    writer.writeKey("short", sink);
    writer.writeValue(typeOf(short.class), (short) 1, sink, true);
    fields++;

    writer.writeKey("Short", sink);
    writer.writeValue(typeOf(Short.class), (short) 1, sink, true);
    fields++;

    writer.writeKey("int", sink);
    writer.writeValue(typeOf(int.class), (int) 1, sink, true);
    fields++;

    writer.writeKey("Integer", sink);
    writer.writeValue(typeOf(Integer.class), (int) 1, sink, true);
    fields++;

    writer.writeKey("long", sink);
    writer.writeValue(typeOf(long.class), (long) 1, sink, true);
    fields++;

    writer.writeKey("Long", sink);
    writer.writeValue(typeOf(Long.class), (long) 1, sink, true);
    fields++;

    writer.writeKey("float", sink);
    writer.writeValue(typeOf(float.class), (float) 1, sink, true);
    fields++;

    writer.writeKey("Float", sink);
    writer.writeValue(typeOf(Float.class), (float) 1, sink, true);
    fields++;

    writer.writeKey("double", sink);
    writer.writeValue(typeOf(double.class), (double) 1, sink, true);
    fields++;

    writer.writeKey("Double", sink);
    writer.writeValue(typeOf(Double.class), (double) 1, sink, true);
    fields++;

    writer.writeKey("String", sink);
    writer.writeValue(typeOf(String.class), "1", sink, true);
    fields++;

    writer.writeKey("ByteBuf", sink);
    writer.writeValue(typeOf(ByteBuf.class), Unpooled.wrappedBuffer(new byte[] { 1 }), sink, true);
    fields++;

    writer.writeHeader(fields, 255, headerIndex, sink);

    byte[] bytes = ByteBufUtil.getBytes(sink);

    assertPrimitivesExample(bytes);

}

From source file:io.datty.msgpack.test.MessageWriterTypedTest.java

License:Apache License

@Test
public void testComplexStringMap() {

    ByteBuf sink = Unpooled.buffer();//  ww w.j  ava  2s  .co m

    MessageWriter writer = MapMessageWriter.INSTANCE;
    writer.writeHeader(5, sink);

    // 1
    writer.writeKey("id", sink);
    writer.writeValue(typeOf(Long.class), Long.valueOf(1000), sink, true);

    // 2
    writer.writeKey("balance", sink);
    writer.writeValue(typeOf(Double.class), Double.valueOf(33.45), sink, true);

    // 3
    writer.writeKey("withdrawals", sink);
    writeDoubleList(Arrays.asList(10.45, 44.30), sink);

    // 4
    writer.writeKey("names", sink);
    Map<String, String> map = new HashMap<String, String>();
    map.put("first", "John");
    map.put("second", "Dow");
    writeMap(map, sink);

    // 5
    writer.writeKey("logins", sink);
    writer.writeValue(typeOf(long[].class), new long[] { 34, 56 }, sink, true);

    byte[] bytes = ByteBufUtil.getBytes(sink);

    //System.out.println(Arrays.toString(bytes));

    assertComplexStringMapExample(bytes);

}

From source file:io.datty.msgpack.test.table.PackableTableTest.java

License:Apache License

private byte[] getAndCheck(PackableTable table) throws IOException {

    byte[] core = table.toByteArray();

    ByteBuf buffer = Unpooled.buffer();/*from   ww w.  j a va  2 s  .  com*/
    table.pack(buffer);
    byte[] raw = ByteBufUtil.getBytes(buffer);
    Assert.assertTrue(Arrays.equals(core, raw));

    return core;
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private NettyClientHandler(Http2ConnectionDecoder decoder, StreamBufferingEncoder encoder,
        Http2Settings settings, ClientTransportLifecycleManager lifecycleManager,
        KeepAliveManager keepAliveManager, Supplier<Stopwatch> stopwatchFactory,
        final Runnable tooManyPingsRunnable, TransportTracer transportTracer, Attributes eagAttributes,
        String authority) {//ww w.  ja  v  a2s .  c o  m
    super(/* channelUnused= */ null, decoder, encoder, settings);
    this.lifecycleManager = lifecycleManager;
    this.keepAliveManager = keepAliveManager;
    this.stopwatchFactory = stopwatchFactory;
    this.transportTracer = Preconditions.checkNotNull(transportTracer);
    this.eagAttributes = eagAttributes;
    this.authority = authority;
    this.attributes = Attributes.newBuilder().set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttributes).build();

    // Set the frame listener on the decoder.
    decoder().frameListener(new FrameListener());

    Http2Connection connection = encoder.connection();
    streamKey = connection.newKey();

    connection.addListener(new Http2ConnectionAdapter() {
        @Override
        public void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData) {
            byte[] debugDataBytes = ByteBufUtil.getBytes(debugData);
            goingAway(statusFromGoAway(errorCode, debugDataBytes));
            if (errorCode == Http2Error.ENHANCE_YOUR_CALM.code()) {
                String data = new String(debugDataBytes, UTF_8);
                logger.log(Level.WARNING, "Received GOAWAY with ENHANCE_YOUR_CALM. Debug data: {1}", data);
                if ("too_many_pings".equals(data)) {
                    tooManyPingsRunnable.run();
                }
            }
        }

        @Override
        public void onStreamActive(Http2Stream stream) {
            if (connection().numActiveStreams() == 1 && NettyClientHandler.this.keepAliveManager != null) {
                NettyClientHandler.this.keepAliveManager.onTransportActive();
            }
        }

        @Override
        public void onStreamClosed(Http2Stream stream) {
            // Although streams with CALL_OPTIONS_RPC_OWNED_BY_BALANCER are not marked as "in-use" in
            // the first place, we don't propagate that option here, and it's safe to reset the in-use
            // state for them, which will be a cheap no-op.
            inUseState.updateObjectInUse(stream, false);
            if (connection().numActiveStreams() == 0 && NettyClientHandler.this.keepAliveManager != null) {
                NettyClientHandler.this.keepAliveManager.onTransportIdle();
            }
        }
    });
}

From source file:io.grpc.netty.NettyClientHandlerTest.java

License:Apache License

@Test
public void inboundShouldForwardToStream() throws Exception {
    createStream();//from w w w. ja v  a  2  s .  com

    // Read a headers frame first.
    Http2Headers headers = new DefaultHttp2Headers().status(STATUS_OK)
            .set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC).set(as("magic"), as("value"));
    ByteBuf headersFrame = headersFrame(3, headers);
    channelRead(headersFrame);
    ArgumentCaptor<Metadata> captor = ArgumentCaptor.forClass(Metadata.class);
    verify(streamListener).headersRead(captor.capture());
    assertEquals("value", captor.getValue().get(Metadata.Key.of("magic", Metadata.ASCII_STRING_MARSHALLER)));

    streamTransportState.requestMessagesFromDeframer(1);

    // Create a data frame and then trigger the handler to read it.
    ByteBuf frame = grpcDataFrame(3, false, contentAsArray());
    channelRead(frame);
    InputStream message = streamListenerMessageQueue.poll();
    assertArrayEquals(ByteBufUtil.getBytes(content()), ByteStreams.toByteArray(message));
    message.close();
    assertNull("no additional message expected", streamListenerMessageQueue.poll());
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

protected final byte[] contentAsArray() {
    return ByteBufUtil.getBytes(content());
}

From source file:io.grpc.netty.NettyServerHandlerTest.java

License:Apache License

private void inboundDataShouldForwardToStreamListener(boolean endStream) throws Exception {
    createStream();/*from  w ww  . jav  a2s  .  com*/
    stream.request(1);

    // Create a data frame and then trigger the handler to read it.
    ByteBuf frame = grpcDataFrame(STREAM_ID, endStream, contentAsArray());
    channelRead(frame);
    verify(streamListener, atLeastOnce()).messagesAvailable(any(StreamListener.MessageProducer.class));
    InputStream message = streamListenerMessageQueue.poll();
    assertArrayEquals(ByteBufUtil.getBytes(content()), ByteStreams.toByteArray(message));
    message.close();
    assertNull("no additional message expected", streamListenerMessageQueue.poll());

    if (endStream) {
        verify(streamListener).halfClosed();
    }
    verify(streamListener, atLeastOnce()).onReady();
    verifyNoMoreInteractions(streamListener);
}

From source file:org.apache.bookkeeper.client.api.WriteAdvHandleTest.java

License:Apache License

@Test
public void testAppendBytes() throws Exception {
    byte[] testData = runtime.getMethodName().getBytes(UTF_8);
    handle.writeAsync(entryId, testData);

    ByteBuf buffer = entryQueue.take();//  www . j a v  a  2s . c  o  m
    byte[] bufferData = ByteBufUtil.getBytes(buffer);
    assertArrayEquals(testData, bufferData);
    verify(handle, times(1)).writeAsync(eq(entryId), any(ByteBuf.class));
}

From source file:org.apache.bookkeeper.client.api.WriteAdvHandleTest.java

License:Apache License

@Test
public void testAppendBytes2() throws Exception {
    byte[] testData = runtime.getMethodName().getBytes(UTF_8);
    handle.writeAsync(entryId, testData, 1, testData.length / 2);
    byte[] expectedData = new byte[testData.length / 2];
    System.arraycopy(testData, 1, expectedData, 0, testData.length / 2);

    ByteBuf buffer = entryQueue.take();//from  ww  w  . ja  v  a 2  s. co  m
    byte[] bufferData = ByteBufUtil.getBytes(buffer);
    assertArrayEquals(expectedData, bufferData);
    verify(handle, times(1)).writeAsync(eq(entryId), any(ByteBuf.class));
}

From source file:org.apache.bookkeeper.client.api.WriteAdvHandleTest.java

License:Apache License

@Test
public void testAppendByteBuffer() throws Exception {
    byte[] testData = runtime.getMethodName().getBytes(UTF_8);
    handle.writeAsync(entryId, ByteBuffer.wrap(testData, 1, testData.length / 2));
    byte[] expectedData = new byte[testData.length / 2];
    System.arraycopy(testData, 1, expectedData, 0, testData.length / 2);

    ByteBuf buffer = entryQueue.take();/*from   w w w  . ja v  a 2  s  .  c o m*/
    byte[] bufferData = ByteBufUtil.getBytes(buffer);
    assertArrayEquals(expectedData, bufferData);
    verify(handle, times(1)).writeAsync(eq(entryId), any(ByteBuf.class));
}