Example usage for io.netty.handler.codec.http HttpContent release

List of usage examples for io.netty.handler.codec.http HttpContent release

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpContent release.

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:cc.blynk.core.http.handlers.UploadHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (!accept(ctx, req)) {
            ctx.fireChannelRead(msg);/*from  w  w  w  .  ja v  a 2s  . c  o  m*/
            return;
        }

        try {
            log.debug("Incoming {} {}", req.method(), req.uri());
            decoder = new HttpPostRequestDecoder(factory, req);
        } catch (ErrorDataDecoderException e) {
            log.error("Error creating http post request decoder.", e);
            ctx.writeAndFlush(badRequest(e.getMessage()));
            return;
        }

    }

    if (decoder != null && msg instanceof HttpContent) {
        // New chunk is received
        HttpContent chunk = (HttpContent) msg;
        try {
            decoder.offer(chunk);
        } catch (ErrorDataDecoderException e) {
            log.error("Error creating http post offer.", e);
            ctx.writeAndFlush(badRequest(e.getMessage()));
            return;
        } finally {
            chunk.release();
        }

        // example of reading only if at the end
        if (chunk instanceof LastHttpContent) {
            Response response;
            try {
                String path = finishUpload();
                if (path != null) {
                    response = afterUpload(ctx, path);
                } else {
                    response = serverError("Can't find binary data in request.");
                }
            } catch (NoSuchFileException e) {
                log.error("Unable to copy uploaded file to static folder. Reason : {}", e.getMessage());
                response = (serverError());
            } catch (Exception e) {
                log.error("Error during file upload.", e);
                response = (serverError());
            }
            ctx.writeAndFlush(response);
        }
    }
}

From source file:io.crate.protocols.http.HttpAuthUpstreamHandler.java

private void handleHttpChunk(ChannelHandlerContext ctx, HttpContent msg) {
    if (authorized) {
        ctx.fireChannelRead(msg);/*  ww  w .j  a v a 2  s .c o  m*/
    } else {
        // We won't forward the message downstream, thus we have to release
        msg.release();
        sendUnauthorized(ctx.channel(), null);
    }
}

From source file:org.ballerinalang.net.grpc.ClientConnectorListener.java

License:Open Source License

@Override
public void onMessage(HttpCarbonMessage httpMessage) {
    InboundMessage inboundMessage = new InboundMessage(httpMessage);
    if (isValid(inboundMessage)) {
        stateListener.inboundHeadersReceived(inboundMessage.getHeaders());
    }/*from ww w .  j a v a2 s .c om*/

    final Executor wrappedExecutor = ThreadPoolFactory.getInstance().getWorkerExecutor();
    wrappedExecutor.execute(() -> {
        try {
            HttpContent httpContent = inboundMessage.getHttpCarbonMessage().getHttpContent();
            while (true) {
                if (httpContent == null) {
                    break;
                }
                if (transportError != null) {
                    // Referenced from grpc-java, when transport error exists. we collect more details about the
                    // error by augmenting the description.
                    transportError = transportError.augmentDescription(
                            "MESSAGE DATA: " + readAsString(httpContent, Charset.forName("UTF-8")));
                    // Release content as we are not going to process it.
                    httpContent.release();
                    // Report transport error.
                    if ((transportError.getDescription() != null
                            && transportError.getDescription().length() > 1000)
                            || (httpContent instanceof LastHttpContent)) {
                        stateListener.transportReportStatus(transportError, false, transportErrorMetadata);
                        break;
                    }
                } else {
                    stateListener.inboundDataReceived(httpContent);
                    // Exit the loop at the end of the content
                    if (httpContent instanceof LastHttpContent) {
                        LastHttpContent lastHttpContent = (LastHttpContent) httpContent;
                        if (lastHttpContent.decoderResult() != null
                                && lastHttpContent.decoderResult().isFailure()) {
                            transportError = Status.Code.ABORTED.toStatus()
                                    .withDescription(lastHttpContent.decoderResult().cause().getMessage());
                        } else if (lastHttpContent.trailingHeaders().isEmpty()) {
                            // This is a protocol violation as we expect to receive trailer headers with Last Http
                            // content.
                            transportError = Status.Code.INTERNAL.toStatus()
                                    .withDescription("Received unexpected" + " EOS on DATA frame from server.");
                            transportErrorMetadata = new DefaultHttpHeaders();
                            stateListener.transportReportStatus(transportError, false, transportErrorMetadata);
                        } else {
                            // Read Trailer header to get gRPC response status.
                            transportTrailersReceived(lastHttpContent.trailingHeaders());
                        }
                        break;
                    }
                }
                httpContent = inboundMessage.getHttpCarbonMessage().getHttpContent();
            }
        } catch (RuntimeException e) {
            if (transportError != null) {
                // Already received a transport error so just augment it.
                transportError = transportError.augmentDescription(e.getMessage());
            } else {
                transportError = Status.fromThrowable(e);
            }
            stateListener.transportReportStatus(transportError, false, transportErrorMetadata);
        }
    });
}

From source file:org.ballerinalang.net.grpc.MessageDeframer.java

License:Open Source License

public void deframe(HttpContent data) {
    if (data == null) {
        throw new RuntimeException("Data buffer is null");
    }/*w w w  .j a  v a2s . c  om*/
    boolean needToCloseData = true;
    try {
        if (!isClosedOrScheduledToClose()) {
            unprocessed.addBuffer(data.content());
            needToCloseData = false;
            deliver();
        }
    } finally {
        if (needToCloseData && data.refCnt() != 0) {
            data.release();
        }
    }
}

From source file:org.ebayopensource.scc.filter.NettyResponseProxyFilter.java

License:Apache License

@Override
public HttpObject filterResponse(HttpObject orignal, ChannelHandlerContext ctx) {
    HttpObject httpObject = orignal;//ww w  .j  a va2 s.c  o m
    if (httpObject instanceof HttpResponse) {
        String uri = ctx.attr(NettyRequestProxyFilter.REQUEST_URI).get();
        LOGGER.info("Received a response from: " + uri);
        if (((HttpResponse) httpObject).getStatus().code() >= 300) {
            ctx.attr(NettyRequestProxyFilter.IS_CACHABLE).set(false);
        }
    }
    if (!ctx.attr(NettyRequestProxyFilter.IS_CACHABLE).get()) {
        return httpObject;
    }
    final String key = ctx.attr(NettyRequestProxyFilter.CACHE_KEY).get();
    if (key == null) {
        return httpObject;
    }

    if (httpObject instanceof HttpResponse) {
        LOGGER.debug("Response code: " + ((HttpResponse) httpObject).getStatus().code());
    }
    if (httpObject instanceof FullHttpResponse) {
        m_policyManager.getCacheManager().put(key, httpObject);
    } else {
        final List<HttpObject> chunkedResponses = m_chunkedResponses.get();
        if (httpObject instanceof HttpContent) {
            HttpContent httpContent = ((HttpContent) httpObject).duplicate();
            httpContent.retain();
            httpObject = httpContent;
        }
        chunkedResponses.add(httpObject);
        if (httpObject instanceof LastHttpContent) {
            Runnable runnable = new Runnable() {

                @Override
                public void run() {
                    try {
                        m_policyManager.getCacheManager().put(key, chunkedResponses);
                    } catch (Throwable t) {
                        LOGGER.error(t.getMessage(), t);
                        return;
                    }
                    for (HttpObject obj : chunkedResponses) {
                        if (obj instanceof HttpContent) {
                            HttpContent httpContent = (HttpContent) obj;
                            httpContent.release();
                        }
                    }
                    chunkedResponses.clear();
                    LOGGER.debug("Cache response to: " + key);
                }

            };
            m_execService.submit(runnable);
        }
    }
    return orignal;
}

From source file:org.wso2.carbon.transport.http.netty.message.BlockingEntityCollector.java

License:Open Source License

public void waitAndReleaseAllEntities() {
    if (!isConsumed.get() && !alreadyRead.get()) {
        boolean isEndOfMessageProcessed = false;
        while (!isEndOfMessageProcessed) {
            try {
                HttpContent httpContent = httpContentQueue.poll(soTimeOut, TimeUnit.SECONDS);
                // This check is to make sure we add the last http content after getClone and avoid adding
                // empty content to bytebuf list again and again
                if (httpContent instanceof EmptyLastHttpContent) {
                    break;
                }//from   www.  ja  va  2 s .c om

                if (httpContent instanceof LastHttpContent) {
                    isEndOfMessageProcessed = true;
                    isConsumed.set(true);
                }
                httpContent.release();
            } catch (InterruptedException e) {
                LOG.error("Error while getting full message body", e);
            }
        }
    }
}

From source file:org.wso2.msf4j.internal.MSF4JHttpConnectorListener.java

License:Open Source License

/**
 * Dispatch appropriate resource method.
 */// w  w w .ja v  a 2s.com
private void dispatchMethod(MicroservicesRegistryImpl registry, Request request, Response response)
        throws Exception {
    HttpUtil.setConnectionHeader(request, response);
    PatternPathRouter.RoutableDestination<HttpResourceModel> destination = registry.getMetadata()
            .getDestinationMethod(request.getUri(), request.getHttpMethod(), request.getContentType(),
                    request.getAcceptTypes());
    HttpResourceModel resourceModel = destination.getDestination();
    response.setMediaType(
            Util.getResponseType(request.getAcceptTypes(), resourceModel.getProducesMediaTypes()));
    HttpMethodInfoBuilder httpMethodInfoBuilder = new HttpMethodInfoBuilder().httpResourceModel(resourceModel)
            .httpRequest(request).httpResponder(response).requestInfo(destination.getGroupNameValues());
    HttpMethodInfo httpMethodInfo = httpMethodInfoBuilder.build();
    if (httpMethodInfo.isStreamingSupported()) {
        Method method = resourceModel.getMethod();
        Class<?> clazz = method.getDeclaringClass();
        // Execute request interceptors
        if (InterceptorExecutor.executeGlobalRequestInterceptors(registry, request, response)
                // Execute class level request interceptors
                && InterceptorExecutor.executeClassLevelRequestInterceptors(request, response, clazz)
                // Execute method level request interceptors
                && InterceptorExecutor.executeMethodLevelRequestInterceptors(request, response, method)) {

            HTTPCarbonMessage carbonMessage = getHttpCarbonMessage(request);
            HttpContent httpContent = carbonMessage.getHttpContent();
            while (true) {
                if (httpContent == null) {
                    break;
                }
                httpMethodInfo.chunk(httpContent.content().nioBuffer());
                httpContent.release();
                // Exit the loop at the end of the content
                if (httpContent instanceof LastHttpContent) {
                    break;
                }
                httpContent = carbonMessage.getHttpContent();
            }
            boolean isResponseInterceptorsSuccessful = InterceptorExecutor
                    .executeMethodLevelResponseInterceptors(request, response, method)
                    // Execute class level interceptors (first in - last out order)
                    && InterceptorExecutor.executeClassLevelResponseInterceptors(request, response, clazz)
                    // Execute global interceptors
                    && InterceptorExecutor.executeGlobalResponseInterceptors(registry, request, response);
            httpMethodInfo.end(isResponseInterceptorsSuccessful);
        }
    } else {
        httpMethodInfo.invoke(destination, request, httpMethodInfo, registry);
    }
}

From source file:ratpack.server.internal.RequestBody.java

License:Apache License

@Override
public void add(HttpContent httpContent) {
    if (state == State.READ) {
        httpContent.release();
    } else {//from w w  w. j a va 2s . com
        if (httpContent instanceof LastHttpContent) {
            ctx.channel().closeFuture().removeListener(closeListener);
            receivedLast = true;
        }

        if (listener == null) {
            addToReceived(httpContent);
        } else {
            listener.onContent(httpContent);
        }
    }
}

From source file:ratpack.server.internal.RequestBody.java

License:Apache License

public void drain(Consumer<? super Throwable> resume) {
    release();// w ww . ja  va  2 s  .  co m

    if (!isUnread()) {
        throw new RequestBodyAlreadyReadException();
    }

    state = State.READING;
    if (earlyClose) {
        discard();
        resume.accept(null);
    } else if (advertisedLength > maxContentLength || receivedLength > maxContentLength) {
        discard();
        resume.accept(tooLargeException(advertisedLength));
    } else if (receivedLast || isContinueExpected()) {
        release(); // don't close connection, we can reuse
        state = State.READ;
        resume.accept(null);
    } else {
        listener = new Listener() {
            @Override
            public void onContent(HttpContent httpContent) {
                httpContent.release();
                if ((receivedLength += httpContent.content().readableBytes()) > maxContentLength) {
                    state = State.READ;
                    listener = null;
                    resume.accept(tooLargeException(RequestBody.this.receivedLength));
                } else if (httpContent instanceof LastHttpContent) {
                    state = State.READ;
                    listener = null;
                    resume.accept(null);
                } else {
                    ctx.read();
                }
            }

            @Override
            public void onEarlyClose() {
                resume.accept(null);
            }
        };

        // Don't use startBodyRead as we don't want to issue continue
        ctx.read();
    }

}