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.tc.websocket.server.handler.ProxyBackendHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    ByteBuf buf = (ByteBuf) msg;//from  w  w w.j a va 2s  .c  o  m
    String data = new String(ByteBufUtil.getBytes(buf));
    ByteBuf bufData = buf;

    if (Config.getInstance().isEncrypted() && data.contains(StringCache.HTTP)) {
        data = data.replace(StringCache.HTTP, StringCache.HTTPS);
        bufData = Unpooled.wrappedBuffer(data.getBytes());
    }

    //ProxyFrontendHandler.writeToFile("backend", ByteBufUtil.getBytes(bufData));

    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ctx.channel().read();

            } else {
                future.channel().close();
            }
        }
    });

}

From source file:com.tesora.dve.db.mysql.portal.protocol.BaseMSPMessage.java

License:Open Source License

public BaseMSPMessage(byte[] heapData) {
    this.set(Unpooled.wrappedBuffer(heapData));
}

From source file:com.thomas.netty4.SimpleWSClient.java

License:Apache License

public static void readInput(Channel ch) throws Exception {
    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();//from  w  w w.ja  v  a 2  s. c  o  m
            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);
        }
    }
}

From source file:com.titilink.camel.rest.client.CamelClient.java

License:LGPL

private static RestResponse handle(HttpMethod httpMethod, URI uri, byte[] reqBuffer,
        Map<String, String> additionalHeaders, ChallengeResponse challengeResponse, boolean longConn,
        long msTimeout) {
    LOGGER.debug("handleRequest begin. uri={}, method={}, longConn={}, msTimeout={}", uri, httpMethod, longConn,
            msTimeout);/*from w  w w .  jav a 2s  .  c  om*/
    if (null == uri) {
        LOGGER.error("uri is null.");
        return null;
    }

    CamelClient client = getInstance(uri);

    // Create a simple GET request with just headers.
    FullHttpRequest request = null;
    String requestUri = uri.getRawQuery() == null ? uri.getRawPath()
            : uri.getRawPath() + "?" + uri.getRawQuery();
    if (null == reqBuffer) {
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, requestUri);
    } else {
        ByteBuf byteBuf = Unpooled.wrappedBuffer(reqBuffer);
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, requestUri, byteBuf);
        request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    }
    request.headers().add(HttpHeaders.Names.HOST, uri.getHost() + ':' + uri.getPort());
    request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().add("user-agent", "HttpClient");
    if (null != additionalHeaders) {
        Iterator<Map.Entry<String, String>> iter = additionalHeaders.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
            String key = entry.getKey();
            String headerValue = entry.getValue();
            if (null == key || HEADER_NEED_SKIP.contains(key.toLowerCase())) {
                continue;
            }
            if (null != headerValue) {
                request.headers().add(key, headerValue);
            }
        }
    }

    // duel with challengeResponse
    if (null != challengeResponse) {
        Series<Header> headers = new Series<Header>(Header.class);
        for (Map.Entry<String, String> entry : request.headers().entries()) {
            if (null != entry && null != entry.getValue()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        String authHeader = org.restlet.engine.security.AuthenticatorUtils.formatResponse(challengeResponse,
                null, headers);
        for (Header header : headers) {
            if (null != header) {
                request.headers().add(header.getName(), header.getValue());
            }
        }
        if (authHeader != null) {
            request.headers().add(HeaderConstants.HEADER_AUTHORIZATION, authHeader);
        }
    }
    RestResponse result = null;
    int retry = 3;
    boolean success = false;
    while (!success && retry > 0) {
        Channel channel = null;

        // ????????
        if (longConn) {
            channel = getLongChannel(client);
        } else {
            LOGGER.info("open a new channel");
            channel = client.connect();
        }
        // channel?
        if (null == channel || null == channel.pipeline()) {
            LOGGER.error("channle is null or channel.pipeline is null.");
            return null;
        }
        final HttpClientHandler httpClientHandler = (HttpClientHandler) channel.pipeline().get("handler");

        if (null == httpClientHandler) {
            LOGGER.error("httpClientHandler is null.");
            return null;
        }

        try {
            channel.writeAndFlush(request);
            result = httpClientHandler.getResult(msTimeout);
            success = true;
        } catch (Throwable t) {
            LOGGER.error("send request by channel raised a exception:", t);
            channel.close();
            if (t instanceof SSLException) {
                success = false;
            } else {
                //??
                success = true;
            }

        } finally {
            retry--;
            // ??
            // ????????????
            if (longConn && client.getChannelQueue().size() < client.connAmout && !isTimeOut(result)) {
                try {
                    client.getChannelQueue().put(channel);
                } catch (InterruptedException e) {
                    LOGGER.error("put channel to channelQueue had been interrupted.");
                }
            } else {
                LOGGER.info("Close channel.");
                channel.close();
            }
        }
    }

    if (result == null) {
        LOGGER.error("response is null.");
    }
    return result;
}

From source file:com.topsec.bdc.platform.api.test.http.helloworld.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }/* ww w .j  av a 2s  . com*/
        boolean keepAlive = HttpHeaders.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:com.topsec.bdc.platform.api.test.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 w  w.  j a v  a 2  s  .c  o  m
        } 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), 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.turo.pushy.apns.AbstractMockApnsServerHandler.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise)
        throws Exception {
    if (message instanceof AcceptNotificationResponse) {
        final AcceptNotificationResponse acceptNotificationResponse = (AcceptNotificationResponse) message;
        this.encoder().writeHeaders(context, acceptNotificationResponse.getStreamId(), SUCCESS_HEADERS, 0, true,
                writePromise);// w ww . j a va  2 s. c  om

        log.trace("Accepted push notification on stream {}", acceptNotificationResponse.getStreamId());
    } else if (message instanceof RejectNotificationResponse) {
        final RejectNotificationResponse rejectNotificationResponse = (RejectNotificationResponse) message;

        final Http2Headers headers = new DefaultHttp2Headers();
        headers.status(rejectNotificationResponse.getErrorReason().getHttpResponseStatus().codeAsText());
        headers.add(HttpHeaderNames.CONTENT_TYPE, "application/json");

        if (rejectNotificationResponse.getApnsId() != null) {
            headers.add(APNS_ID_HEADER, rejectNotificationResponse.getApnsId().toString());
        }

        final byte[] payloadBytes;
        {
            final ErrorResponse errorResponse = new ErrorResponse(
                    rejectNotificationResponse.getErrorReason().getReasonText(),
                    rejectNotificationResponse.getTimestamp());

            payloadBytes = GSON.toJson(errorResponse).getBytes();
        }

        final ChannelPromise headersPromise = context.newPromise();
        this.encoder().writeHeaders(context, rejectNotificationResponse.getStreamId(), headers, 0, false,
                headersPromise);

        final ChannelPromise dataPromise = context.newPromise();
        this.encoder().writeData(context, rejectNotificationResponse.getStreamId(),
                Unpooled.wrappedBuffer(payloadBytes), 0, true, dataPromise);

        final PromiseCombiner promiseCombiner = new PromiseCombiner();
        promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise);
        promiseCombiner.finish(writePromise);

        log.trace("Rejected push notification on stream {}: {}", rejectNotificationResponse.getStreamId(),
                rejectNotificationResponse.getErrorReason());
    } else if (message instanceof InternalServerErrorResponse) {
        final InternalServerErrorResponse internalServerErrorResponse = (InternalServerErrorResponse) message;

        final Http2Headers headers = new DefaultHttp2Headers();
        headers.status(HttpResponseStatus.INTERNAL_SERVER_ERROR.codeAsText());

        this.encoder().writeHeaders(context, internalServerErrorResponse.getStreamId(), headers, 0, true,
                writePromise);

        log.trace("Encountered an internal error on stream {}", internalServerErrorResponse.getStreamId());
    } else {
        context.write(message, writePromise);
    }
}

From source file:com.turo.pushy.apns.auth.ApnsKey.java

License:Open Source License

protected static byte[] decodeBase64EncodedString(final String base64EncodedString) {
    final ByteBuf base64EncodedByteBuf = Unpooled
            .wrappedBuffer(base64EncodedString.getBytes(StandardCharsets.US_ASCII));

    final ByteBuf decodedByteBuf = Base64.decode(base64EncodedByteBuf);
    final byte[] decodedBytes = new byte[decodedByteBuf.readableBytes()];

    decodedByteBuf.readBytes(decodedBytes);

    base64EncodedByteBuf.release();// ww  w  . j  a  v  a2 s.  c  o  m
    decodedByteBuf.release();

    return decodedBytes;
}

From source file:com.turo.pushy.apns.auth.AuthenticationToken.java

License:Open Source License

static String encodeUnpaddedBase64UrlString(final byte[] data) {
    final ByteBuf wrappedString = Unpooled.wrappedBuffer(data);
    final ByteBuf encodedString = Base64.encode(wrappedString, Base64Dialect.URL_SAFE);

    final String encodedUnpaddedString = encodedString.toString(StandardCharsets.US_ASCII).replace("=", "");

    wrappedString.release();/*from   www . ja v  a  2s.  com*/
    encodedString.release();

    return encodedUnpaddedString;
}

From source file:com.turo.pushy.apns.auth.AuthenticationToken.java

License:Open Source License

static byte[] decodeBase64UrlEncodedString(final String base64UrlEncodedString) {
    final String paddedBase64UrlEncodedString;

    switch (base64UrlEncodedString.length() % 4) {
    case 2: {/*from  w  w w.j  a  v a  2 s. c o m*/
        paddedBase64UrlEncodedString = base64UrlEncodedString + "==";
        break;
    }

    case 3: {
        paddedBase64UrlEncodedString = base64UrlEncodedString + "=";
        break;
    }

    default: {
        paddedBase64UrlEncodedString = base64UrlEncodedString;
    }
    }

    final ByteBuf base64EncodedByteBuf = Unpooled
            .wrappedBuffer(paddedBase64UrlEncodedString.getBytes(StandardCharsets.US_ASCII));

    final ByteBuf decodedByteBuf = Base64.decode(base64EncodedByteBuf, Base64Dialect.URL_SAFE);
    final byte[] decodedBytes = new byte[decodedByteBuf.readableBytes()];

    decodedByteBuf.readBytes(decodedBytes);

    base64EncodedByteBuf.release();
    decodedByteBuf.release();

    return decodedBytes;
}