Example usage for io.netty.util ReferenceCountUtil safeRelease

List of usage examples for io.netty.util ReferenceCountUtil safeRelease

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil safeRelease.

Prototype

public static void safeRelease(Object msg) 

Source Link

Document

Try to call ReferenceCounted#release() if the specified message implements ReferenceCounted .

Usage

From source file:com.amazonaws.http.JsonRxNettyErrorResponseHandler.java

License:Apache License

public Observable<AmazonServiceException> handle(HttpClientResponse<ByteBuf> response) throws Exception {
    return response.getContent().reduce(new ByteArrayOutputStream(), (out, bb) -> {
        try {/*from  w w  w.j  a v a 2 s  .  c  o  m*/
            bb.readBytes(out, bb.readableBytes());
            return out;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } finally {
            ReferenceCountUtil.safeRelease(bb);
        }
    }).observeOn(RxSchedulers.computation()).map(out -> {
        JSONObject jsonErrorMessage;
        try {
            String s = new String(out.toByteArray());
            if (s.length() == 0 || s.trim().length() == 0)
                s = "{}";
            jsonErrorMessage = new JSONObject(s);
        } catch (Exception e) {
            throw new AmazonClientException("Unable to parse error response", e);
        }

        String errorTypeFromHeader = parseErrorTypeFromHeader(response);

        AmazonServiceException ase = runErrorUnmarshallers(response, jsonErrorMessage, errorTypeFromHeader);
        if (ase == null)
            return null;

        ase.setServiceName(serviceName);
        ase.setStatusCode(response.getStatus().code());
        if (response.getStatus().code() < 500) {
            ase.setErrorType(ErrorType.Client);
        } else {
            ase.setErrorType(ErrorType.Service);
        }

        ase.setRequestId(response.getHeaders().get("X-Amzn-RequestId"));

        return ase;
    });
}

From source file:com.amazonaws.http.JsonRxNettyErrorResponseHandlerV2.java

License:Apache License

public Observable<AmazonServiceException> handle(HttpClientResponse<ByteBuf> response) throws Exception {
    return response.getContent().reduce(new ByteArrayOutputStream(), (out, bb) -> {
        try {//  ww w  . jav a  2 s  . c o  m
            bb.readBytes(out, bb.readableBytes());
            return out;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } finally {
            ReferenceCountUtil.safeRelease(bb);
        }
    }).observeOn(RxSchedulers.computation()).map(out -> {
        JsonContent jsonContent;
        try {
            String s = new String(out.toByteArray());
            if (s.length() == 0 || s.trim().length() == 0)
                s = "{}";
            jsonContent = new JsonContent(s);
        } catch (Exception e) {
            throw new AmazonClientException("Unable to parse error response", e);
        }

        Map<String, String> responseHeaders = new HashMap<String, String>();
        for (String k : response.getHeaders().names()) {
            // TODO: comma seperated?
            responseHeaders.put(k, response.getHeaders().get(k));
        }

        String errorCode = errorCodeParser.parseErrorCode(responseHeaders, jsonContent.jsonNode);
        AmazonServiceException ase = runErrorUnmarshallers(errorCode, jsonContent);

        ase.setErrorCode(errorCode);
        ase.setServiceName(serviceName);
        ase.setStatusCode(response.getStatus().code());
        ase.setRawResponseContent(jsonContent.rawJsonContent);

        if (response.getStatus().code() < 500) {
            ase.setErrorType(ErrorType.Client);
        } else {
            ase.setErrorType(ErrorType.Service);
        }

        ase.setRequestId(response.getHeaders().get("X-Amzn-RequestId"));

        return ase;
    });
}

From source file:com.amazonaws.http.JsonRxNettyResponseHandler.java

License:Apache License

public Observable<AmazonWebServiceResponse<T>> handle(HttpClientResponse<ByteBuf> response) throws Exception {

    return response.getContent().reduce(new ByteArrayOutputStream(), (out, bb) -> {
        try {/*from w  ww  . ja v a 2 s  .  c om*/
            bb.readBytes(out, bb.readableBytes());
            return out;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } finally {
            ReferenceCountUtil.safeRelease(bb);
        }
    }).observeOn(RxSchedulers.computation()).map(out -> {
        return new ByteArrayInputStream(out.toByteArray());
    }).map(in -> {
        String CRC32Checksum = response.getHeaders().get("x-amz-crc32");
        CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null;
        JsonParser jsonParser = null;
        try {
            if (!needsConnectionLeftOpen) {
                if (CRC32Checksum != null) {
                    crc32ChecksumInputStream = new CRC32ChecksumCalculatingInputStream(in);
                    jsonParser = jsonFactory.createJsonParser(crc32ChecksumInputStream);
                } else {
                    jsonParser = jsonFactory.createJsonParser(in);
                }
            }

            AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
            JsonUnmarshallerContext unmarshallerContext = new JsonRxNettyUnmarshallerContextImpl(jsonParser,
                    response.getHeaders());
            registerAdditionalMetadataExpressions(unmarshallerContext);

            T result = responseUnmarshaller.unmarshall(unmarshallerContext);

            if (CRC32Checksum != null) {
                long serverSideCRC = Long.parseLong(CRC32Checksum);
                long clientSideCRC = crc32ChecksumInputStream.getCRC32Checksum();
                if (clientSideCRC != serverSideCRC) {
                    throw new CRC32MismatchException(
                            "Client calculated crc32 checksum didn't match that calculated by server side ["
                                    + clientSideCRC + " != " + serverSideCRC + "]");
                }
            }

            awsResponse.setResult(result);

            Map<String, String> metadata = unmarshallerContext.getMetadata();
            metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get("x-amzn-RequestId"));
            awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

            log.trace("Done parsing service response");
            return awsResponse;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } catch (java.lang.Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (!needsConnectionLeftOpen) {
                try {
                    jsonParser.close();
                } catch (Exception e) {
                }
            }
        }
    });
}

From source file:com.amazonaws.http.StaxRxNettyResponseHandler.java

License:Apache License

@Override
public Observable<AmazonWebServiceResponse<T>> handle(HttpClientResponse<ByteBuf> response) throws Exception {
    return response.getContent().reduce(new ByteArrayOutputStream(),
            new Func2<ByteArrayOutputStream, ByteBuf, ByteArrayOutputStream>() {
                @Override//w ww .  j a va  2  s.co  m
                public ByteArrayOutputStream call(ByteArrayOutputStream out, ByteBuf bb) {
                    try {
                        bb.readBytes(out, bb.readableBytes());
                        return out;
                    } catch (java.io.IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        ReferenceCountUtil.safeRelease(bb);
                    }
                }
            }).observeOn(RxSchedulers.computation()).flatMap(out -> {
                byte[] bytes = out.toByteArray();
                if (bytes.length == 0)
                    bytes = "<eof/>".getBytes();
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                XMLEventReader reader = null;
                try {
                    reader = xmlInputFactory.createXMLEventReader(in);
                } catch (XMLStreamException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Map<String, String> responseHeaders = new HashMap<String, String>();
                    for (String k : response.getHeaders().names()) {
                        // TODO: comma seperated?
                        responseHeaders.put(k, response.getHeaders().get(k));
                    }
                    AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
                    StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(reader,
                            responseHeaders);
                    unmarshallerContext.registerMetadataExpression("ResponseMetadata/RequestId", 2,
                            ResponseMetadata.AWS_REQUEST_ID);
                    unmarshallerContext.registerMetadataExpression("requestId", 2,
                            ResponseMetadata.AWS_REQUEST_ID);
                    registerAdditionalMetadataExpressions(unmarshallerContext);

                    T result = responseUnmarshaller.unmarshall(unmarshallerContext);
                    awsResponse.setResult(result);

                    Map<String, String> metadata = unmarshallerContext.getMetadata();
                    if (responseHeaders != null) {
                        if (responseHeaders.get("x-amzn-RequestId") != null) {
                            metadata.put(ResponseMetadata.AWS_REQUEST_ID,
                                    responseHeaders.get("x-amzn-RequestId"));
                        }
                    }
                    awsResponse.setResponseMetadata(new ResponseMetadata(metadata));

                    return Observable.just(awsResponse);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        reader.close();
                    } catch (XMLStreamException e) {
                        log.warn("Error closing xml parser", e);
                    }
                }
            });
}

From source file:com.amazonaws.http.XmlRxNettyErrorResponseHandler.java

License:Apache License

@Override
public Observable<AmazonServiceException> handle(HttpClientResponse<ByteBuf> response) throws Exception {
    // Try to read the error response
    return response.getContent().reduce(new ByteArrayOutputStream(),
            new Func2<ByteArrayOutputStream, ByteBuf, ByteArrayOutputStream>() {
                @Override/* w  w w.  ja v a  2 s.  c  o  m*/
                public ByteArrayOutputStream call(ByteArrayOutputStream out, ByteBuf bb) {
                    try {
                        bb.readBytes(out, bb.readableBytes());
                        return out;
                    } catch (java.io.IOException e) {
                        throw newAmazonServiceException("Unable to unmarshall error response", response, e);
                    } finally {
                        ReferenceCountUtil.safeRelease(bb);
                    }
                }
            }).observeOn(RxSchedulers.computation()).map(new Func1<ByteArrayOutputStream, Document>() {
                @Override
                public Document call(ByteArrayOutputStream out) {
                    String content = new String(out.toByteArray());
                    try {
                        return XpathUtils.documentFrom(content);
                    } catch (Exception e) {
                        throw newAmazonServiceException(
                                String.format("Unable to unmarshall error response (%s)", content), response,
                                e);
                    }
                }
            }).map(new Func1<Document, AmazonServiceException>() {
                @Override
                public AmazonServiceException call(Document document) {
                    for (Unmarshaller<AmazonServiceException, Node> unmarshaller : unmarshallerList) {
                        try {
                            AmazonServiceException ase = unmarshaller.unmarshall(document);
                            if (ase != null) {
                                ase.setStatusCode(response.getStatus().code());
                                return ase;
                            }
                        } catch (Exception e) {
                        }
                    }
                    throw new AmazonClientException("Unable to unmarshall error response from service");
                }
            }).onErrorResumeNext(new Func1<Throwable, Observable<AmazonServiceException>>() {
                @Override
                public Observable<AmazonServiceException> call(Throwable t) {
                    if (t instanceof AmazonServiceException)
                        return Observable.just((AmazonServiceException) t);
                    else
                        return Observable.error(t);
                }
            });
}

From source file:com.linecorp.armeria.client.HttpRequestSubscriber.java

License:Apache License

@Override
public void onNext(HttpObject o) {
    if (!(o instanceof HttpData) && !(o instanceof HttpHeaders)) {
        throw newIllegalStateException(
                "published an HttpObject that's neither Http2Headers nor Http2Data: " + o);
    }//w  w w  .j av a2 s.  co  m

    boolean endOfStream = o.isEndOfStream();
    switch (state) {
    case NEEDS_DATA_OR_TRAILING_HEADERS: {
        if (o instanceof HttpHeaders) {
            final HttpHeaders trailingHeaders = (HttpHeaders) o;
            if (trailingHeaders.status() != null) {
                throw newIllegalStateException("published a trailing HttpHeaders with status: " + o);
            }
            // Trailing headers always end the stream even if not explicitly set.
            endOfStream = true;
        }
        break;
    }
    case DONE:
        ReferenceCountUtil.safeRelease(o);
        return;
    }

    write(o, endOfStream, true);
}

From source file:com.linecorp.armeria.client.HttpRequestSubscriber.java

License:Apache License

private void write(HttpObject o, boolean endOfStream, boolean flush) {
    final Channel ch = ctx.channel();
    if (!ch.isActive()) {
        ReferenceCountUtil.safeRelease(o);
        fail(ClosedSessionException.get());
        return;/* w w w.  j  ava2s .com*/
    }

    if (endOfStream) {
        setDone();
    }

    ch.eventLoop().execute(() -> write0(o, endOfStream, flush));
}

From source file:com.linecorp.armeria.common.http.HttpMessageAggregator.java

License:Apache License

private void onData(HttpData data) {
    boolean added = false;
    try {//  w  ww .  j  av a 2s  . co m
        if (future.isDone()) {
            return;
        }

        final int dataLength = data.length();
        if (dataLength > 0) {
            final int allowedMaxDataLength = Integer.MAX_VALUE - contentLength;
            if (dataLength > allowedMaxDataLength) {
                subscription.cancel();
                fail(new IllegalStateException("content length greater than Integer.MAX_VALUE"));
                return;
            }

            contentList.add(data);
            contentLength += dataLength;
            added = true;
        }
    } finally {
        if (!added) {
            ReferenceCountUtil.safeRelease(data);
        }
    }
}

From source file:com.linecorp.armeria.common.HttpMessageAggregator.java

License:Apache License

protected void onData(HttpData data) {
    boolean added = false;
    try {// w  ww.j  a v  a 2  s  .  com
        if (future.isDone()) {
            return;
        }

        final int dataLength = data.length();
        if (dataLength > 0) {
            final int allowedMaxDataLength = Integer.MAX_VALUE - contentLength;
            if (dataLength > allowedMaxDataLength) {
                subscription.cancel();
                fail(new IllegalStateException("content length greater than Integer.MAX_VALUE"));
                return;
            }

            contentList.add(data);
            contentLength += dataLength;
            added = true;
        }
    } finally {
        if (!added) {
            ReferenceCountUtil.safeRelease(data);
        }
    }
}

From source file:com.linecorp.armeria.common.HttpResponse.java

License:Apache License

/**
 * Creates a new HTTP response of the specified objects and closes the stream.
 *//*w w w  .  j a  v  a 2s .co  m*/
static HttpResponse of(HttpHeaders headers, HttpData content, HttpHeaders trailingHeaders) {
    requireNonNull(headers, "headers");
    requireNonNull(content, "content");
    requireNonNull(trailingHeaders, "trailingHeaders");

    final HttpStatus status = headers.status();

    // From the section 8.1.2.4 of RFC 7540:
    //// For HTTP/2 responses, a single :status pseudo-header field is defined that carries the HTTP status
    //// code field (see [RFC7231], Section 6). This pseudo-header field MUST be included in all responses;
    //// otherwise, the response is malformed (Section 8.1.2.6).
    if (status == null) {
        throw new IllegalStateException("not a response (missing :status)");
    }

    if (isContentAlwaysEmptyWithValidation(status, content, trailingHeaders)) {
        ReferenceCountUtil.safeRelease(content);
        return new OneElementFixedHttpResponse(headers);
    } else if (!content.isEmpty()) {
        if (trailingHeaders.isEmpty()) {
            return new TwoElementFixedHttpResponse(headers, content);
        } else {
            return new RegularFixedHttpResponse(headers, content, trailingHeaders);
        }
    } else if (!trailingHeaders.isEmpty()) {
        return new TwoElementFixedHttpResponse(headers, trailingHeaders);
    } else {
        return new OneElementFixedHttpResponse(headers);
    }
}