Example usage for io.netty.buffer Unpooled copiedBuffer

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

Introduction

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

Prototype

private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) 

Source Link

Usage

From source file:com.flysoloing.learning.network.netty.qotm.QuoteOfTheMomentClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   w w  w .j a v a 2  s . c o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                SocketUtils.socketAddress("255.255.255.255", PORT))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.qotm.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);// w  w  w  . j a v a 2  s.  c  o  m
    if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:com.flysoloing.learning.network.netty.spdy.server.SpdyServerHandler.java

License:Apache License

@Override
public void channelRead0(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  ww . ja v a  2  s . com*/
        boolean keepAlive = isKeepAlive(req);

        ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

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

From source file:com.github.jonbonazza.puni.core.requests.HttpResponse.java

License:Apache License

public HttpResponse(HttpResponseStatus status, String content) {
    this(status, Unpooled.copiedBuffer(content, CharsetUtil.UTF_8));
}

From source file:com.github.mrstampy.kitchensync.netty.channel.payload.KiSyMessageByteBufCreator.java

License:Open Source License

@Override
public <MSG> ByteBuf createByteBuf(MSG message, InetSocketAddress recipient) {
    try {//from w w  w  . j  av  a 2 s.c o  m
        String s = mapper.writeValueAsString(message);
        return Unpooled.copiedBuffer(s, CharsetUtil.UTF_8);
    } catch (JsonProcessingException e) {
        log.error("Could not return KiSyMessage Json string for {}", message, e);
    }

    return null;
}

From source file:com.github.mrstampy.kitchensync.netty.channel.payload.StringByteBufCreator.java

License:Open Source License

@Override
public <MSG> ByteBuf createByteBuf(MSG message, InetSocketAddress recipient) {
    return Unpooled.copiedBuffer((String) message, CharsetUtil.UTF_8);
}

From source file:com.github.rmannibucau.featuredmock.http.FeaturedHandler.java

License:Apache License

private static void sendError(final ChannelHandlerContext ctx, final HttpResponseStatus status) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.HttpProxyServer.java

License:Apache License

private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), Matchers.is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }/*from  www  .j  av a  2s  . c om*/

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().remove(HttpRequestDecoder.class);

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = StringUtil.split(authz.toString(), ' ', 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0])
                    && expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}

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

License:Open Source License

private static void sendError(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = ctx.writeAndFlush(response);

    if (!HttpUtil.isKeepAlive(request)) {
        future.addListener(ChannelFutureListener.CLOSE);
    }/*  www  .  ja v a 2  s . co m*/
}

From source file:com.heliosapm.webrpc.websocket.WebSocketServiceHandler.java

License:Apache License

private static void sendHttpResponse(final ChannelHandlerContext ctx, final FullHttpRequest req,
        final FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  w w w  .j a v a2s.co  m*/
        buf.release();
        HttpUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}