Search in sources :

Example 26 with RestException

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

the class TestRestLiCallback method testOnErrorRestLiServiceExceptionNoFilters.

@SuppressWarnings("unchecked")
@Test
public void testOnErrorRestLiServiceExceptionNoFilters() throws Exception {
    RestLiServiceException ex = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    Map<String, String> inputHeaders = Maps.newHashMap();
    inputHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString());
    Map<String, String> restExceptionHeaders = Maps.newHashMap();
    restExceptionHeaders.put("foo", "bar");
    @SuppressWarnings("rawtypes") ArgumentCaptor<Map> augErrorHeadersCapture = ArgumentCaptor.forClass(Map.class);
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(ex, restExceptionHeaders, Collections.<HttpCookie>emptyList());
    responseData.setResponseEnvelope(new GetResponseEnvelope(new EmptyRecord(), responseData));
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    RestException restException = new RestException(new RestResponseBuilder().build());
    // Set up.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_restRequest.getHeaders()).thenReturn(inputHeaders);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), eq(ex), augErrorHeadersCapture.capture(), anyList())).thenReturn(responseData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
    when(_responseHandler.buildRestException(ex, partialResponse)).thenReturn(restException);
    // Invoke.
    _noFilterRestLiCallback.onError(ex, executionReport, _requestAttachmentReader, responseAttachments);
    // Verify.
    verify(_responseHandler).buildRestException(ex, partialResponse);
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), eq(ex), augErrorHeadersCapture.capture(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
    verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
    verify(_restRequest, times(1)).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
    Map<String, String> augErrorHeaders = augErrorHeadersCapture.getValue();
    assertNotNull(augErrorHeaders);
    assertFalse(augErrorHeaders.isEmpty());
    assertTrue(augErrorHeaders.containsKey(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION));
    assertEquals(augErrorHeaders.get(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION), AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString());
    String errorHeaderName = HeaderUtil.getErrorResponseHeaderName(inputHeaders);
    assertTrue(augErrorHeaders.containsKey(errorHeaderName));
    assertEquals(augErrorHeaders.get(errorHeaderName), RestConstants.HEADER_VALUE_ERROR);
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) Map(java.util.Map) Matchers.anyMap(org.mockito.Matchers.anyMap) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 27 with RestException

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

the class TestRestLiCallback method testOnSuccessWithExceptionBuildingResponseNoFilters.

@SuppressWarnings("unchecked")
@Test
public void testOnSuccessWithExceptionBuildingResponseNoFilters() throws Exception {
    String result = "foo";
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    RestLiServiceException ex = new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY);
    Map<String, String> inputHeaders = Maps.newHashMap();
    inputHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString());
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(ex, new HashMap<String, String>(), Collections.<HttpCookie>emptyList());
    responseData.setResponseEnvelope(new GetResponseEnvelope(new EmptyRecord(), responseData));
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    RestException restException = new RestException(new RestResponseBuilder().build());
    // Set up.
    // Throw an exception when we try to build the response data.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildRestLiResponseData(_restRequest, _routingResult, result)).thenThrow(ex);
    when(_restRequest.getHeaders()).thenReturn(inputHeaders);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), eq(ex), anyMap(), anyList())).thenReturn(responseData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
    when(_responseHandler.buildRestException(ex, partialResponse)).thenReturn(restException);
    // invoke request filters so cursor is in correct place
    when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
    _twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
    // Invoke.
    _noFilterRestLiCallback.onSuccess(result, executionReport, responseAttachments);
    // Verify.
    verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, result);
    verify(_responseHandler).buildRestException(ex, partialResponse);
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), eq(ex), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
    verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
    verify(_restRequest).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 28 with RestException

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

the class TestRestLiMethodInvocation method testInvokeWithUnsupportedAcceptMimeType.

@Test
public void testInvokeWithUnsupportedAcceptMimeType() throws Exception {
    RestRequestBuilder builder = new RestRequestBuilder(new URI("")).addHeaderValue("Accept", "text/plain").setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString());
    RestRequest request = builder.build();
    final RestLiAttachmentReader attachmentReader = new RestLiAttachmentReader(null);
    final CountDownLatch latch = new CountDownLatch(1);
    RestLiResponseHandler restLiResponseHandler = new RestLiResponseHandler.Builder().build();
    RequestExecutionCallback<RestResponse> executionCallback = new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            latch.countDown();
            Assert.assertTrue(e instanceof RestException);
            RestException ex = (RestException) e;
            Assert.assertEquals(ex.getResponse().getStatus(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
            Assert.assertEquals(requestAttachmentReader, attachmentReader);
            Assert.assertNull(responseAttachments);
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail();
        }
    };
    ServerResourceContext resourceContext = new ResourceContextImpl(new PathKeysImpl(), new RestRequestBuilder(URI.create("")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.LATEST_PROTOCOL_VERSION.toString()).build(), new RequestContext(), false, attachmentReader);
    try {
        RoutingResult routingResult = new RoutingResult(resourceContext, null);
        RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) routingResult.getContext());
        FilterChainCallback filterChainCallback = new FilterChainCallbackImpl(null, _invoker, null, null, null, restLiResponseHandler, executionCallback);
        final RestLiCallback<Object> callback = new RestLiCallback<Object>(null, new RestLiFilterResponseContextFactory<Object>(request, null, restLiResponseHandler), new RestLiFilterChain(null, filterChainCallback));
        _invoker.invoke(null, routingResult, null, callback, null);
        latch.await();
    } catch (Exception e) {
        // exception is expected
        Assert.assertTrue(e instanceof RestLiServiceException);
    }
    Assert.assertNull(resourceContext.getResponseMimeType());
}
Also used : URI(java.net.URI) RestLiFilterChain(com.linkedin.restli.internal.server.filter.RestLiFilterChain) RequestExecutionCallback(com.linkedin.restli.server.RequestExecutionCallback) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RestLiResponseHandler(com.linkedin.restli.internal.server.response.RestLiResponseHandler) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterChainCallbackImpl(com.linkedin.restli.internal.server.filter.FilterChainCallbackImpl) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl) RestResponse(com.linkedin.r2.message.rest.RestResponse) PathKeysImpl(com.linkedin.restli.internal.server.PathKeysImpl) RestException(com.linkedin.r2.message.rest.RestException) CountDownLatch(java.util.concurrent.CountDownLatch) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestException(com.linkedin.r2.message.rest.RestException) URISyntaxException(java.net.URISyntaxException) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestLiSyntaxException(com.linkedin.restli.internal.server.util.RestLiSyntaxException) RestRequest(com.linkedin.r2.message.rest.RestRequest) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) EasyMock.anyObject(org.easymock.EasyMock.anyObject) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 29 with RestException

use of com.linkedin.r2.message.rest.RestException in project voldemort by voldemort.

the class R2Store method put.

@Override
public void put(ByteArray key, Versioned<byte[]> value, byte[] transform) throws VoldemortException {
    RestResponse response = null;
    try {
        byte[] payload = value.getValue();
        // Create the REST request with this byte array
        String base64Key = RestUtils.encodeVoldemortKey(key.get());
        RestRequestBuilder rb = new RestRequestBuilder(new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));
        // Create a HTTP POST request
        rb.setMethod(POST);
        rb.setEntity(payload);
        rb.setHeader(CONTENT_TYPE, "binary");
        rb.setHeader(CONTENT_LENGTH, "" + payload.length);
        String timeoutStr = Long.toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.PUT_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, String.valueOf(System.currentTimeMillis()));
        if (this.routingTypeCode != null) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
        }
        if (this.zoneId != INVALID_ZONE_ID) {
            rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
        }
        // Serialize the Vector clock
        VectorClock vc = (VectorClock) value.getVersion();
        // doing the put.
        if (vc != null) {
            String serializedVC = null;
            if (!vc.getEntries().isEmpty()) {
                serializedVC = RestUtils.getSerializedVectorClock(vc);
            }
            if (serializedVC != null && serializedVC.length() > 0) {
                rb.setHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, serializedVC);
            }
        }
        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);
        // This will block
        response = f.get();
        String serializedUpdatedVC = response.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK);
        if (serializedUpdatedVC == null || serializedUpdatedVC.length() == 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received empty vector clock in the response");
            }
        } else {
            VectorClock updatedVC = RestUtils.deserializeVectorClock(serializedUpdatedVC);
            VectorClock originalVC = (VectorClock) value.getVersion();
            originalVC.copyFromVectorClock(updatedVC);
        }
        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
            int httpErrorStatus = exception.getResponse().getStatus();
            if (httpErrorStatus == BAD_REQUEST.getCode()) {
                throw new VoldemortException("Bad request: " + e.getMessage(), e);
            } else if (httpErrorStatus == PRECONDITION_FAILED.getCode()) {
                throw new ObsoleteVersionException(e.getMessage());
            } else if (httpErrorStatus == REQUEST_TIMEOUT.getCode() || httpErrorStatus == INTERNAL_SERVER_ERROR.getCode()) {
                throw new InsufficientOperationalNodesException(e.getMessage());
            }
        }
        throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage());
        }
        throw new VoldemortException("Unknown Voldemort exception: " + e.getMessage());
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage());
    }
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) VectorClock(voldemort.versioning.VectorClock) RestException(com.linkedin.r2.message.rest.RestException) ByteString(com.linkedin.data.ByteString) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) VoldemortException(voldemort.VoldemortException) RestRequest(com.linkedin.r2.message.rest.RestRequest) ObsoleteVersionException(voldemort.versioning.ObsoleteVersionException) InsufficientOperationalNodesException(voldemort.store.InsufficientOperationalNodesException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 30 with RestException

use of com.linkedin.r2.message.rest.RestException in project voldemort by voldemort.

the class R2Store method getVersions.

@Override
public List<Version> getVersions(ByteArray key) {
    List<Version> resultList = new ArrayList<Version>();
    String base64Key = RestUtils.encodeVoldemortKey(key.get());
    RestRequestBuilder rb = null;
    try {
        rb = new RestRequestBuilder(new URI(this.restBootstrapURL + "/" + getName() + "/" + base64Key));
        String timeoutStr = Long.toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE));
        rb.setHeader(RestMessageHeaders.X_VOLD_GET_VERSION, "true");
        RestResponse response = fetchGetResponse(rb, timeoutStr);
        final ByteString entity = response.getEntity();
        if (entity != null) {
            resultList = parseGetVersionResponse(entity);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Did not get any response!");
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
        } else {
            throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage(), e);
        }
        throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e);
    }
    return resultList;
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) ArrayList(java.util.ArrayList) RestException(com.linkedin.r2.message.rest.RestException) ByteString(com.linkedin.data.ByteString) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) VoldemortException(voldemort.VoldemortException) Version(voldemort.versioning.Version) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

RestException (com.linkedin.r2.message.rest.RestException)62 RestResponse (com.linkedin.r2.message.rest.RestResponse)48 Test (org.testng.annotations.Test)44 RestRequest (com.linkedin.r2.message.rest.RestRequest)33 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)31 URI (java.net.URI)23 BeforeTest (org.testng.annotations.BeforeTest)21 ExecutionException (java.util.concurrent.ExecutionException)20 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)19 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)19 RequestContext (com.linkedin.r2.message.RequestContext)18 Callback (com.linkedin.common.callback.Callback)16 URISyntaxException (java.net.URISyntaxException)16 ByteString (com.linkedin.data.ByteString)15 AfterTest (org.testng.annotations.AfterTest)12 MultiPartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback)11 SinglePartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback)11 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)11 RequestExecutionReport (com.linkedin.restli.server.RequestExecutionReport)11 RestLiResponseAttachments (com.linkedin.restli.server.RestLiResponseAttachments)11