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:http2.server.HelloWorldHttp1Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    logger.info("HTTP 1.1");
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }//from ww w. j a v a 2s.  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) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}

From source file:http2.server.HelloWorldHttp2Handler.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) {
    logger.info("onHeaderRead, send hello");
    if (endOfStream) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES.duplicate());
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, streamId, content);
    }//w ww. j  av  a  2s.c o m
}

From source file:io.advantageous.conekt.dns.impl.netty.DnsResponseDecoder.java

License:Open Source License

/**
 * Decodes a response from a {@link io.netty.channel.socket.DatagramPacket} containing a
 * {@link io.netty.buffer.ByteBuf} with a DNS packet. Responses are sent from a DNS server
 * to a client in response to a query. This method writes the decoded
 * response to the specified {@link java.util.List} to be handled by a specialized
 * message handler.//from   w  w w. ja v a2s .co m
 *
 * @param ctx    the {@link io.netty.channel.ChannelHandlerContext} this
 *               {@link DnsResponseDecoder} belongs to
 * @param packet the message being decoded, a {@link io.netty.channel.socket.DatagramPacket} containing
 *               a DNS packet
 * @param out    the {@link java.util.List} to which decoded messages should be added
 * @throws Exception
 */
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    out.add(decodeResponse(packet.content(), ctx.alloc()).retain());
}

From source file:io.advantageous.conekt.http.impl.ConektHttpHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        ByteBuf buf = frame.getBinaryData();
        if (buf != Unpooled.EMPTY_BUFFER) {
            buf = safeBuffer(buf, ctx.alloc());
        }//from   ww  w  .  j ava 2  s . com
        switch (frame.type()) {
        case BINARY:
            msg = new BinaryWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case TEXT:
            msg = new TextWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case CLOSE:
            msg = new CloseWebSocketFrame(true, 0, buf);
            break;
        case CONTINUATION:
            msg = new ContinuationWebSocketFrame(frame.isFinal(), 0, buf);
            break;
        case PONG:
            msg = new PongWebSocketFrame(buf);
            break;
        case PING:
            msg = new PingWebSocketFrame(buf);
            break;
        default:
            throw new IllegalStateException("Unsupported websocket msg " + msg);
        }
    }
    ctx.write(msg, promise);
}

From source file:io.advantageous.conekt.net.impl.ConektHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
    Object message = safeObject(msg, chctx.alloc());
    C connection = getConnection(chctx.channel());

    ContextImpl context;//from  w  w  w. ja  v a  2 s  .c om
    if (connection != null) {
        context = getContext(connection);
        context.executeFromIO(connection::startRead);
    } else {
        context = null;
    }
    channelRead(connection, context, chctx, message);
}

From source file:io.airlift.drift.transport.netty.client.ThriftClientHandler.java

License:Apache License

private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise)
        throws Exception {
    // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed
    int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet();
    RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId);

    // register timeout
    requestHandler.registerRequestTimeout(context.executor());

    // write request
    ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc());

    // register request if we are expecting a response
    if (!thriftRequest.isOneway()) {
        if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) {
            requestHandler.onChannelError(
                    new TTransportException("Another request with the same sequenceId is already in progress"));
            requestBuffer.release();//from   ww w  .jav  a2  s  .  co m
            return;
        }
    }

    // if this connection is failed, immediately fail the request
    TException channelError = this.channelError.get();
    if (channelError != null) {
        thriftRequest.failed(channelError);
        requestBuffer.release();
        return;
    }

    try {
        ThriftFrame thriftFrame = new ThriftFrame(sequenceId, requestBuffer, thriftRequest.getHeaders(),
                transport, protocol, true);

        ChannelFuture sendFuture = context.write(thriftFrame, promise);
        sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler));
    } catch (Throwable t) {
        onError(context, t, Optional.of(requestHandler));
        requestBuffer.release();
    }
}

From source file:io.airlift.drift.transport.netty.server.OptionalSslHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) {
    // minimum bytes required to detect ssl
    if (in.readableBytes() < SSL_RECORD_HEADER_LENGTH) {
        return;/*from   www.  j  a  va 2  s  .  c o  m*/
    }

    ChannelPipeline pipeline = context.pipeline();
    if (isTls(in, in.readerIndex())) {
        pipeline.replace(this, "ssl", sslContext.newHandler(context.alloc()));
    } else {
        pipeline.remove(this);
    }
}

From source file:io.airlift.drift.transport.netty.server.ThriftServerHandler.java

License:Apache License

private static ThriftFrame writeSuccessResponse(ChannelHandlerContext context, MethodMetadata methodMetadata,
        Transport transport, Protocol protocol, int sequenceId, boolean supportOutOfOrderResponse,
        Object result) throws Exception {
    TChannelBufferOutputTransport outputTransport = new TChannelBufferOutputTransport(context.alloc());
    try {//from   w ww .j av a  2 s.  co  m
        writeResponse(methodMetadata.getName(), protocol.createProtocol(outputTransport), sequenceId, "success",
                (short) 0, methodMetadata.getResultCodec(), result);

        return new ThriftFrame(sequenceId, outputTransport.getBuffer(), ImmutableMap.of(), transport, protocol,
                supportOutOfOrderResponse);
    } finally {
        outputTransport.release();
    }
}

From source file:io.airlift.drift.transport.netty.server.ThriftServerHandler.java

License:Apache License

private static ThriftFrame writeExceptionResponse(ChannelHandlerContext context, MethodMetadata methodMetadata,
        Transport transport, Protocol protocol, int sequenceId, boolean supportOutOfOrderResponse,
        Throwable exception) throws Exception {
    Optional<Short> exceptionId = methodMetadata.getExceptionId(exception.getClass());
    if (exceptionId.isPresent()) {
        TChannelBufferOutputTransport outputTransport = new TChannelBufferOutputTransport(context.alloc());
        try {//from  w  w  w .  j  av  a 2s  .  co m
            TProtocolWriter protocolWriter = protocol.createProtocol(outputTransport);

            writeResponse(methodMetadata.getName(), protocolWriter, sequenceId, "exception", exceptionId.get(),
                    methodMetadata.getExceptionCodecs().get(exceptionId.get()), exception);

            return new ThriftFrame(sequenceId, outputTransport.getBuffer(), ImmutableMap.of(), transport,
                    protocol, supportOutOfOrderResponse);
        } finally {
            outputTransport.release();
        }
    }

    TApplicationException.Type type = INTERNAL_ERROR;
    if (exception instanceof TApplicationException) {
        type = ((TApplicationException) exception).getType().orElse(INTERNAL_ERROR);
    }
    return writeApplicationException(context, methodMetadata.getName(), transport, protocol, sequenceId,
            supportOutOfOrderResponse, type,
            "Internal error processing " + methodMetadata.getName() + ": " + exception.getMessage(), exception);
}

From source file:io.airlift.drift.transport.netty.server.ThriftServerHandler.java

License:Apache License

private static ThriftFrame writeApplicationException(ChannelHandlerContext context, String methodName,
        Transport transport, Protocol protocol, int sequenceId, boolean supportOutOfOrderResponse,
        TApplicationException.Type errorCode, String errorMessage, Throwable cause) throws Exception {
    TApplicationException applicationException = new TApplicationException(errorCode, errorMessage);
    if (cause != null) {
        applicationException.initCause(cause);
    }//  www. j a v a  2 s .  c  om

    TChannelBufferOutputTransport outputTransport = new TChannelBufferOutputTransport(context.alloc());
    try {
        TProtocolWriter protocolWriter = protocol.createProtocol(outputTransport);

        protocolWriter.writeMessageBegin(new TMessage(methodName, EXCEPTION, sequenceId));

        ExceptionWriter.writeTApplicationException(applicationException, protocolWriter);

        protocolWriter.writeMessageEnd();
        return new ThriftFrame(sequenceId, outputTransport.getBuffer(), ImmutableMap.of(), transport, protocol,
                supportOutOfOrderResponse);
    } finally {
        outputTransport.release();
    }
}