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);
}
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);
}
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());
}
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());
}
}
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;
}
Aggregations