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.moquette.parser.netty.TestUtils.java

License:Open Source License

static ChannelHandlerContext mockChannelHandler() {
    ChannelHandlerContext m_mockedContext = mock(ChannelHandlerContext.class);
    ByteBufAllocator allocator = UnpooledByteBufAllocator.DEFAULT;
    when(m_mockedContext.alloc()).thenReturn(allocator);
    return m_mockedContext;
}

From source file:io.mycat.netty.mysql.MySQLHandshakeHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    logger.info("MySQLHandshakeHandler channel Active");

    // maybe leak here
    ByteBuf out = ctx.alloc().buffer();
    Handshake handshake = new Handshake();
    handshake.sequenceId = 0;/*w ww. ja v  a  2 s  .c o  m*/
    handshake.protocolVersion = MySQLServer.PROTOCOL_VERSION;
    handshake.serverVersion = MySQLServer.SERVER_VERSION;
    handshake.connectionId = connIdGenerator.incrementAndGet();
    handshake.challenge1 = getRandomString(8);
    handshake.capabilityFlags = Flags.CLIENT_BASIC_FLAGS;
    handshake.characterSet = CharsetUtil.getIndex(MySQLServer.DEFAULT_CHARSET);
    handshake.statusFlags = Flags.SERVER_STATUS_AUTOCOMMIT;
    handshake.challenge2 = getRandomString(12);
    handshake.authPluginDataLength = 21;
    handshake.authPluginName = "mysql_native_password";
    // Remove some flags from the reply
    handshake.removeCapabilityFlag(Flags.CLIENT_COMPRESS);
    handshake.removeCapabilityFlag(Flags.CLIENT_IGNORE_SPACE);
    handshake.removeCapabilityFlag(Flags.CLIENT_LOCAL_FILES);
    handshake.removeCapabilityFlag(Flags.CLIENT_SSL);
    handshake.removeCapabilityFlag(Flags.CLIENT_TRANSACTIONS);
    handshake.removeCapabilityFlag(Flags.CLIENT_RESERVED);
    handshake.removeCapabilityFlag(Flags.CLIENT_REMEMBER_OPTIONS);

    MysqlFrontendSession temp = new MysqlFrontendSession();
    temp.setHandshake(handshake);
    temp.setAttachment(SEED_KEY, handshake.challenge1);
    ctx.attr(TMP_SESSION_KEY).set(temp);

    logger.info("prepare flush authentication, mysql handshake handler : {}", handshake);
    out.writeBytes(handshake.toPacket());
    ctx.writeAndFlush(out);

    //  ===========

    //        HandshakePacket handshake = new HandshakePacket();
    //        handshake.packetId = 0;
    //        handshake.protocolVersion = MySQLServer.PROTOCOL_VERSION;
    //        // TODO:
    //        handshake.serverVersion = MySQLServer.SERVER_VERSION.getBytes();
    //        handshake.threadId= connIdGenerator.incrementAndGet();
    //        // TODO:
    //        handshake.seed = getRandomString(8).getBytes();
    //        handshake.serverCapabilities = Flags.CLIENT_BASIC_FLAGS;
    //        handshake.serverCharsetIndex = (byte)CharsetUtil.getIndex(MySQLServer.DEFAULT_CHARSET);
    //        handshake.serverStatus = Flags.SERVER_STATUS_AUTOCOMMIT;
    //        // TODO:
    //        handshake.restOfScrambleBuff = getRandomString(12).getBytes();
    ////        handshake. = 21;
    ////        handshake.authPluginName = "mysql_native_password";
    //        // Remove some flags from the reply
    //        handshake.removeCapabilityFlag(Flags.CLIENT_COMPRESS);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_IGNORE_SPACE);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_LOCAL_FILES);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_SSL);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_TRANSACTIONS);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_RESERVED);
    //        handshake.removeCapabilityFlag(Flags.CLIENT_REMEMBER_OPTIONS);
    //
    //
    //        MysqlFrontendSession temp = new MysqlFrontendSession();
    //        temp.setHandshake(handshake);
    //        temp.setAttachment(SEED_KEY, handshake.seed);
    //        ctx.attr(TMP_SESSION_KEY).set(temp);

    //        logger.info("prepare flush authentication, mysql handshake handler : {}", handshake);
    //        out.writeBytes(handshake.getPacket());
    //        ctx.writeAndFlush(out);
    //
}

From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java

License:Apache License

private void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) {
    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n")
            .append("<html><head><meta charset='utf-8' /><title>").append("Listing of: ").append(dirPath)
            .append("</title></head><body>\r\n")

            .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n")

            .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }/*from   w  ww. j  av a 2 s. c o  m*/

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");

    ByteBuf buffer = ctx.alloc().buffer(buf.length());
    buffer.writeCharSequence(buf.toString(), CharsetUtil.UTF_8);

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

    this.sendAndCleanupConnection(ctx, response);
}

From source file:io.netty.example.http.websocketx.benchmarkserver.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req,//from  w  w  w  . ja v  a2s.co m
                new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST, ctx.alloc().buffer(0)));
        return;
    }

    // Allow only GET methods.
    if (!GET.equals(req.method())) {
        sendHttpResponse(ctx, req,
                new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN, ctx.alloc().buffer(0)));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.uri())) {
        ByteBuf content = WebSocketServerBenchmarkPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), OK, content);

        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }

    if ("/favicon.ico".equals(req.uri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), NOT_FOUND,
                ctx.alloc().buffer(0));
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true, 5 * 1024 * 1024);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:io.netty.example.http.websocketx.server.WebSocketIndexPageHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req,/*from w w w  .  j  a v  a 2 s .com*/
                new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST, ctx.alloc().buffer(0)));
        return;
    }

    // Allow only GET methods.
    if (!GET.equals(req.method())) {
        sendHttpResponse(ctx, req,
                new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN, ctx.alloc().buffer(0)));
        return;
    }

    // Send the index page
    if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) {
        String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
        ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
        FullHttpResponse res = new DefaultFullHttpResponse(req.protocolVersion(), OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
    } else {
        sendHttpResponse(ctx, req,
                new DefaultFullHttpResponse(req.protocolVersion(), NOT_FOUND, ctx.alloc().buffer(0)));
    }
}

From source file:io.netty.example.http2.helloworld.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER));
    }//from w w w. j  a  v  a 2 s .  co m
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

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

    if (keepAlive) {
        if (req.protocolVersion().equals(HTTP_1_0)) {
            response.headers().set(CONNECTION, KEEP_ALIVE);
        }
        ctx.write(response);
    } else {
        // Tell the client we're going to close the connection.
        response.headers().set(CONNECTION, CLOSE);
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.netty.example.http2.tiles.FallbackRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, EMPTY_BUFFER));
    }//w  w  w.  j a va 2  s. c o  m

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(response.duplicate());

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

    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:io.reactivesocket.transport.tcp.ReactiveSocketFrameCodec.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof Frame) {
        ByteBuffer src = ((Frame) msg).getByteBuffer();
        ByteBuf toWrite = ctx.alloc().buffer(src.remaining()).writeBytes(src);
        ctx.write(toWrite, promise);/*from  w  w w .ja v  a 2  s. c om*/
    } else {
        super.write(ctx, msg, promise);
    }
}

From source file:io.reactivex.netty.pipeline.ByteArrayPipelineConfigurator.java

License:Apache License

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

        @Override/*from   www .  j a va  2 s .  c o  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 readableBytes = byteBuf.readableBytes();
                    byte[] msgToPass = new byte[readableBytes];
                    byteBuf.readBytes(msgToPass);
                    handled = true;
                    ctx.fireChannelRead(msgToPass);
                }
            }
            if (!handled) {
                super.channelRead(ctx, msg);
            }
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            if (msg instanceof byte[]) {
                byte[] msgAsBytes = (byte[]) msg;
                ByteBuf byteBuf = ctx.alloc().buffer(msgAsBytes.length).writeBytes(msgAsBytes);
                super.write(ctx, byteBuf, promise);
            } else {
                super.write(ctx, msg, promise); // pass-through
            }
        }
    });
}

From source file:io.reactivex.netty.protocol.http.sse.ServerSentEventDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (null == sseEncodingCharset) {
        throw new IllegalArgumentException("Can not read SSE data as UTF-8 charset is not available.");
    }/*  ww  w  .  j  ava2s.  co m*/

    while (in.isReadable()) {

        final int readerIndexAtStart = in.readerIndex();

        switch (state) {
        case SkipColonAndWhiteSpaces:
            if (skipColonAndWhiteSpaces(in)) {
                state = State.ReadFieldValue;
            }
            break;
        case SkipLineDelimitersAndSpaces:
            if (skipLineDelimiters(in)) {
                state = State.ReadFieldName;
            }
            break;
        case DiscardTillEOL:
            if (skipTillEOL(in)) {
                state = State.SkipLineDelimitersAndSpaces;
            }
            break;
        case ReadFieldName:
            final int indexOfColon = scanAndFindColon(in);

            if (-1 == indexOfColon) { // No colon found
                // Accumulate data into the field name buffer.
                if (null == incompleteData) {
                    incompleteData = ctx.alloc().buffer();
                }
                // accumulate into incomplete data buffer to be used when the full data arrives.
                incompleteData.writeBytes(in);
            } else {
                int fieldNameLengthInTheCurrentBuffer = indexOfColon - readerIndexAtStart;

                ByteBuf fieldNameBuffer;
                if (null != incompleteData) {
                    // Read the remaining data into the temporary buffer
                    in.readBytes(incompleteData, fieldNameLengthInTheCurrentBuffer);
                    fieldNameBuffer = incompleteData;
                    incompleteData = null;
                } else {
                    // Consume the data from the input buffer.
                    fieldNameBuffer = ctx.alloc().buffer(fieldNameLengthInTheCurrentBuffer,
                            fieldNameLengthInTheCurrentBuffer);
                    in.readBytes(fieldNameBuffer, fieldNameLengthInTheCurrentBuffer);
                }

                state = State.SkipColonAndWhiteSpaces; // We have read the field name, next we should skip colon & WS.
                try {
                    currentFieldType = readCurrentFieldTypeFromBuffer(fieldNameBuffer);
                } finally {
                    if (null == currentFieldType) {
                        state = State.DiscardTillEOL; // Ignore this event completely.
                    }
                    fieldNameBuffer.release();
                }
            }
            break;
        case ReadFieldValue:

            final int endOfLineStartIndex = scanAndFindEndOfLine(in);

            if (-1 == endOfLineStartIndex) { // End of line not found, accumulate data into a temporary buffer.
                if (null == incompleteData) {
                    incompleteData = ctx.alloc().buffer(in.readableBytes());
                }
                // accumulate into incomplete data buffer to be used when the full data arrives.
                incompleteData.writeBytes(in);
            } else { // Read the data till end of line into the value buffer.
                final int bytesAvailableInThisIteration = endOfLineStartIndex - readerIndexAtStart;
                if (null == incompleteData) {
                    incompleteData = ctx.alloc().buffer(bytesAvailableInThisIteration,
                            bytesAvailableInThisIteration);
                }
                incompleteData.writeBytes(in, bytesAvailableInThisIteration);

                switch (currentFieldType) {
                case Data:
                    if (incompleteData.isReadable()) {
                        out.add(ServerSentEvent.withEventIdAndType(lastEventId, lastEventType, incompleteData));
                    } else {
                        incompleteData.release();
                    }
                    break;
                case Id:
                    if (incompleteData.isReadable()) {
                        lastEventId = incompleteData;
                    } else {
                        incompleteData.release();
                        lastEventId = null;
                    }
                    break;
                case EventType:
                    if (incompleteData.isReadable()) {
                        lastEventType = incompleteData;
                    } else {
                        incompleteData.release();
                        lastEventType = null;
                    }
                    break;
                }
                /**
                 * Since all data is read, reset the incomplete data to null. Release of this buffer happens in
                 * the following ways
                 * 1) If this was a data buffer, it is released when ServerSentEvent is released.
                 * 2) If this was an eventId buffer, it is released when next Id arrives or when the connection
                 *     is closed.
                 * 3) If this was an eventType buffer, it is released when next type arrives or when the connection
                 *     is closed.
                 */
                incompleteData = null;
                state = State.SkipLineDelimitersAndSpaces; // Skip line delimiters after reading a field value completely.
            }
            break;
        }
    }

}