Example usage for io.netty.buffer Unpooled wrappedBuffer

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

Introduction

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

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java

License:Apache License

public FullHttpResponse setResponse(FullHttpResponse response, StringBuilder responseContent) {

    LoginNameServiceHelper ffHelper = new LoginNameServiceHelper();
    List<String> dtos = ffHelper.findDomain();

    StringBuilder res = new StringBuilder();
    res.append(responseContent);/*from w  w w .j  a va  2  s.c o  m*/

    // create Pseudo Menu
    res.append("<html>");
    res.append("<head>");
    res.append("<title>Netty Test Form</title>\r\n");
    res.append("</head>\r\n");
    res.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");

    res.append("<table border=\"0\">");
    res.append("<tr>");
    res.append("<td>");
    res.append("<h1>Netty Test Form</h1>");
    res.append("Choose one FORM");
    res.append("</td>");
    res.append("</tr>");

    for (String ss : dtos) {
        res.append("<tr>");
        res.append("<td>");
        res.append(ss);
        res.append("</td>");
        res.append("</tr>");
    }

    res.append("</table>\r\n");

    response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(res.toString().getBytes()));
    response.headers().set(Names.CONTENT_TYPE, "text/html; charset=UTF-8");
    response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:bean.lee.demo.netty.learn.http.helloworld.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from w w w.  j  a  v  a2 s . co  m*/
        boolean keepAlive = isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:blazingcache.client.CacheEntry.java

License:Apache License

public boolean isSerializedDataEqualTo(byte[] other) {
    // let Netty do the best not to copy memory
    return buf.equals(Unpooled.wrappedBuffer(other));
}

From source file:bridgempp.bot.wrapper.BotWrapper.java

private static void botInitialize(File botConfig) {
    try {//  w  w w.  j a v a2s . c om
        Properties botProperties = new Properties();
        if (!botConfig.exists()) {
            botConfig.createNewFile();
        }
        botProperties.load(new FileInputStream(botConfig));
        String botClass = botProperties.getProperty("botClass");
        if (botClass == null) {
            writeDefaultConfig(botProperties);
            throw new UnsupportedOperationException(
                    "Bot Class is null, cannot execute BridgeMPP server commands");
        }
        Bot bot = (Bot) Class.forName(botClass).newInstance();
        bot.initializeBot();
        String serverAddress = botProperties.getProperty("serverAddress");
        int portNumber = Integer.parseInt(botProperties.getProperty("serverPort"));
        if (serverAddress == null) {
            writeDefaultConfig(botProperties);
            throw new UnsupportedOperationException(
                    "Server Address is null, cannot execute BridgeMPP server commands");
        }
        ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(serverAddress, portNumber));
        byte[] protocol = new byte[1];
        protocol[0] = 0x32;
        channelFuture.await();
        channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer(protocol));
        channelFuture.channel().pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        channelFuture.channel().pipeline().addLast("protobufDecoder",
                new ProtobufDecoder(ProtoBuf.Message.getDefaultInstance()));
        channelFuture.channel().pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        channelFuture.channel().pipeline().addLast("protobufEncoder", new ProtobufEncoder());
        channelFuture.channel().pipeline().addLast(new IncommingMessageHandler(bot));
        bot.channelFuture = channelFuture;
        bot.setProperties(botProperties);

        String serverKey = botProperties.getProperty("serverKey");
        if (serverKey == null) {
            writeDefaultConfig(botProperties);
            throw new UnsupportedOperationException(
                    "Server Key is null, cannot execute BridgeMPP server commands");
        }
        printCommand("!usekey " + serverKey, bot);
        String botAlias = botProperties.getProperty("botname");
        if (botAlias != null) {
            printCommand("!createalias " + botAlias, bot);
        }
        bot.name = botAlias;
        String[] groups = botProperties.getProperty("groups").split("; ");
        for (int i = 0; i < groups.length; i++) {
            printCommand("!subscribegroup " + groups[i], bot);
        }
        System.out.println("Joined " + groups.length + " groups");

    } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
            | InterruptedException ex) {
        Logger.getLogger(BotWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:c5db.codec.ProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message<T> msg, List<Object> out) throws Exception {
    Schema<T> schema = msg.cachedSchema();

    LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput();
    schema.writeTo(lcpo, (T) msg);/*from   ww w.  j  a  va  2 s  .  c  om*/

    List<ByteBuffer> buffers = lcpo.buffer.finish();

    long size = lcpo.buffer.size();
    if (size > Integer.MAX_VALUE) {
        throw new EncoderException("Serialized form was too large, actual size: " + size);
    }

    out.add(Unpooled.wrappedBuffer(buffers.toArray(new ByteBuffer[] {})));
}

From source file:c5db.codec.UdpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, UdpProtostuffMessage<T> msg, List<Object> out)
        throws Exception {
    LinkBuffer buffer = new LinkBuffer(bufferAllocSize);
    if (protostuffOutput) {
        LowCopyProtostuffOutput lcpo = new LowCopyProtostuffOutput(buffer);
        schema.writeTo(lcpo, msg.message);
    } else {/*from ww w . j  ava2 s.co  m*/
        LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(buffer);
        schema.writeTo(lcpo, msg.message);
    }

    List<ByteBuffer> buffers = buffer.finish();
    ByteBuf data = Unpooled.wrappedBuffer(buffers.toArray(new ByteBuffer[buffers.size()]));
    data.retain();

    DatagramPacket dg = new DatagramPacket(data, msg.remoteAddress);
    dg.retain();
    out.add(dg);
}

From source file:c5db.control.ClientHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf requestContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.POST,
            "foo", requestContent);

    httpRequest.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");
    httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, requestContent.readableBytes());

    out.add(httpRequest);/* w  ww . ja v a 2 s  . co m*/
}

From source file:c5db.control.ServerHttpProtostuffEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
    Class<?> messageType = msg.getClass();

    LowCopyProtobufOutput outputSerializer = new LowCopyProtobufOutput();
    msg.cachedSchema().writeTo(outputSerializer, msg);
    List<ByteBuffer> serializedBuffers = outputSerializer.buffer.finish();
    ByteBuf replyContent = Unpooled.wrappedBuffer(serializedBuffers.toArray(new ByteBuffer[] {}));

    DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0,
            HttpResponseStatus.OK, replyContent);
    httpResponse.headers().set(HttpProtostuffConstants.PROTOSTUFF_HEADER_NAME, messageType.getName());
    httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");

    out.add(httpResponse);//  w w w .  ja v a2  s .  com

}

From source file:c5db.replication.ReplicationWireMessageTest.java

License:Apache License

@Test
public void testSimpleSerialization() throws Exception {
    RequestVote rv = new RequestVote(1, 22222, 34, 22);
    ReplicationWireMessage rwm = new ReplicationWireMessage(1, 1, 0, "quorumId", false, rv, null, null, null,
            null, null);//from  w  ww .j  ava  2s.c o  m

    LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(new LinkBuffer(24));
    rwm.writeTo(lcpo, rwm);
    List<ByteBuffer> serBufs = lcpo.buffer.finish();
    logBufsInformation("ReplicationWireMessage", serBufs);

    ByteBuf b = Unpooled.wrappedBuffer(serBufs.toArray(new ByteBuffer[serBufs.size()]));
    System.out.println("ByteBuf info = " + b);
    System.out.println("ByteBuf size = " + b.readableBytes());
    assertEquals(lcpo.buffer.size(), b.readableBytes());

    System.out.println("rwm = " + rwm);
}

From source file:ca.lambtoncollege.netty.webSocket.ClientWebSocket.java

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/* w w  w .  j a va  2 s . co  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final ClientHandlerWebSocket handler = new ClientHandlerWebSocket(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}