Example usage for io.netty.buffer Unpooled buffer

List of usage examples for io.netty.buffer Unpooled buffer

Introduction

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

Prototype

public static ByteBuf buffer(int initialCapacity) 

Source Link

Document

Creates a new big-endian Java heap buffer with the specified capacity , which expands its capacity boundlessly on demand.

Usage

From source file:com.cloudhopper.smpp.transcoder.DefaultPduTranscoder.java

License:Apache License

@Override
public ByteBuf encode(Pdu pdu) throws UnrecoverablePduException, RecoverablePduException {
    // see if we can map the command status into a message
    if (pdu instanceof PduResponse) {
        PduResponse response = (PduResponse) pdu;
        if (response.getResultMessage() == null) {
            response.setResultMessage(context.lookupResultMessage(pdu.getCommandStatus()));
        }//from  ww  w . ja v  a2 s.c o  m
    }

    // if the pdu length hasn't been assigned yet, calculate it now
    // NOTE: it may be safest to recalculate it, but we won't since the SmppSession
    // should really be the only interface creating PDUs
    if (!pdu.hasCommandLengthCalculated()) {
        pdu.calculateAndSetCommandLength();
    }

    // create the buffer and add the header
    ByteBuf buffer = Unpooled.buffer(pdu.getCommandLength());
    buffer.order(ByteOrder.BIG_ENDIAN);

    buffer.writeInt(pdu.getCommandLength());
    buffer.writeInt(pdu.getCommandId());
    buffer.writeInt(pdu.getCommandStatus());
    buffer.writeInt(pdu.getSequenceNumber());

    // add mandatory body (a noop if no body exists)
    pdu.writeBody(buffer);

    // add optional parameters (a noop if none exist)
    pdu.writeOptionalParameters(buffer, context);

    // NOTE: at this point, the entire buffer written MUST match the command length
    // from earlier -- if it doesn't match, the our encoding process went awry
    if (buffer.readableBytes() != pdu.getCommandLength()) {
        throw new NotEnoughDataInBufferException(
                "During PDU encoding the expected commandLength did not match the actual encoded (a serious error with our own encoding process)",
                pdu.getCommandLength(), buffer.readableBytes());
    }

    return buffer;
}

From source file:com.cmz.sctp.SctpEchoClientHandler.java

License:Apache License

/**
 * Creates a client-side handler./*from w  w w.jav  a2 s  . co  m*/
 */
public SctpEchoClientHandler() {
    firstMessage = Unpooled.buffer(SctpEchoClient.SIZE);
    for (int i = 0; i < firstMessage.capacity(); i++) {
        firstMessage.writeByte((byte) i);
    }
}

From source file:com.codeabovelab.dm.platform.http.async.NettyRequest.java

License:Apache License

NettyRequest(Bootstrap bootstrap, URI uri, HttpMethod method) {
    this.bootstrap = bootstrap;
    this.uri = uri;
    this.method = method;
    this.body = new ByteBufOutputStream(Unpooled.buffer(1024));
}

From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
    } else if (frame instanceof TextWebSocketFrame) {
        String request = ((TextWebSocketFrame) frame).text();
        LOG.debug("{} received {}", ctx.channel(), request);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), request));
    } else if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf buffer = Unpooled.buffer(frame.content().capacity());
        buffer.writeBytes(frame.content());
        byte[] data = buffer.array();
        LOG.debug("{} received {} bytes of data.", ctx.channel(), data.length);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), data));
    } else {/*from w  ww .j ava  2s  .c o m*/
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }
}

From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.NettyWebSocketClientHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    Channel ch = ctx.channel();/*w  ww .  j a v a  2  s.  c  o  m*/
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        LOG.info("WebSocket client {} connected.", connectionName);
        connectionMonitor.connectionEstablished(getContext(ctx));
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        LOG.debug("WebSocket client {} received message: " + textFrame.text(), connectionName);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), textFrame.text()));
    } else if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf buffer = Unpooled.buffer(frame.content().capacity());
        buffer.writeBytes(frame.content());
        byte[] data = buffer.array();
        LOG.debug("WebSocket client {} received buffer with length " + data.length, connectionName);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), buffer));
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.trace("WebSocket client {} received ping.", connectionName);
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.debug("WebSocket client {} received closing frame.", connectionName);
        ch.close();
    }
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueFeatureHandler.java

License:Apache License

/**
 * Creates the HELLO request to ask for certain supported features.
 *
 * @return the request to send over the wire
 *//*  www.  j a va2 s  . c o m*/
private FullBinaryMemcacheRequest helloRequest() {
    byte[] key = userAgent.getBytes(CharsetUtil.UTF_8);
    short keyLength = (short) key.length;

    ByteBuf wanted = Unpooled.buffer(features.size() * 2);
    for (ServerFeatures feature : features) {
        wanted.writeShort(feature.value());
    }

    LOGGER.debug("Requesting supported features: {}", features);
    FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER,
            wanted);
    request.setOpcode(HELLO_CMD);
    request.setKeyLength(keyLength);
    request.setTotalBodyLength(keyLength + wanted.readableBytes());
    return request;
}

From source file:com.couchbase.client.core.endpoint.view.ViewHandler.java

License:Apache License

@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ViewRequest msg) throws Exception {
    if (msg instanceof KeepAliveRequest) {
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.HEAD, "/",
                Unpooled.EMPTY_BUFFER);//  w  w w.j a  va 2 s  .c o  m
        request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
        return request;
    }

    StringBuilder path = new StringBuilder();

    HttpMethod method = HttpMethod.GET;
    ByteBuf content = null;
    if (msg instanceof ViewQueryRequest) {
        ViewQueryRequest queryMsg = (ViewQueryRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.design() : queryMsg.design());
        if (queryMsg.spatial()) {
            path.append("/_spatial/");
        } else {
            path.append("/_view/");
        }
        path.append(queryMsg.view());

        int queryLength = queryMsg.query() == null ? 0 : queryMsg.query().length();
        int keysLength = queryMsg.keys() == null ? 0 : queryMsg.keys().length();
        boolean hasQuery = queryLength > 0;
        boolean hasKeys = keysLength > 0;

        if (hasQuery || hasKeys) {
            if (queryLength + keysLength < MAX_GET_LENGTH) {
                //the query is short enough for GET
                //it has query, query+keys or keys only
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                    if (hasKeys) {
                        path.append("&keys=").append(encodeKeysGet(queryMsg.keys()));
                    }
                } else {
                    //it surely has keys if not query
                    path.append("?keys=").append(encodeKeysGet(queryMsg.keys()));
                }
            } else {
                //the query is too long for GET, use the keys as JSON body
                if (hasQuery) {
                    path.append("?").append(queryMsg.query());
                }
                String keysContent = encodeKeysPost(queryMsg.keys());

                //switch to POST
                method = HttpMethod.POST;
                //body is "keys" but in JSON
                content = ctx.alloc().buffer(keysContent.length());
                content.writeBytes(keysContent.getBytes(CHARSET));
            }
        }
    } else if (msg instanceof GetDesignDocumentRequest) {
        GetDesignDocumentRequest queryMsg = (GetDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else if (msg instanceof UpsertDesignDocumentRequest) {
        method = HttpMethod.PUT;
        UpsertDesignDocumentRequest queryMsg = (UpsertDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
        content = Unpooled.copiedBuffer(queryMsg.body(), CHARSET);
    } else if (msg instanceof RemoveDesignDocumentRequest) {
        method = HttpMethod.DELETE;
        RemoveDesignDocumentRequest queryMsg = (RemoveDesignDocumentRequest) msg;
        path.append("/").append(msg.bucket()).append("/_design/");
        path.append(queryMsg.development() ? "dev_" + queryMsg.name() : queryMsg.name());
    } else {
        throw new IllegalArgumentException("Unknown incoming ViewRequest type " + msg.getClass());
    }

    if (content == null) {
        content = Unpooled.buffer(0);
    }
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, path.toString(),
            content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));
    addHttpBasicAuth(ctx, request, msg.bucket(), msg.password());

    return request;
}

From source file:com.couchbase.client.core.message.kv.subdoc.multi.SubMultiLookupRequest.java

License:Apache License

private static ByteBuf encode(List<LookupCommand> commands) {
    CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size()); //FIXME pooled allocator?
    for (LookupCommand command : commands) {
        byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8);
        short pathLength = (short) pathBytes.length;

        ByteBuf commandBuf = Unpooled.buffer(4 + pathLength); //FIXME a way of using the pooled allocator?
        commandBuf.writeByte(command.opCode());
        commandBuf.writeByte(0); //no flags supported for lookup
        commandBuf.writeShort(pathLength);
        //no value length
        commandBuf.writeBytes(pathBytes);

        compositeBuf.addComponent(commandBuf);
        compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes());
    }//from  ww w  .  j ava 2  s . c  o  m
    return compositeBuf;
}

From source file:com.couchbase.client.core.message.kv.subdoc.multi.SubMultiMutationRequest.java

License:Apache License

private static ByteBuf encode(List<MutationCommand> commands) {
    //FIXME a way of using the pooled allocator?
    CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size());
    for (MutationCommand command : commands) {
        byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8);
        short pathLength = (short) pathBytes.length;

        ByteBuf commandBuf = Unpooled.buffer(4 + pathLength + command.fragment().readableBytes());
        commandBuf.writeByte(command.opCode());
        if (command.createIntermediaryPath()) {
            commandBuf.writeByte(KeyValueHandler.SUBDOC_BITMASK_MKDIR_P); //0 | SUBDOC_BITMASK_MKDIR_P
        } else {// w w w .j a  v a  2s . c o m
            commandBuf.writeByte(0);
        }
        commandBuf.writeShort(pathLength);
        commandBuf.writeInt(command.fragment().readableBytes());
        commandBuf.writeBytes(pathBytes);

        //copy the fragment but don't move indexes (in case it is retained and reused)
        commandBuf.writeBytes(command.fragment(), command.fragment().readerIndex(),
                command.fragment().readableBytes());
        //eagerly release the fragment once it's been copied
        command.fragment().release();

        //add the command to the composite buffer
        compositeBuf.addComponent(commandBuf);
        compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes());
    }
    return compositeBuf;
}

From source file:com.ctrip.xpipe.redis.console.health.netty.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {//from w  ww  .j a v  a 2  s. co  m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        // p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT);
        Channel c = f.channel();

        while (true) {
            ByteBuf buf = Unpooled.buffer(8);
            buf.writeLong(System.nanoTime());
            c.writeAndFlush(buf);
            Thread.sleep(1000);
        }

    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}