Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:io.reactivex.netty.protocol.text.sse.ServerSentEventEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ServerSentEvent serverSentEvent, List<Object> out)
        throws Exception {
    StringBuilder eventBuilder = new StringBuilder();
    if (serverSentEvent.getEventType() != null) {
        eventBuilder.append("event: ").append(serverSentEvent.getEventType()).append('\n');
    }/* w  ww . ja  v  a  2  s .c o m*/
    if (serverSentEvent.getEventData() != null) {
        appendData(serverSentEvent, eventBuilder);
    }
    if (serverSentEvent.getEventId() != null) {
        eventBuilder.append("id: ").append(serverSentEvent.getEventId()).append('\n');
    }
    eventBuilder.append('\n');
    String data = eventBuilder.toString();
    out.add(ctx.alloc().buffer(data.length()).writeBytes(data.getBytes()));
}

From source file:io.reactivex.netty.RxEventPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(new ChannelDuplexHandler() {

        @Override//from ww w .  ja v  a2s .  co m
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            boolean handled = false;
            if (ByteBuf.class.isAssignableFrom(msg.getClass())) {
                ByteBuf byteBuf = (ByteBuf) msg;
                if (byteBuf.isReadable()) {
                    int protocolVersion = byteBuf.readByte();
                    if (protocolVersion != PROTOCOL_VERSION) {
                        throw new RuntimeException("Unsupported protocol version: " + protocolVersion);
                    }
                    int observableNameLength = byteBuf.readByte();
                    String observableName = null;
                    if (observableNameLength > 0) {
                        // read name
                        observableName = new String(byteBuf.readBytes(observableNameLength).array());
                    }
                    int operation = byteBuf.readByte();
                    RemoteRxEvent.Type type = null;
                    Map<String, String> subscribeParams = null;
                    byte[] valueData = null;
                    if (operation == 1) {
                        logger.debug("READ request for RemoteRxEvent: next");
                        type = RemoteRxEvent.Type.next;
                        valueData = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(valueData);
                    } else if (operation == 2) {
                        logger.debug("READ request for RemoteRxEvent: error");
                        type = RemoteRxEvent.Type.error;
                        valueData = new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(valueData);
                    } else if (operation == 3) {
                        logger.debug("READ request for RemoteRxEvent: completed");
                        type = RemoteRxEvent.Type.completed;
                    } else if (operation == 4) {
                        logger.debug("READ request for RemoteRxEvent: subscribed");
                        type = RemoteRxEvent.Type.subscribed;
                        // read subscribe parameters
                        int subscribeParamsLength = byteBuf.readInt();
                        if (subscribeParamsLength > 0) {
                            // read byte into map
                            byte[] subscribeParamsBytes = new byte[subscribeParamsLength];
                            byteBuf.readBytes(subscribeParamsBytes);
                            subscribeParams = fromBytesToMap(subscribeParamsBytes);
                        }
                    } else if (operation == 5) {
                        logger.debug("READ request for RemoteRxEvent: unsubscribed");
                        type = RemoteRxEvent.Type.unsubscribed;
                    } else {
                        throw new RuntimeException("operation: " + operation + " not support.");
                    }
                    handled = true;
                    byteBuf.release();
                    ctx.fireChannelRead(new RemoteRxEvent(observableName, type, valueData, subscribeParams));
                }
            }
            if (!handled) {
                super.channelRead(ctx, msg);
            }
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof RemoteRxEvent) {
                ByteBuf buf = ctx.alloc().buffer();
                buf.writeByte(PROTOCOL_VERSION);
                RemoteRxEvent event = (RemoteRxEvent) msg;
                String observableName = event.getName();
                if (observableName != null && !observableName.isEmpty()) {
                    // write length
                    int nameLength = observableName.length();
                    if (nameLength < 127) {
                        buf.writeByte(nameLength);
                        buf.writeBytes(observableName.getBytes());
                    } else {
                        throw new RuntimeException(
                                "observableName " + observableName + " exceeds max limit of 127 characters");
                    }
                } else {
                    // no name provided, write 0 bytes for name length
                    buf.writeByte(0);
                }
                if (event.getType() == RemoteRxEvent.Type.next) {
                    logger.debug("WRITE request for RemoteRxEvent: next");
                    buf.writeByte(1);
                    buf.writeBytes(event.getData());
                    super.write(ctx, buf, promise);
                } else if (event.getType() == RemoteRxEvent.Type.error) {
                    logger.debug("WRITE request for RemoteRxEvent: error");
                    buf.writeByte(2);
                    buf.writeBytes(event.getData());
                    super.write(ctx, buf, promise);
                } else if (event.getType() == RemoteRxEvent.Type.completed) {
                    logger.debug("WRITE request for RemoteRxEvent: completed");
                    buf.writeByte(3);
                    super.write(ctx, buf, promise);
                    super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data??
                } else if (event.getType() == RemoteRxEvent.Type.subscribed) {
                    logger.debug("WRITE request for RemoteRxEvent: subscribed");
                    buf.writeByte(4);
                    Map<String, String> subscribeParameters = event.getSubscribeParameters();
                    if (subscribeParameters != null && !subscribeParameters.isEmpty()) {
                        byte[] subscribeBytes = fromMapToBytes(subscribeParameters);
                        buf.writeInt(subscribeBytes.length); // write int for length
                        buf.writeBytes(subscribeBytes); // write data
                    } else {
                        buf.writeInt(0); // no data
                    }
                    super.write(ctx, buf, promise);
                    super.flush(ctx);
                } else if (event.getType() == RemoteRxEvent.Type.unsubscribed) {
                    logger.debug("WRITE request for RemoteRxEvent: unsubscribed");
                    buf.writeByte(5);
                    super.write(ctx, buf, promise);
                    super.flush(ctx); // TODO why do I need to explicitly call flush for this to work??? empty data??
                }
            } else {
                super.write(ctx, msg, promise);
            }
        }

    });

}

From source file:io.scalechain.blockchain.net.p2p.BitcoinProtocolEncoder.java

License:Apache License

/**
 * Allocate a {@link ByteBuf} which will be used for constructing an encoded byte buffer of protocol message.
 * BUGBUG : Modify this method to return a {@link ByteBuf} with a perfect matching initial capacity.
 *///  w ww.j  ava 2s .  c o m
protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, @SuppressWarnings("unused") ProtocolMessage msg)
        throws Exception {
    return ctx.alloc().ioBuffer(1024);
}

From source file:io.scalecube.socketio.pipeline.FlashPolicyHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//  w  w  w. j  ava2s.  c o m
    if (msg instanceof ByteBuf) {
        ByteBuf message = (ByteBuf) msg;
        if (message.readableBytes() >= policyRequestBuffer.readableBytes()) {
            ByteBuf data = message.slice(0, policyRequestBuffer.readableBytes());
            if (data.equals(policyRequestBuffer)) {
                // Remove SSL handler from pipeline otherwise on channel close SSL handler
                // will fail all pending writes instead of flushing them and as a result
                // client won't get flash policy file.
                if (ctx.pipeline().get(SocketIOChannelInitializer.SSL_HANDLER) != null) {
                    ctx.pipeline().remove(SocketIOChannelInitializer.SSL_HANDLER);
                }

                // Send flash policy file and close connection
                ByteBuf response = PipelineUtils.copiedBuffer(ctx.alloc(), policyResponse);
                ChannelFuture f = ctx.writeAndFlush(response);
                f.addListener(ChannelFutureListener.CLOSE);
                if (log.isDebugEnabled())
                    log.debug("Sent flash policy file to channel: {}", ctx.channel());
                message.release();
                return;
            }
        }
        ctx.pipeline().remove(this);
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandler.java

License:Apache License

private void handshake(final ChannelHandlerContext ctx, final HttpRequest req,
        final QueryStringDecoder queryDecoder) throws IOException {
    // Generate session ID
    final String sessionId = UUID.randomUUID().toString();
    if (log.isDebugEnabled())
        log.debug("New sessionId: {} generated", sessionId);

    // Send handshake response
    final String handshakeMessage = getHandshakeMessage(sessionId, queryDecoder);

    ByteBuf content = PipelineUtils.copiedBuffer(ctx.alloc(), handshakeMessage);
    HttpResponse res = PipelineUtils.createHttpResponse(PipelineUtils.getOrigin(req), content, false);
    ChannelFuture f = ctx.writeAndFlush(res);
    f.addListener(ChannelFutureListener.CLOSE);
    if (log.isDebugEnabled())
        log.debug("Sent handshake response: {} to channel: {}", handshakeMessage, ctx.channel());
}

From source file:io.scalecube.socketio.pipeline.JsonpPollingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//from  www.j a v  a 2 s  .co m
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (requestPath.startsWith(connectPath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP JSONP-Polling request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final String origin = PipelineUtils.getOrigin(req);

            if (HttpMethod.GET.equals(requestMethod)) {
                // Process polling request from client
                SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader);

                String jsonpIndexParam = PipelineUtils.extractParameter(queryDecoder, "i");
                final ConnectPacket packet = new ConnectPacket(sessionId, origin);
                packet.setTransportType(TransportType.JSONP_POLLING);
                packet.setJsonpIndexParam(jsonpIndexParam);
                packet.setRemoteAddress(clientIp);

                ctx.fireChannelRead(packet);
            } else if (HttpMethod.POST.equals(requestMethod)) {
                // Process message request from client
                ByteBuf buffer = req.content();
                String content = buffer.toString(CharsetUtil.UTF_8);
                if (content.startsWith("d=")) {
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(content, CharsetUtil.UTF_8,
                            false);
                    content = PipelineUtils.extractParameter(queryStringDecoder, "d");
                    content = preprocessJsonpContent(content);
                    ByteBuf buf = PipelineUtils.copiedBuffer(ctx.alloc(), content);
                    List<Packet> packets = PacketFramer.decodePacketsFrame(buf);
                    buf.release();
                    for (Packet packet : packets) {
                        packet.setSessionId(sessionId);
                        packet.setOrigin(origin);
                        ctx.fireChannelRead(packet);
                    }
                } else {
                    log.warn(
                            "Can't process HTTP JSONP-Polling message. Incorrect content format: {} from channel: {}",
                            content, ctx.channel());
                }
            } else {
                log.warn(
                        "Can't process HTTP JSONP-Polling request. Unknown request method: {} from channel: {}",
                        requestMethod, ctx.channel());
            }
            ReferenceCountUtil.release(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.PacketEncoderHandler.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof IPacket) {
        IPacket packet = (IPacket) msg;/*from  ww  w . jav  a 2  s  .c  o m*/

        if (log.isDebugEnabled())
            log.debug("Sending packet: {} to channel: {}", msg, ctx.channel());
        ByteBuf encodedPacket = encodePacket(packet);
        if (log.isDebugEnabled())
            log.debug("Encoded packet: {}", encodedPacket);

        TransportType transportType = packet.getTransportType();
        if (transportType == TransportType.WEBSOCKET || transportType == TransportType.FLASHSOCKET) {
            out.add(new TextWebSocketFrame(encodedPacket));
        } else if (transportType == TransportType.XHR_POLLING) {
            out.add(PipelineUtils.createHttpResponse(packet.getOrigin(), encodedPacket, false));
        } else if (transportType == TransportType.JSONP_POLLING) {
            String jsonpIndexParam = (packet.getJsonpIndexParam() != null) ? packet.getJsonpIndexParam() : "0";
            String encodedStringPacket = encodedPacket.toString(CharsetUtil.UTF_8);
            encodedPacket.release();
            String encodedJsonpPacket = String.format(JSONP_TEMPLATE, jsonpIndexParam, encodedStringPacket);
            HttpResponse httpResponse = PipelineUtils.createHttpResponse(packet.getOrigin(),
                    PipelineUtils.copiedBuffer(ctx.alloc(), encodedJsonpPacket), true);
            httpResponse.headers().add("X-XSS-Protection", "0");
            out.add(httpResponse);
        } else {
            throw new UnsupportedTransportTypeException(transportType);
        }
    } else {
        if (msg instanceof ReferenceCounted) {
            ((ReferenceCounted) msg).retain();
        }
        out.add(msg);
    }
}

From source file:io.vertx.core.http.impl.Http2ConnectionBase.java

License:Open Source License

@Override
public synchronized void onPingRead(ChannelHandlerContext ctx, ByteBuf data) {
    Handler<Buffer> handler = pingHandler;
    if (handler != null) {
        Buffer buff = Buffer.buffer(safeBuffer(data, ctx.alloc()));
        context.executeFromIO(() -> {
            handler.handle(buff);//from w w w .  j a  va2s .  c o m
        });
    }
}

From source file:io.vertx.core.http.impl.Http2ConnectionBase.java

License:Open Source License

@Override
public synchronized void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) {
    Handler<AsyncResult<Buffer>> handler = pongHandlers.poll();
    if (handler != null) {
        context.executeFromIO(() -> {
            Buffer buff = Buffer.buffer(safeBuffer(data, ctx.alloc()));
            handler.handle(Future.succeededFuture(buff));
        });/*  w  ww  .jav  a  2 s  . co m*/
    }
}

From source file:io.vertx.core.http.impl.Http2ConnectionBase.java

License:Open Source License

@Override
public synchronized void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId,
        Http2Flags flags, ByteBuf payload) {
    VertxHttp2Stream req = streams.get(streamId);
    if (req != null) {
        Buffer buff = Buffer.buffer(safeBuffer(payload, ctx.alloc()));
        context.executeFromIO(() -> {
            req.handleCustomFrame(frameType, flags.value(), buff);
        });//  w  w w.java2 s.  c  o  m
    }
}