Example usage for io.netty.buffer UnpooledByteBufAllocator DEFAULT

List of usage examples for io.netty.buffer UnpooledByteBufAllocator DEFAULT

Introduction

In this page you can find the example usage for io.netty.buffer UnpooledByteBufAllocator DEFAULT.

Prototype

UnpooledByteBufAllocator DEFAULT

To view the source code for io.netty.buffer UnpooledByteBufAllocator DEFAULT.

Click Source Link

Document

Default instance which uses leak-detection for direct buffers.

Usage

From source file:com.yahoo.pulsar.broker.service.PersistentMessageFinderTest.java

License:Apache License

public static byte[] createMessageWrittenToLedger(String msg) throws Exception {
    PulsarApi.MessageMetadata.Builder messageMetadataBuilder = PulsarApi.MessageMetadata.newBuilder();
    messageMetadataBuilder.setPublishTime(System.currentTimeMillis());
    messageMetadataBuilder.setProducerName("createMessageWrittenToLedger");
    messageMetadataBuilder.setSequenceId(1);
    PulsarApi.MessageMetadata messageMetadata = messageMetadataBuilder.build();
    ByteBuf data = UnpooledByteBufAllocator.DEFAULT.heapBuffer().writeBytes(msg.getBytes());

    int msgMetadataSize = messageMetadata.getSerializedSize();
    int payloadSize = data.readableBytes();
    int totalSize = 4 + msgMetadataSize + payloadSize;

    ByteBuf headers = PooledByteBufAllocator.DEFAULT.heapBuffer(totalSize, totalSize);
    ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(headers);
    headers.writeInt(msgMetadataSize);/*w w  w  .j  a va 2 s.com*/
    messageMetadata.writeTo(outStream);
    ByteBuf headersAndPayload = DoubleByteBuf.get(headers, data);
    byte[] byteMessage = headersAndPayload.nioBuffer().array();
    headersAndPayload.release();
    return byteMessage;
}

From source file:de.saxsys.synchronizefx.netty.base.client.NettyBasicClient.java

License:Open Source License

@Override
public void connect() throws SynchronizeFXException {
    this.eventLoopGroup = new NioEventLoopGroup();
    BasicChannelInitializerClient channelInitializer = createChannelInitializer();
    channelInitializer.setTopologyCallback(callback);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).handler(channelInitializer);

    LOG.info("Connecting to server");
    try {/*from   w ww  .  ja v a  2 s.  c  o m*/
        ChannelFuture future = bootstrap.connect(address);
        if (!future.await(TIMEOUT)) {
            disconnect();
            throw new SynchronizeFXException("Timeout while trying to connect to the server.");
        }
        if (!future.isSuccess()) {
            disconnect();
            throw new SynchronizeFXException("Connection to the server failed.", future.cause());
        }
        this.channel = future.channel();
        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(final Future<? super Void> future) throws Exception {
                // stop the event loop
                eventLoopGroup.shutdownGracefully();
            }
        });
    } catch (InterruptedException e) {
        disconnect();
        throw new SynchronizeFXException(e);
    }
}

From source file:de.unipassau.isl.evs.ssh.core.sec.DeviceConnectInformation.java

License:Open Source License

/**
 * Read a DeviceConnectInformation from a Base64 encoded String, which was read from a QR Code.
 *///from   w  ww .j a  v  a  2 s  .  c  o  m
public static DeviceConnectInformation fromDataString(String data) throws IOException {
    final ByteBuf base64 = UnpooledByteBufAllocator.DEFAULT.heapBuffer(data.length());
    ByteBufUtil.writeAscii(base64, data);
    final ByteBuf byteBuf = decode(base64);
    if (byteBuf.readableBytes() != DATA_LENGTH) {
        throw new IOException("too many bytes encoded");
    }

    final byte[] addressData = new byte[ADDRESS_LENGTH];
    byteBuf.readBytes(addressData);
    final InetAddress address = InetAddress.getByAddress(addressData);
    final int port = byteBuf.readUnsignedShort();
    final byte[] idData = new byte[DeviceID.ID_LENGTH];
    byteBuf.readBytes(idData);
    final DeviceID id = new DeviceID(idData);
    final byte[] encodedToken = new byte[TOKEN_BASE64_LENGTH];
    byteBuf.readBytes(encodedToken);
    final byte[] token = decodeToken(new String(encodedToken));

    return new DeviceConnectInformation(address, port, id, token);
}

From source file:de.unipassau.isl.evs.ssh.core.sec.DeviceConnectInformation.java

License:Open Source License

/**
 * Serialize this Object to a String which can be converted to a QR Code
 *//*from   w  w w .j ava 2s .  com*/
public String toDataString() {
    final ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.heapBuffer(DATA_LENGTH, DATA_LENGTH);
    byteBuf.writeBytes(address.getAddress());
    byteBuf.writeShort(port);
    byteBuf.writeBytes(id.getIDBytes());
    byteBuf.writeBytes(encodeToken(token).getBytes());
    return encode(byteBuf).toString(Charsets.US_ASCII);
}

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

License:Apache License

protected final ChannelHandlerContext newMockContext() {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    EventLoop eventLoop = mock(EventLoop.class);
    when(ctx.executor()).thenReturn(eventLoop);
    when(ctx.channel()).thenReturn(channel);
    return ctx;//from w ww  .j  a  v  a 2 s.com
}

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

License:Apache License

@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
    ListMultimap<CharSequence, CharSequence> expectedHeaders = ImmutableListMultimap
            .copyOf(new DefaultHttp2Headers().status(new AsciiString("200"))
                    .set(new AsciiString("content-type"), new AsciiString("application/grpc"))
                    .set(new AsciiString("grpc-status"), new AsciiString("0")));

    // Client half-closes. Listener gets halfClosed()
    stream().transportState().inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);

    verify(serverListener).halfClosed();

    // Server closes. Status sent
    stream().close(Status.OK, trailers);
    assertNull("no message expected", listenerMessageQueue.poll());

    ArgumentCaptor<SendResponseHeadersCommand> cmdCap = ArgumentCaptor
            .forClass(SendResponseHeadersCommand.class);
    verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
    SendResponseHeadersCommand cmd = cmdCap.getValue();
    assertThat(cmd.stream()).isSameInstanceAs(stream.transportState());
    assertThat(ImmutableListMultimap.copyOf(cmd.headers())).containsExactlyEntriesIn(expectedHeaders);
    assertThat(cmd.endOfStream()).isTrue();

    // Sending and receiving complete. Listener gets closed()
    stream().transportState().complete();
    verify(serverListener).closed(Status.OK);
    assertNull("no message expected", listenerMessageQueue.poll());
}

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

License:Apache License

@Test
public void abortStreamAfterClientHalfCloseShouldCallClose() {
    Status status = Status.INTERNAL.withCause(new Throwable());
    // Client half-closes. Listener gets halfClosed()
    stream().transportState().inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);
    verify(serverListener).halfClosed();
    // Abort from the transport layer
    stream().transportState().transportReportStatus(status);
    verify(serverListener).closed(same(status));
    assertNull("no message expected", listenerMessageQueue.poll());
}

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

License:Apache License

/** Set up for test. */
@Before//w  w  w.  j a v  a  2 s .  c  o  m
public void setUp() {
    MockitoAnnotations.initMocks(this);

    when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    when(channel.pipeline()).thenReturn(pipeline);
    when(channel.eventLoop()).thenReturn(eventLoop);
    when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel));
    when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel));
    ChannelPromise completedPromise = new DefaultChannelPromise(channel).setSuccess();
    when(channel.write(any())).thenReturn(completedPromise);
    when(channel.writeAndFlush(any())).thenReturn(completedPromise);
    when(writeQueue.enqueue(any(QueuedCommand.class), anyBoolean())).thenReturn(completedPromise);
    when(pipeline.firstContext()).thenReturn(ctx);
    when(eventLoop.inEventLoop()).thenReturn(true);
    when(http2Stream.id()).thenReturn(STREAM_ID);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = (Runnable) invocation.getArguments()[0];
            runnable.run();
            return null;
        }
    }).when(eventLoop).execute(any(Runnable.class));

    stream = createStream();
}

From source file:io.moquette.parser.netty.ConnAckEncoderTest.java

License:Open Source License

@Before
public void setUp() {
    //mock the ChannelHandlerContext to return an UnpooledAllocator
    m_mockedContext = mock(ChannelHandlerContext.class);
    ByteBufAllocator allocator = UnpooledByteBufAllocator.DEFAULT;
    when(m_mockedContext.alloc()).thenReturn(allocator);
}

From source file:io.moquette.parser.netty.TestUtils.java

License:Open Source License

static ChannelHandlerContext mockChannelHandler() {
    ChannelHandlerContext m_mockedContext = mock(ChannelHandlerContext.class);
    ByteBufAllocator allocator = UnpooledByteBufAllocator.DEFAULT;
    when(m_mockedContext.alloc()).thenReturn(allocator);
    return m_mockedContext;
}