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:com.springapp.mvc.netty.example.http.websocketx.client.WebSocketClient.java

License:Apache License

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;/*from  ww w  .  j a  v a 2 s.c om*/
        } 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 = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } 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 WebSocketClientHandler handler = new WebSocketClientHandler(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();
    }
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.TestNetflowDecoder.java

License:Apache License

@Test
public void testSinglePacket() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(makeNetflowDecoder());

    byte[] bytes = get10V5MessagesBytes();
    ch.writeInbound(Unpooled.wrappedBuffer(bytes));

    List<Record> records = collect10NetflowV5MessagesFromChannel(ch, bytes.length);

    ch.finish();/*from  ww w.j  a  v a  2s  .c  om*/

    NetflowTestUtil.assertRecordsForTenPackets(records);
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.TestNetflowDecoder.java

License:Apache License

@Test
public void testMultiplePackets() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(makeNetflowDecoder());

    byte[] bytes = get10V5MessagesBytes();

    long bytesWritten = 0;
    List<List<Byte>> slices = NetTestUtils.getRandomByteSlices(bytes);
    for (int s = 0; s < slices.size(); s++) {
        List<Byte> slice = slices.get(s);
        byte[] sliceBytes = Bytes.toArray(slice);
        ch.writeInbound(Unpooled.wrappedBuffer(sliceBytes));
        bytesWritten += sliceBytes.length;
    }/*from  w w  w . j  a  v a  2s  . co m*/

    assertThat(bytesWritten, equalTo((long) bytes.length));

    List<Record> records = collect10NetflowV5MessagesFromChannel(ch, bytes.length);

    ch.finish();

    NetflowTestUtil.assertRecordsForTenPackets(records);
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.TestNetflowDecoder.java

License:Apache License

private void writeBytesToChannel(EmbeddedChannel ch, byte[] bytes, boolean randomlySlice) {
    if (randomlySlice) {
        long bytesWritten = 0;
        List<List<Byte>> slices = NetTestUtils.getRandomByteSlices(bytes);
        for (int s = 0; s < slices.size(); s++) {
            List<Byte> slice = slices.get(s);
            byte[] sliceBytes = Bytes.toArray(slice);
            ch.writeInbound(Unpooled.wrappedBuffer(sliceBytes));
            bytesWritten += sliceBytes.length;
        }// w w w .j av a2  s  . c  o m

        assertThat(bytesWritten, equalTo((long) bytes.length));
    } else {
        ch.writeInbound(Unpooled.wrappedBuffer(bytes));
    }
}

From source file:com.streamsets.pipeline.lib.udp.TestUDPMessageSerialization.java

License:Apache License

private static UDPMessage createUDPMessage(int size) {
    InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 2000);
    InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 3000);
    byte[] arr = new byte[size];
    for (int i = 0; i < size; i++) {
        arr[i] = (byte) (i % 256);
    }//from  w  w  w  .  j a v  a  2  s. co m
    ByteBuf buffer = Unpooled.wrappedBuffer(arr);
    DatagramPacket datagram = new DatagramPacket(buffer, recipient, sender);
    return new UDPMessage(UDPConstants.NETFLOW, 1, datagram);
}

From source file:com.streamsets.pipeline.lib.udp.UDPMessageDeserializer.java

License:Apache License

public UDPMessage deserialize(byte[] buffer) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
    ObjectInputStream ois = new ObjectInputStream(bais);
    int version = ois.readInt();
    if (version == UDPConstants.UDP_MESSAGE_VERSION) {
        int type = ois.readInt();
        long received = ois.readLong();
        String address = ois.readUTF();
        int port = ois.readInt();
        InetSocketAddress sender = new InetSocketAddress(address, port);
        address = ois.readUTF();//from   w  w w  . jav  a2  s  .  co  m
        port = ois.readInt();
        InetSocketAddress receiver = new InetSocketAddress(address, port);
        int dataLen = ois.readInt();
        byte[] data = new byte[dataLen];
        ois.readFully(data);
        ois.close();
        ByteBuf byteBuf = Unpooled.wrappedBuffer(data);
        DatagramPacket datagram = new DatagramPacket(byteBuf, receiver, sender);
        return new UDPMessage(type, received, datagram);
    } else {
        throw new IOException(Utils.format("Unsupported version '{}'", version));
    }
}

From source file:com.streamsets.pipeline.lib.util.UDPTestUtil.java

License:Apache License

public static byte[] getUDPData(int type, byte[] data) throws IOException {
    InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 2000);
    InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 3000);
    ByteBuf buffer = Unpooled.wrappedBuffer(data);
    DatagramPacket datagram = new DatagramPacket(buffer, recipient, sender);
    UDPMessage message = new UDPMessage(type, 1, datagram);
    UDPMessageSerializer serializer = new UDPMessageSerializer();
    return serializer.serialize(message);
}

From source file:com.streamsets.pipeline.stage.origin.udptokafka.TestKafkaUDPConsumer.java

License:Apache License

private static DatagramPacket createDatagramPackage(int size) {
    InetSocketAddress recipient = new InetSocketAddress("127.0.0.1", 2000);
    InetSocketAddress sender = new InetSocketAddress("127.0.0.1", 3000);
    byte[] arr = new byte[size];
    for (int i = 0; i < size; i++) {
        arr[i] = (byte) (i % 256);
    }/*from   ww  w. j av  a  2  s.  c  o m*/
    ByteBuf buffer = Unpooled.wrappedBuffer(arr);
    return new DatagramPacket(buffer, recipient, sender);
}

From source file:com.study.hc.net.netty.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    System.out.println("?" + ((ByteBuf) msg).toString(Charset.defaultCharset()));
    ctx.write(Unpooled.wrappedBuffer("98877".getBytes()));
    // ((ByteBuf) msg).release();
    ctx.fireChannelRead(msg);//from   w  w  w  .  j a  va  2  s  .co m
}

From source file:com.study.hc.net.netty.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {//  ww  w .ja v a  2 s . c o m
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}