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.cloudera.livy.client.local.rpc.TestKryoMessageCodec.java

License:Apache License

private ByteBuf newBuffer() {
    return UnpooledByteBufAllocator.DEFAULT.buffer(1024);
}

From source file:com.comphenix.protocol.compat.netty.independent.IndependentNetty.java

License:Open Source License

@Override
public WrappedByteBuf createPacketBuffer() {
    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    Class<?> packetSerializer = MinecraftReflection.getPacketDataSerializerClass();

    try {/*from  ww w.jav  a2s  .  com*/
        return new NettyByteBuf((ByteBuf) packetSerializer.getConstructor(ByteBuf.class).newInstance(buffer));
    } catch (Exception e) {
        throw new RuntimeException("Cannot construct packet serializer.", e);
    }
}

From source file:com.comphenix.protocol.events.PacketContainer.java

License:Open Source License

/**
 * Construct a new packet data serializer.
 * @return The packet data serializer.//from www  . j  a v  a  2  s. c  om
 */
public static ByteBuf createPacketBuffer() {
    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    Class<?> packetSerializer = MinecraftReflection.getPacketDataSerializerClass();

    try {
        return (ByteBuf) packetSerializer.getConstructor(ByteBuf.class).newInstance(buffer);
    } catch (Exception e) {
        throw new RuntimeException("Cannot construct packet serializer.", e);
    }
}

From source file:com.corundumstudio.socketio.handler.PacketHandlerTest.java

License:Apache License

private void testHandler(PacketHandler handler, Queue<Packet> packets) throws Exception {
    int size = packets.size();
    ByteBuf buffer = Unpooled.buffer();/*from   w w w  . ja  va2s  . c  o  m*/
    encoder.encodePackets(packets, buffer, UnpooledByteBufAllocator.DEFAULT);
    handler.channelRead0(null, new PacketsMessage(client, buffer));
    Assert.assertEquals(size, invocations.get());
}

From source file:com.corundumstudio.socketio.parser.EncoderJsonPacketTest.java

License:Apache License

@Test
public void testPerf() throws IOException {
    List<Packet> packets = new ArrayList<Packet>();
    for (int i = 0; i < 100; i++) {
        Packet packet = new Packet(PacketType.JSON);
        packet.setId(1L);// w  w w .ja  v  a2s . c o  m
        packet.setData(Collections.singletonMap("", "123123jksdf213"));
        packets.add(packet);
    }

    List<Queue<Packet>> queues = new ArrayList<Queue<Packet>>();
    for (int i = 0; i < 5000; i++) {
        ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue(packets);
        queues.add(queue);

    }
    long t = System.currentTimeMillis();

    for (int i = 0; i < 5000; i++) {
        encoder.encodePackets(queues.get(i), Unpooled.buffer(), UnpooledByteBufAllocator.DEFAULT);
        //            String message = encoder.encodePackets(queues.get(i));
        //            ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8);
    }
    // 1000 ms

    System.out.println(System.currentTimeMillis() - t);
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

/**
 * Create a new {@link AbstractEndpoint}.
 *
 * @param hostname the hostname/ipaddr of the remote channel.
 * @param bucket the name of the bucket.
 * @param password the password of the bucket.
 * @param port the port of the remote channel.
 * @param environment the environment of the core.
 * @param responseBuffer the response buffer for passing responses up the stack.
 *//*from w  w  w .  ja va2 s. c  om*/
protected AbstractEndpoint(final String hostname, final String bucket, final String password, final int port,
        final CoreEnvironment environment, final RingBuffer<ResponseEvent> responseBuffer,
        boolean isTransient) {
    super(LifecycleState.DISCONNECTED);
    this.bucket = bucket;
    this.password = password;
    this.responseBuffer = responseBuffer;
    this.env = environment;
    this.isTransient = isTransient;
    if (environment.sslEnabled()) {
        this.sslEngineFactory = new SSLEngineFactory(environment);
    }

    Class<? extends Channel> channelClass = NioSocketChannel.class;
    if (environment.ioPool() instanceof EpollEventLoopGroup) {
        channelClass = EpollSocketChannel.class;
    } else if (environment.ioPool() instanceof OioEventLoopGroup) {
        channelClass = OioSocketChannel.class;
    }

    ByteBufAllocator allocator = env.bufferPoolingEnabled() ? PooledByteBufAllocator.DEFAULT
            : UnpooledByteBufAllocator.DEFAULT;

    boolean tcpNodelay = environment().tcpNodelayEnabled();
    bootstrap = new BootstrapAdapter(
            new Bootstrap().remoteAddress(hostname, port).group(environment.ioPool()).channel(channelClass)
                    .option(ChannelOption.ALLOCATOR, allocator).option(ChannelOption.TCP_NODELAY, tcpNodelay)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, env.socketConnectTimeout())
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            if (environment.sslEnabled()) {
                                pipeline.addLast(new SslHandler(sslEngineFactory.get()));
                            }
                            if (LOGGER.isTraceEnabled()) {
                                pipeline.addLast(LOGGING_HANDLER_INSTANCE);
                            }
                            customEndpointHandlers(pipeline);
                        }
                    }));
}

From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponseTest.java

License:Apache License

@Test
public void testGetContent() {
    String msg = "This is a test";
    testGetContent(msg, UnpooledByteBufAllocator.DEFAULT.heapBuffer(msg.getBytes(Charsets.UTF_8).length));
}

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  w w. ja v  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.lambdaworks.redis.protocol.CommandArgs.java

License:Apache License

@Override
public String toString() {

    final StringBuilder sb = new StringBuilder();
    sb.append(getClass().getSimpleName());

    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(singularArguments.size() * 10);
    encode(buffer);/*from ww w.  jav  a2s .  c  o  m*/
    buffer.resetReaderIndex();

    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    sb.append(" [buffer=").append(new String(bytes));
    sb.append(']');
    buffer.release();

    return sb.toString();
}

From source file:com.linecorp.armeria.common.stream.StreamMessageDuplicatorTest.java

License:Apache License

private static ByteBuf newUnpooledBuffer() {
    return UnpooledByteBufAllocator.DEFAULT.buffer().writeByte(0);
}