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.github.sparkfy.network.protocol.MessageWithHeaderSuite.java

License:Apache License

private ByteBuf doWrite(MessageWithHeader msg, int minExpectedWrites) throws Exception {
    int writes = 0;
    ByteArrayWritableChannel channel = new ByteArrayWritableChannel((int) msg.count());
    while (msg.transfered() < msg.count()) {
        msg.transferTo(channel, msg.transfered());
        writes++;/* w  ww  .  ja v a2 s.c  o m*/
    }
    assertTrue("Not enough writes!", minExpectedWrites <= writes);
    return Unpooled.wrappedBuffer(channel.getData());
}

From source file:com.github.sparkfy.network.TestManagedBuffer.java

License:Apache License

public TestManagedBuffer(int len) {
    Preconditions.checkArgument(len <= Byte.MAX_VALUE);
    this.len = len;
    byte[] byteArray = new byte[len];
    for (int i = 0; i < len; i++) {
        byteArray[i] = (byte) i;
    }// ww w  .j  a  v  a  2s  .  c o  m
    this.underlying = new NettyManagedBuffer(Unpooled.wrappedBuffer(byteArray));
}

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Writes a HTTP response.//from   ww w.  j av a2 s .c om
 *
 * @param ctx         The channel context.
 * @param request     The HTTP request.
 * @param status      The HTTP status code.
 * @param contentType The response content type.
 * @param content     The response content.
 */
private void writeResponse(final ChannelHandlerContext ctx, final FullHttpRequest request,
        final HttpResponseStatus status, final CharSequence contentType, final String content) {

    final byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
    final ByteBuf entity = Unpooled.wrappedBuffer(bytes);
    writeResponse(ctx, request, status, entity, contentType, bytes.length);
}

From source file:com.github.unafraid.signer.server.ServerHandler.java

License:Apache License

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

        if (HttpHeaderUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*  ww  w. j  a  v a2  s .c  om*/

        final List<BiFunction<ChannelHandlerContext, HttpRequest, FullHttpResponse>> handlers = HandlerManager
                .getInstance().getHandler(req.uri());
        for (BiFunction<ChannelHandlerContext, HttpRequest, FullHttpResponse> handler : handlers) {
            final FullHttpResponse response = handler.apply(ctx, req);
            if (response != null) {
                processResponse(ctx, req, response);
                return;
            }
        }

        // This shouldn't happen ever!
        processResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND,
                Unpooled.wrappedBuffer("Default handler was not found".getBytes())));
    }
}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

private void handleGet(ChannelHandlerContext ctx, FullHttpRequest request) {
    byte[] contents = cache.get(request.uri());

    if (contents == null) {
        sendError(ctx, request, HttpResponseStatus.NOT_FOUND);
        return;//w  w w.jav a2s.  c o  m
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(contents));
    HttpUtil.setContentLength(response, contents.length);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream");
    ChannelFuture lastContentFuture = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.hop.hhxx.example.http.helloworld.HttpHelloWorldServerHandler.java

License:Apache License

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

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/*from   w  ww.j  a  v  a 2s  .  c o  m*/
        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 {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:com.hop.hhxx.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 ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;/*from w  ww.  j  av a  2 s.  c  om*/
        } else if ("wss".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),
                        WebSocketClientCompressionHandler.INSTANCE, 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.hzmsc.scada.Jmtis.server.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        System.out.println(req);/*from ww  w .j a  va 2 s  . c  o  m*/

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        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 {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf buf = content.content();
        System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
        buf.release();
        System.out.println(ChannelMap.channelMap);
        Channel channel = ChannelMap.channelMap.get("null0");
        if (channel != null) {

            System.out.println(channel.id().asLongText());
            JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short) 1, (short) 1, (short) 1, (short) 1,
                    new int[] { 1, 2, 3, 4, 5 });
            //System.out.println(jmtisMsg);
            System.out.println(ctx.channel().id().asLongText());
            channel.writeAndFlush(jmtisMsg);
            channel.write(jmtisMsg);
            channel.flush();
        } else {
            System.out.println("there is no active channel.......");
        }
        //JmtisMsg jmtisMsg = new JmtisMsg("clientCompany", (short)1, (short)1, (short)1, (short)1, new int[]{1, 2, 3, 4, 5});
        //System.out.println(jmtisMsg);
        //channel.write(jmtisMsg);

    }
}

From source file:com.ibm.mqlight.api.impl.engine.MockNetworkChannel.java

License:Apache License

public void process() {
    if (transport.pending() > 0) {
        ByteBuffer head = transport.head();
        int amount = head.remaining();
        ByteBuffer tmp = ByteBuffer.allocate(amount);
        tmp.put(head);//from  w ww .j a v  a2 s .co m
        tmp.flip();
        final ByteBuf buf = Unpooled.wrappedBuffer(tmp);
        transport.pop(amount);
        listener.onRead(this, buf);
    }
}

From source file:com.ibm.mqlight.api.impl.network.TestNetworkListenerImpl.java

License:Apache License

@Test
public void onRead() {
    MockComponent component = new MockComponent();
    NetworkListenerImpl listener = new NetworkListenerImpl(component);
    StubNetworkChannel expectedChannel = new StubNetworkChannel();
    ByteBuffer buf = ByteBuffer.allocate(1);
    ByteBuf expectedBuffer = Unpooled.wrappedBuffer(buf);
    listener.onRead(expectedChannel, expectedBuffer);
    assertEquals("Expected component to receive 1 message", 1, component.getMessages().size());
    assertTrue("Expected message to be instanceof DataRead",
            component.getMessages().get(0) instanceof DataRead);
    DataRead read = (DataRead) component.getMessages().get(0);
    assertSame("Expected same buffer in message", expectedBuffer, read.buffer);
    assertSame("Expected same channel in message", expectedChannel, read.channel);
}