Search in sources :

Example 6 with StreamException

use of com.linkedin.r2.message.stream.StreamException in project rest.li by linkedin.

the class TestRestLiServer method testInternalErrorMessage.

@Test(dataProvider = "restOrStream")
public void testInternalErrorMessage(final RestOrStream restOrStream) throws Exception {
    final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.get(eq(1L))).andThrow(new IllegalArgumentException("oops")).once();
    EasyMock.replay(statusResource);
    Callback<RestResponse> restResponseCallback = new Callback<RestResponse>() {

        @Override
        public void onSuccess(RestResponse restResponse) {
            fail();
        }

        @Override
        public void onError(Throwable e) {
            assertTrue(e instanceof RestException);
            RestException restException = (RestException) e;
            RestResponse restResponse = restException.getResponse();
            try {
                ErrorResponse responseBody = DataMapUtils.read(restResponse.getEntity().asInputStream(), ErrorResponse.class);
                assertEquals(responseBody.getMessage(), ErrorResponseBuilder.DEFAULT_INTERNAL_ERROR_MESSAGE);
                EasyMock.verify(statusResource);
                EasyMock.reset(statusResource);
            } catch (Exception e2) {
                fail(e2.toString());
            }
        }
    };
    if (restOrStream == RestOrStream.REST) {
        RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()).build();
        _server.handleRequest(request, new RequestContext(), restResponseCallback);
    } else {
        StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()).build(EntityStreams.emptyStream());
        Callback<StreamResponse> callback = new Callback<StreamResponse>() {

            @Override
            public void onSuccess(StreamResponse streamResponse) {
                fail();
            }

            @Override
            public void onError(Throwable e) {
                Messages.toRestException((StreamException) e, new Callback<RestException>() {

                    @Override
                    public void onError(Throwable e) {
                        Assert.fail();
                    }

                    @Override
                    public void onSuccess(RestException result) {
                        restResponseCallback.onError(result);
                    }
                });
            }
        };
        _server.handleRequest(streamRequest, new RequestContext(), callback);
    }
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) RestException(com.linkedin.r2.message.rest.RestException) URI(java.net.URI) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URISyntaxException(java.net.URISyntaxException) StreamException(com.linkedin.r2.message.stream.StreamException) ParseException(javax.mail.internet.ParseException) RestException(com.linkedin.r2.message.rest.RestException) IOException(java.io.IOException) ErrorResponse(com.linkedin.restli.common.ErrorResponse) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) RestRequest(com.linkedin.r2.message.rest.RestRequest) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 7 with StreamException

use of com.linkedin.r2.message.stream.StreamException in project rest.li by linkedin.

the class TestRestLiServer method testApplicationException.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersions")
public void testApplicationException(final ProtocolVersion protocolVersion, final String errorResponseHeaderName, final RestOrStream restOrStream) throws Exception {
    final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.get(eq(1L))).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Mock Exception")).once();
    EasyMock.replay(statusResource);
    Callback<RestResponse> restResponseCallback = new Callback<RestResponse>() {

        @Override
        public void onSuccess(RestResponse restResponse) {
            fail();
        }

        @Override
        public void onError(Throwable e) {
            assertTrue(e instanceof RestException);
            RestException restException = (RestException) e;
            RestResponse restResponse = restException.getResponse();
            try {
                assertEquals(restResponse.getStatus(), 500);
                assertTrue(restResponse.getEntity().length() > 0);
                assertEquals(restResponse.getHeader(errorResponseHeaderName), RestConstants.HEADER_VALUE_ERROR);
                ErrorResponse responseBody = DataMapUtils.read(restResponse.getEntity().asInputStream(), ErrorResponse.class);
                assertEquals(responseBody.getMessage(), "Mock Exception");
                assertEquals(responseBody.getExceptionClass(), "com.linkedin.restli.server.RestLiServiceException");
                assertTrue(responseBody.getStackTrace().startsWith("com.linkedin.restli.server.RestLiServiceException [HTTP Status:500]: Mock Exception"));
                assertEquals(responseBody.getStatus().intValue(), 500);
                EasyMock.verify(statusResource);
                EasyMock.reset(statusResource);
            } catch (Exception e2) {
                fail(e2.toString());
            }
        }
    };
    if (restOrStream == RestOrStream.REST) {
        RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build();
        _server.handleRequest(request, new RequestContext(), restResponseCallback);
    } else {
        StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build(EntityStreams.emptyStream());
        Callback<StreamResponse> callback = new Callback<StreamResponse>() {

            @Override
            public void onSuccess(StreamResponse streamResponse) {
                fail();
            }

            @Override
            public void onError(Throwable e) {
                Messages.toRestException((StreamException) e, new Callback<RestException>() {

                    @Override
                    public void onError(Throwable e) {
                        Assert.fail();
                    }

                    @Override
                    public void onSuccess(RestException result) {
                        restResponseCallback.onError(result);
                    }
                });
            }
        };
        _server.handleRequest(streamRequest, new RequestContext(), callback);
    }
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) RestException(com.linkedin.r2.message.rest.RestException) URI(java.net.URI) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URISyntaxException(java.net.URISyntaxException) StreamException(com.linkedin.r2.message.stream.StreamException) ParseException(javax.mail.internet.ParseException) RestException(com.linkedin.r2.message.rest.RestException) IOException(java.io.IOException) ErrorResponse(com.linkedin.restli.common.ErrorResponse) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) RestRequest(com.linkedin.r2.message.rest.RestRequest) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 8 with StreamException

use of com.linkedin.r2.message.stream.StreamException in project rest.li by linkedin.

the class HttpDispatcher method handleRequest.

/**
   * handle a {@link com.linkedin.r2.message.stream.StreamRequest} using the given request context.
   * @see com.linkedin.r2.transport.common.bridge.server.TransportDispatcher#handleStreamRequest
   *
   * @param req the request to be handled.
   * @param context the request context.
   * @param callback the callback to be invoked with the response or error.
   */
public void handleRequest(StreamRequest req, RequestContext context, final TransportCallback<StreamResponse> callback) {
    final Map<String, String> headers = new HashMap<String, String>(req.getHeaders());
    final Map<String, String> wireAttrs = WireAttributeHelper.removeWireAttributes(headers);
    final BaseConnector connector = new BaseConnector();
    try {
        MessageType.Type msgType = MessageType.getMessageType(wireAttrs, MessageType.Type.REST);
        switch(msgType) {
            default:
            case REST:
                req.getEntityStream().setReader(connector);
                StreamRequest newReq = req.builder().build(EntityStreams.newEntityStream(connector));
                // decorate the call back so that if response is error or response finishes streaming,
                // we cancel the request stream
                TransportCallback<StreamResponse> decorateCallback = new TransportCallback<StreamResponse>() {

                    @Override
                    public void onResponse(TransportResponse<StreamResponse> response) {
                        // no need to check StreamException because that's handled by HttpBridge.httpToStreamCallback
                        if (response.hasError()) {
                            connector.cancel();
                        } else {
                            Observer observer = new Observer() {

                                @Override
                                public void onDataAvailable(ByteString data) {
                                // do nothing
                                }

                                @Override
                                public void onDone() {
                                    connector.cancel();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    connector.cancel();
                                }
                            };
                            response.getResponse().getEntityStream().addObserver(observer);
                        }
                        callback.onResponse(response);
                    }
                };
                _dispatcher.handleStreamRequest(HttpBridge.toStreamRequest(newReq, headers), wireAttrs, context, HttpBridge.httpToStreamCallback(decorateCallback));
        }
    } catch (Exception e) {
        connector.cancel();
        callback.onResponse(TransportResponseImpl.<StreamResponse>error(e, Collections.<String, String>emptyMap()));
    }
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) HashMap(java.util.HashMap) BaseConnector(com.linkedin.r2.message.stream.entitystream.BaseConnector) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) TransportResponse(com.linkedin.r2.transport.common.bridge.common.TransportResponse) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) Observer(com.linkedin.r2.message.stream.entitystream.Observer) MessageType(com.linkedin.r2.transport.common.MessageType)

Example 9 with StreamException

use of com.linkedin.r2.message.stream.StreamException in project rest.li by linkedin.

the class ClientStreamCompressionFilter method onStreamError.

@Override
public void onStreamError(Throwable ex, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<StreamRequest, StreamResponse> nextFilter) {
    if (ex instanceof StreamException) {
        Boolean decompressionOff = (Boolean) requestContext.getLocalAttr(R2Constants.RESPONSE_DECOMPRESSION_OFF);
        if (decompressionOff == null || !decompressionOff) {
            StreamException se = (StreamException) ex;
            StreamResponse response = se.getResponse();
            //Check for header encoding
            String compressionHeader = response.getHeader(HttpConstants.CONTENT_ENCODING);
            //decompress if necessary
            if (compressionHeader != null) {
                StreamEncodingType encoding = StreamEncodingType.get(compressionHeader.trim().toLowerCase());
                if (encoding != null) {
                    final StreamingCompressor compressor = encoding.getCompressor(_executor);
                    EntityStream uncompressedStream = compressor.inflate(response.getEntityStream());
                    StreamResponseBuilder builder = response.builder();
                    Map<String, String> headers = stripHeaders(builder.getHeaders(), HttpConstants.CONTENT_ENCODING, HttpConstants.CONTENT_LENGTH);
                    response = builder.setHeaders(headers).build(uncompressedStream);
                    ex = new StreamException(response);
                }
            }
        }
    }
    nextFilter.onError(ex, requestContext, wireAttrs);
}
Also used : EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) StreamingCompressor(com.linkedin.r2.filter.compression.streaming.StreamingCompressor) StreamEncodingType(com.linkedin.r2.filter.compression.streaming.StreamEncodingType) StreamException(com.linkedin.r2.message.stream.StreamException)

Example 10 with StreamException

use of com.linkedin.r2.message.stream.StreamException in project rest.li by linkedin.

the class TestServerRetryFilter method testStreamRetryFilter.

@Test
public void testStreamRetryFilter() {
    String retryMessage = "this is a retry";
    ServerRetryFilter retryFilter = new ServerRetryFilter();
    StreamFilter captureFilter = new StreamFilter() {

        @Override
        public void onStreamError(Throwable ex, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<StreamRequest, StreamResponse> nextFilter) {
            Assert.assertEquals(wireAttrs.get(R2Constants.RETRY_MESSAGE_ATTRIBUTE_KEY), retryMessage);
        }
    };
    FilterChain filterChain = FilterChains.createStreamChain(captureFilter, retryFilter);
    FilterUtil.fireRestError(filterChain, new StreamException(null, new RetriableRequestException(retryMessage)), new HashMap<String, String>());
}
Also used : RetriableRequestException(com.linkedin.r2.RetriableRequestException) ServerRetryFilter(com.linkedin.r2.filter.transport.ServerRetryFilter) NextFilter(com.linkedin.r2.filter.NextFilter) FilterChain(com.linkedin.r2.filter.FilterChain) RequestContext(com.linkedin.r2.message.RequestContext) StreamFilter(com.linkedin.r2.filter.message.stream.StreamFilter) HashMap(java.util.HashMap) Map(java.util.Map) StreamException(com.linkedin.r2.message.stream.StreamException) Test(org.testng.annotations.Test)

Aggregations

StreamException (com.linkedin.r2.message.stream.StreamException)24 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)24 Test (org.testng.annotations.Test)23 Callback (com.linkedin.common.callback.Callback)19 RequestContext (com.linkedin.r2.message.RequestContext)17 RestResponse (com.linkedin.r2.message.rest.RestResponse)17 RestRequest (com.linkedin.r2.message.rest.RestRequest)15 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)15 RestException (com.linkedin.r2.message.rest.RestException)14 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)14 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)13 ByteString (com.linkedin.data.ByteString)12 URI (java.net.URI)12 MultiPartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback)11 SinglePartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback)11 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)11 AfterTest (org.testng.annotations.AfterTest)10 BeforeTest (org.testng.annotations.BeforeTest)10 FullEntityReader (com.linkedin.r2.message.stream.entitystream.FullEntityReader)9 AsyncStatusCollectionResource (com.linkedin.restli.server.twitter.AsyncStatusCollectionResource)8