Search in sources :

Example 86 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class DatagramPacketObjectEncoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception {
    if (msg.content() instanceof Serializable) {
        Serializable payload = (Serializable) msg.content();
        ByteBuf buf = ctx.alloc().buffer();
        delegateObjectEncoder.encode(ctx, payload, buf);
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<Object, InetSocketAddress>(buf, msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
Also used : Serializable(java.io.Serializable) InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope)

Example 87 with ByteBuf

use of io.netty.buffer.ByteBuf in project camel by apache.

the class DatagramPacketStringDecoder method decode.

@Override
protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf) msg.content();
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<Object, InetSocketAddress>(payload.toString(charset), msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) DefaultAddressedEnvelope(io.netty.channel.DefaultAddressedEnvelope)

Example 88 with ByteBuf

use of io.netty.buffer.ByteBuf in project ratpack by ratpack.

the class NettyHandlerAdapter method newRequest.

private void newRequest(final ChannelHandlerContext ctx, final HttpRequest nettyRequest) throws Exception {
    if (!nettyRequest.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());
    //Find the content length we will use this as an indicator of a body
    Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);
    String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);
    //If there is a content length or transfer encoding that indicates there is a body
    boolean hasBody = (contentLength > 0) || (transferEncoding != null);
    RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;
    final Channel channel = ctx.channel();
    if (requestBody != null) {
        channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);
    }
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final DefaultRequest request = new DefaultRequest(Instant.now(), requestHeaders, nettyRequest.method(), nettyRequest.protocolVersion(), nettyRequest.uri(), remoteAddress, socketAddress, serverRegistry.get(ServerConfig.class), requestBody);
    final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    final AtomicBoolean transmitted = new AtomicBoolean(false);
    final DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, nettyRequest, request, nettyHeaders, requestBody);
    ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);
    Action<Action<Object>> subscribeHandler = thing -> {
        transmitted.set(true);
        ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
    };
    final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(applicationConstants, request, channel, responseTransmitter, subscribeHandler);
    final Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);
    requestConstants.response = response;
    DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {
        if (requestBody != null) {
            requestBody.close();
            channel.attr(BODY_ACCUMULATOR_KEY).set(null);
        }
        if (!transmitted.get()) {
            Handler lastHandler = requestConstants.handler;
            StringBuilder description = new StringBuilder();
            description.append("No response sent for ").append(request.getMethod().getName()).append(" request to ").append(request.getUri());
            if (lastHandler != null) {
                description.append(" (last handler: ");
                if (lastHandler instanceof DescribingHandler) {
                    ((DescribingHandler) lastHandler).describeTo(description);
                } else {
                    DescribingHandlers.describeTo(lastHandler, description);
                }
                description.append(")");
            }
            String message = description.toString();
            LOGGER.warn(message);
            response.getHeaders().clear();
            ByteBuf body;
            if (development) {
                CharBuffer charBuffer = CharBuffer.wrap(message);
                body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8);
                response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8);
            } else {
                body = Unpooled.EMPTY_BUFFER;
            }
            response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes());
            responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body);
        }
    });
}
Also used : AttributeKey(io.netty.util.AttributeKey) DescribingHandlers(ratpack.handling.internal.DescribingHandlers) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Unpooled(io.netty.buffer.Unpooled) ByteBuf(io.netty.buffer.ByteBuf) MutableHeaders(ratpack.http.MutableHeaders) ServerConfig(ratpack.server.ServerConfig) Registry(ratpack.registry.Registry) CharsetUtil(io.netty.util.CharsetUtil) DefaultRenderController(ratpack.render.internal.DefaultRenderController) io.netty.channel(io.netty.channel) DefaultContext(ratpack.handling.internal.DefaultContext) Logger(org.slf4j.Logger) CharBuffer(java.nio.CharBuffer) ClosedChannelException(java.nio.channels.ClosedChannelException) ratpack.http.internal(ratpack.http.internal) ChainHandler(ratpack.handling.internal.ChainHandler) IOException(java.io.IOException) DescribingHandler(ratpack.handling.internal.DescribingHandler) Instant(java.time.Instant) InetSocketAddress(java.net.InetSocketAddress) ByteBufUtil(io.netty.buffer.ByteBufUtil) io.netty.handler.codec.http(io.netty.handler.codec.http) Response(ratpack.http.Response) Headers(ratpack.http.Headers) Action(ratpack.func.Action) Handler(ratpack.handling.Handler) Handlers(ratpack.handling.Handlers) ExecController(ratpack.exec.ExecController) Action(ratpack.func.Action) MutableHeaders(ratpack.http.MutableHeaders) Headers(ratpack.http.Headers) InetSocketAddress(java.net.InetSocketAddress) CharBuffer(java.nio.CharBuffer) ByteBuf(io.netty.buffer.ByteBuf) ServerConfig(ratpack.server.ServerConfig) MutableHeaders(ratpack.http.MutableHeaders) DescribingHandler(ratpack.handling.internal.DescribingHandler) ChainHandler(ratpack.handling.internal.ChainHandler) DescribingHandler(ratpack.handling.internal.DescribingHandler) Handler(ratpack.handling.Handler) Response(ratpack.http.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultContext(ratpack.handling.internal.DefaultContext)

Example 89 with ByteBuf

use of io.netty.buffer.ByteBuf in project ratpack by ratpack.

the class JsonRenderer method render.

@Override
public void render(Context ctx, JsonRender object) throws Exception {
    ObjectWriter writer = object.getObjectWriter();
    if (writer == null) {
        writer = ctx.maybeGet(ObjectWriter.class).orElseGet(() -> ctx.get(ObjectMapper.class).writer());
    }
    Class<?> viewClass = object.getViewClass();
    if (viewClass != null) {
        writer = writer.withView(viewClass);
    }
    ByteBuf buffer = ctx.get(ByteBufAllocator.class).buffer();
    OutputStream outputStream = new ByteBufOutputStream(buffer);
    try {
        writer.writeValue(outputStream, object.getObject());
    } catch (JsonProcessingException e) {
        buffer.release();
        ctx.error(e);
        return;
    }
    ctx.getResponse().contentTypeIfNotSet(HttpHeaderConstants.JSON).send(buffer);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) OutputStream(java.io.OutputStream) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ByteBuf(io.netty.buffer.ByteBuf) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 90 with ByteBuf

use of io.netty.buffer.ByteBuf in project ratpack by ratpack.

the class ContentAggregatingRequestAction method addResponseHandlers.

@Override
protected void addResponseHandlers(ChannelPipeline p, Downstream<? super ReceivedResponse> downstream) {
    p.addLast(AGGREGATOR_HANDLER_NAME, new HttpObjectAggregator(requestConfig.maxContentLength));
    p.addLast(RESPONSE_HANDLER_NAME, new SimpleChannelInboundHandler<FullHttpResponse>(false) {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception {
            response.touch();
            dispose(ctx.pipeline(), response);
            ByteBuf content = response.content();
            execution.onComplete(() -> {
                if (content.refCnt() > 0) {
                    content.release();
                }
            });
            success(downstream, toReceivedResponse(response, content));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            forceDispose(ctx.pipeline());
            error(downstream, cause);
        }
    });
}
Also used : HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ByteBuf (io.netty.buffer.ByteBuf)1557 Test (org.junit.Test)668 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)162 IOException (java.io.IOException)99 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)89 CompositeByteBuf (io.netty.buffer.CompositeByteBuf)81 Test (org.testng.annotations.Test)68 InetSocketAddress (java.net.InetSocketAddress)60 Channel (io.netty.channel.Channel)57 ChannelFuture (io.netty.channel.ChannelFuture)56 ArrayList (java.util.ArrayList)55 Map (java.util.Map)45 ChannelPromise (io.netty.channel.ChannelPromise)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)36 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)35 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 HashMap (java.util.HashMap)34 CountDownLatch (java.util.concurrent.CountDownLatch)34 RecyclableDuplicateByteBuf (io.netty.buffer.RecyclableDuplicateByteBuf)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32