use of com.linkedin.restli.internal.server.util.RestLiSyntaxException in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testStreaming.
@Test
public void testStreaming() throws RestLiSyntaxException, URISyntaxException {
Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, AsyncStatusCollectionResource.class, PromiseStatusCollectionResource.class, TaskStatusCollectionResource.class);
final String payload = "{\"metadata\": \"someMetadata\"}";
ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
ResourceModel asyncStatusResourceModel = resourceModelMap.get("/asyncstatuses");
ResourceModel promiseStatusResourceModel = resourceModelMap.get("/promisestatuses");
ResourceModel taskStatusResourceModel = resourceModelMap.get("/taskstatuses");
ResourceMethodDescriptor methodDescriptor;
StatusCollectionResource statusResource;
AsyncStatusCollectionResource asyncStatusResource;
PromiseStatusCollectionResource promiseStatusResource;
TaskStatusCollectionResource taskStatusResource;
//Sync Method Execution - Successful scenario
methodDescriptor = statusResourceModel.findActionMethod("streamingAction", ResourceLevel.COLLECTION);
statusResource = getMockResource(StatusCollectionResource.class);
EasyMock.expect(statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject())).andReturn(1234l).once();
checkInvocation(statusResource, methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
//Sync Method Execution - Error scenario
statusResource = getMockResource(StatusCollectionResource.class);
EasyMock.expect(statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject())).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR)).once();
checkInvocation(statusResource, methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request passed unexpectedly.");
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Callback Method Execution - Successful scenario
methodDescriptor = asyncStatusResourceModel.findMethod(ResourceMethod.ACTION);
asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
asyncStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
callback.onSuccess(1234l);
return null;
}
});
checkInvocation(asyncStatusResource, methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
//Callback Method Execution - Error scenario
asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
asyncStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
callback.onError(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
return null;
}
});
checkInvocation(asyncStatusResource, methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request passed unexpectedly.");
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Promise Method Execution - Successful scenario
methodDescriptor = promiseStatusResourceModel.findActionMethod("streamingAction", ResourceLevel.COLLECTION);
promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
promiseStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
final SettablePromise<Long> result = Promises.settable();
final Runnable requestHandler = new Runnable() {
public void run() {
try {
result.done(1234l);
} catch (final Throwable throwable) {
result.fail(throwable);
}
}
};
_scheduler.schedule(requestHandler, 0, TimeUnit.MILLISECONDS);
return result;
}
});
checkInvocation(promiseStatusResource, methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
//Promise Method Execution - Error scenario
promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
promiseStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
final SettablePromise<Long> result = Promises.settable();
final Runnable requestHandler = new Runnable() {
public void run() {
result.fail(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
}
};
_scheduler.schedule(requestHandler, 0, TimeUnit.MILLISECONDS);
return result;
}
});
checkInvocation(promiseStatusResource, methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request passed unexpectedly.");
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Task Method Execution - Successful scenario
methodDescriptor = taskStatusResourceModel.findMethod(ResourceMethod.ACTION);
taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
taskStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
return new BaseTask<Long>() {
protected Promise<Long> run(final Context context) throws Exception {
return Promises.value(1234l);
}
};
}
});
checkInvocation(taskStatusResource, methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
//Task Method Execution - Error scenario
taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
taskStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
return new BaseTask<Long>() {
protected Promise<Long> run(final Context context) throws Exception {
return Promises.error(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
}
};
}
});
checkInvocation(taskStatusResource, methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request passed unexpectedly.");
}
}, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
}
use of com.linkedin.restli.internal.server.util.RestLiSyntaxException in project rest.li by linkedin.
the class TestRestLiMethodInvocation method checkInvocation.
private void checkInvocation(Object resource, ResourceMethodDescriptor resourceMethodDescriptor, String httpMethod, ProtocolVersion version, String uri, String entityBody, MutablePathKeys pathkeys, final RequestExecutionCallback<RestResponse> callback, final boolean isDebugMode, final boolean expectRoutingException, final RestLiAttachmentReader expectedRequestAttachments, final RestLiResponseAttachments expectedResponseAttachments) throws URISyntaxException, RestLiSyntaxException {
assertNotNull(resource);
assertNotNull(resourceMethodDescriptor);
try {
EasyMock.replay(resource);
RestRequestBuilder builder = new RestRequestBuilder(new URI(uri)).setMethod(httpMethod).addHeaderValue("Accept", "application/json").setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString());
if (entityBody != null) {
builder.setEntity(entityBody.getBytes(Data.UTF_8_CHARSET));
}
RestRequest request = builder.build();
final ResourceContext resourceContext = new ResourceContextImpl(pathkeys, request, new RequestContext(), true, expectedRequestAttachments);
resourceContext.setResponseAttachments(expectedResponseAttachments);
RoutingResult routingResult = new RoutingResult(resourceContext, resourceMethodDescriptor);
FilterRequestContextInternal filterContext = new FilterRequestContextInternalImpl((ServerResourceContext) routingResult.getContext(), resourceMethodDescriptor);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch expectedRoutingExceptionLatch = new CountDownLatch(1);
RestLiArgumentBuilder adapter = _methodAdapterRegistry.getArgumentBuilder(resourceMethodDescriptor.getType());
RestLiRequestData requestData = adapter.extractRequestData(routingResult, request);
filterContext.setRequestData(requestData);
RestLiResponseHandler restLiResponseHandler = new RestLiResponseHandler.Builder().build();
RequestExecutionReportBuilder requestExecutionReportBuilder = null;
if (isDebugMode) {
requestExecutionReportBuilder = new RequestExecutionReportBuilder();
}
RequestExecutionCallback<RestResponse> executionCallback = new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
if (isDebugMode) {
Assert.assertNotNull(executionReport);
} else {
Assert.assertNull(executionReport);
}
if (e.getCause().getCause() instanceof RoutingException) {
expectedRoutingExceptionLatch.countDown();
}
if (callback != null) {
callback.onError(e, executionReport, null, null);
}
Assert.assertEquals(requestAttachmentReader, expectedRequestAttachments);
Assert.assertEquals(responseAttachments, expectedResponseAttachments);
latch.countDown();
}
@Override
public void onSuccess(final RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
if (isDebugMode) {
Assert.assertNotNull(executionReport);
} else {
Assert.assertNull(executionReport);
}
if (callback != null) {
callback.onSuccess(result, executionReport, null);
}
Assert.assertEquals(responseAttachments, expectedResponseAttachments);
latch.countDown();
}
};
FilterChainCallback filterChainCallback = new FilterChainCallbackImpl(routingResult, _invoker, adapter, requestExecutionReportBuilder, expectedRequestAttachments, restLiResponseHandler, executionCallback);
final RestLiCallback<Object> outerCallback = new RestLiCallback<Object>(filterContext, new RestLiFilterResponseContextFactory<Object>(request, routingResult, restLiResponseHandler), new RestLiFilterChain(null, filterChainCallback));
RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) routingResult.getContext());
filterContext.setRequestData(adapter.extractRequestData(routingResult, request));
_invoker.invoke(filterContext.getRequestData(), routingResult, adapter, outerCallback, requestExecutionReportBuilder);
try {
latch.await();
if (expectRoutingException) {
expectedRoutingExceptionLatch.await();
}
} catch (InterruptedException e) {
// Ignore
}
EasyMock.verify(resource);
Assert.assertEquals(((ServerResourceContext) routingResult.getContext()).getResponseMimeType(), "application/json");
} catch (RestLiSyntaxException e) {
throw new RoutingException("syntax exception", 400);
} finally {
EasyMock.reset(resource);
EasyMock.makeThreadSafe(resource, true);
}
}
use of com.linkedin.restli.internal.server.util.RestLiSyntaxException in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testExecutionReport.
@Test
public void testExecutionReport() throws RestLiSyntaxException, URISyntaxException {
Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, AsyncStatusCollectionResource.class, PromiseStatusCollectionResource.class, TaskStatusCollectionResource.class);
ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
ResourceModel asyncStatusResourceModel = resourceModelMap.get("/asyncstatuses");
ResourceModel promiseStatusResourceModel = resourceModelMap.get("/promisestatuses");
ResourceModel taskStatusResourceModel = resourceModelMap.get("/taskstatuses");
ResourceMethodDescriptor methodDescriptor;
StatusCollectionResource statusResource;
AsyncStatusCollectionResource asyncStatusResource;
PromiseStatusCollectionResource promiseStatusResource;
TaskStatusCollectionResource taskStatusResource;
// #1: Sync Method Execution
methodDescriptor = statusResourceModel.findMethod(ResourceMethod.GET);
statusResource = getMockResource(StatusCollectionResource.class);
EasyMock.expect(statusResource.get(eq(1L))).andReturn(null).once();
checkInvocation(statusResource, methodDescriptor, "GET", version, "/statuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
//A 404 is considered an error by rest.li
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.assertNull(executionReport.getParseqTrace(), "There should be no parseq trace!");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
}, true, false);
// #2: Callback based Async Method Execution
Capture<RequestExecutionReport> requestExecutionReportCapture = new Capture<RequestExecutionReport>();
RestLiCallback<?> callback = getCallback(requestExecutionReportCapture);
methodDescriptor = asyncStatusResourceModel.findMethod(ResourceMethod.GET);
asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
asyncStatusResource.get(eq(1L), EasyMock.<Callback<Status>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<Status> callback = (Callback<Status>) EasyMock.getCurrentArguments()[1];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(asyncStatusResource);
checkAsyncInvocation(asyncStatusResource, callback, methodDescriptor, "GET", version, "/asyncstatuses/1", null, buildPathKeys("statusID", 1L), true);
Assert.assertNull(requestExecutionReportCapture.getValue().getParseqTrace());
// #3: Promise based Async Method Execution
methodDescriptor = promiseStatusResourceModel.findMethod(ResourceMethod.GET);
promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
EasyMock.expect(promiseStatusResource.get(eq(1L))).andReturn(Promises.<Status>value(null)).once();
checkInvocation(promiseStatusResource, methodDescriptor, "GET", version, "/promisestatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
//A 404 is considered an error by rest.li
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.assertNotNull(executionReport.getParseqTrace(), "There should be a valid parseq trace!");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
}, true, false);
// #4: Task based Async Method Execution
methodDescriptor = taskStatusResourceModel.findMethod(ResourceMethod.GET);
taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
EasyMock.expect(taskStatusResource.get(eq(1L))).andReturn(Task.callable("myTask", new Callable<Status>() {
@Override
public Status call() throws Exception {
return new Status();
}
})).once();
checkInvocation(taskStatusResource, methodDescriptor, "GET", version, "/taskstatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Request failed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.assertNotNull(executionReport.getParseqTrace());
}
}, true, false);
}
use of com.linkedin.restli.internal.server.util.RestLiSyntaxException in project rest.li by linkedin.
the class RestLiRouter method process.
/**
* Processes provided {@link RestRequest}.
*
* @param req {@link RestRequest}
* @return {@link RoutingResult}
*/
public RoutingResult process(final RestRequest req, final RequestContext requestContext, final RestLiAttachmentReader attachmentReader) {
String path = req.getURI().getRawPath();
if (path.length() < 2) {
throw new RoutingException(HttpStatus.S_404_NOT_FOUND.getCode());
}
if (path.charAt(0) == '/') {
path = path.substring(1);
}
Queue<String> remainingPath = new LinkedList<String>(Arrays.asList(SLASH_PATTERN.split(path)));
String rootPath = "/" + remainingPath.poll();
ResourceModel currentResource;
try {
currentResource = _pathRootResourceMap.get(URLDecoder.decode(rootPath, RestConstants.DEFAULT_CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
throw new RestLiInternalException("UnsupportedEncodingException while trying to decode the root path", e);
}
if (currentResource == null) {
throw new RoutingException(String.format("No root resource defined for path '%s'", rootPath), HttpStatus.S_404_NOT_FOUND.getCode());
}
ServerResourceContext context;
try {
final String acceptTypeHeader = req.getHeader(RestConstants.HEADER_ACCEPT);
boolean responseAttachmentsAllowed = false;
if (acceptTypeHeader != null) {
final List<String> acceptTypes = MIMEParse.parseAcceptType(acceptTypeHeader);
for (final String acceptType : acceptTypes) {
if (acceptType.equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
responseAttachmentsAllowed = true;
}
}
}
context = new ResourceContextImpl(new PathKeysImpl(), req, requestContext, responseAttachmentsAllowed, attachmentReader);
} catch (RestLiSyntaxException e) {
throw new RoutingException(e.getMessage(), HttpStatus.S_400_BAD_REQUEST.getCode());
}
return processResourceTree(currentResource, context, remainingPath);
}
use of com.linkedin.restli.internal.server.util.RestLiSyntaxException in project rest.li by linkedin.
the class ExampleRequestResponseGenerator method buildResponse.
private RestResponse buildResponse(Object responseEntity, ResourceMethodDescriptor method, RestRequest restRequest) {
try {
ServerResourceContext context = new ResourceContextImpl();
RestUtils.validateRequestHeadersAndUpdateResourceContext(Collections.<String, String>emptyMap(), context);
method.setResourceModel(_resourceModel);
final RoutingResult routingResult = new RoutingResult(context, method);
return _responseHandler.buildResponse(restRequest, routingResult, responseEntity);
} catch (RestLiSyntaxException e) {
throw new ExampleGenerationException("Internal error during example generation", e);
} catch (IOException e) {
throw new ExampleGenerationException("Unable to build example response", e);
}
}
Aggregations