use of com.linkedin.restli.server.RestLiRequestData in project rest.li by linkedin.
the class RestLiServerUtils method updateFilterRequestContext.
/**
* Updates the filter request context with the request data
*
* @param filterContext
* {@link FilterRequestContextInternal}
* @param adapter
* {@link RestLiArgumentBuilder}
* @param request
* {@link RestRequest}
* @param method
* {@link RoutingResult}
*/
public static void updateFilterRequestContext(FilterRequestContextInternal filterContext, RestLiArgumentBuilder adapter, RestRequest request, RoutingResult method) {
RestLiRequestData requestData = adapter.extractRequestData(method, request);
filterContext.setRequestData(requestData);
}
use of com.linkedin.restli.server.RestLiRequestData in project rest.li by linkedin.
the class RestLiValidationFilter method onRequest.
@Override
public CompletableFuture<Void> onRequest(final FilterRequestContext requestContext) {
Class<?> resourceClass = requestContext.getFilterResourceModel().getResourceClass();
ResourceMethod method = requestContext.getMethodType();
RestLiDataValidator validator = new RestLiDataValidator(resourceClass.getAnnotations(), requestContext.getFilterResourceModel().getValueClass(), method);
RestLiRequestData requestData = requestContext.getRequestData();
if (method == ResourceMethod.CREATE || method == ResourceMethod.UPDATE) {
ValidationResult result = validator.validateInput(requestData.getEntity());
if (!result.isValid()) {
throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, result.getMessages().toString());
}
} else if (method == ResourceMethod.PARTIAL_UPDATE) {
ValidationResult result = validator.validateInput((PatchRequest) requestData.getEntity());
if (!result.isValid()) {
throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, result.getMessages().toString());
}
} else if (method == ResourceMethod.BATCH_CREATE) {
StringBuilder sb = new StringBuilder();
for (RecordTemplate entity : requestData.getBatchEntities()) {
ValidationResult result = validator.validateInput(entity);
if (!result.isValid()) {
sb.append(result.getMessages().toString());
}
}
if (sb.length() > 0) {
throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, sb.toString());
}
} else if (method == ResourceMethod.BATCH_UPDATE || method == ResourceMethod.BATCH_PARTIAL_UPDATE) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ? extends RecordTemplate> entry : requestData.getBatchKeyEntityMap().entrySet()) {
ValidationResult result;
if (method == ResourceMethod.BATCH_UPDATE) {
result = validator.validateInput(entry.getValue());
} else {
result = validator.validateInput((PatchRequest) entry.getValue());
}
if (!result.isValid()) {
sb.append("Key: ");
sb.append(entry.getKey());
sb.append(", ");
sb.append(result.getMessages().toString());
}
}
if (sb.length() > 0) {
throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, sb.toString());
}
}
return CompletableFuture.completedFuture(null);
}
use of com.linkedin.restli.server.RestLiRequestData in project rest.li by linkedin.
the class TestActionArgumentBuilder method testBuildArgumentsFailure.
@Test
public void testBuildArgumentsFailure() {
String entity = "{\"param2\":5678}";
RestRequest request = RestLiArgumentBuilderTestHelper.getMockRequest(false, entity, 3);
ResourceMethodDescriptor descriptor = RestLiArgumentBuilderTestHelper.getMockResourceMethodDescriptor(null, getStringAndIntParams(), null, null);
ResourceContext context = RestLiArgumentBuilderTestHelper.getMockResourceContext(null, null, null, false);
RoutingResult routingResult = RestLiArgumentBuilderTestHelper.getMockRoutingResult(descriptor, 2, context, 1);
RestLiArgumentBuilder argumentBuilder = new ActionArgumentBuilder();
RestLiRequestData requestData = argumentBuilder.extractRequestData(routingResult, request);
try {
argumentBuilder.buildArguments(requestData, routingResult);
fail("Expected RoutingException");
} catch (RoutingException e) {
assertEquals(e.getMessage(), "Parameter 'param1' is required");
}
verify(request, descriptor, routingResult);
}
use of com.linkedin.restli.server.RestLiRequestData in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testInvokerWithFilters.
@Test(dataProvider = "provideFilterConfig")
public void testInvokerWithFilters(final boolean throwExceptionFromFirstFilter) throws Exception {
RestLiArgumentBuilder mockBuilder = createMock(RestLiArgumentBuilder.class);
Filter mockFilter = createMock(Filter.class);
@SuppressWarnings("unchecked") RequestExecutionCallback<Object> mockCallback = createMock(RequestExecutionCallback.class);
FilterRequestContextInternal mockFilterContext = createMock(FilterRequestContextInternal.class);
RestLiRequestData requestData = new RestLiRequestDataImpl.Builder().key("Key").build();
RestLiMethodInvoker invokerWithFilters = new RestLiMethodInvoker(_resourceFactory, _engine, new ErrorResponseBuilder());
Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, LocationResource.class, DiscoveredItemsResource.class);
ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
ResourceMethodDescriptor resourceMethodDescriptor = statusResourceModel.findMethod(ResourceMethod.GET);
final StatusCollectionResource resource = getMockResource(StatusCollectionResource.class);
RestRequestBuilder builder = new RestRequestBuilder(new URI("/statuses/1")).setMethod("GET").addHeaderValue("Accept", "application/json").setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.LATEST_PROTOCOL_VERSION.toString());
RestRequest request = builder.build();
RoutingResult routingResult = new RoutingResult(new ResourceContextImpl(buildPathKeys("statusID", 1L), request, new RequestContext()), resourceMethodDescriptor);
mockFilterContext.setRequestData(requestData);
expectLastCall();
expect(mockBuilder.extractRequestData(routingResult, request)).andReturn(requestData);
FilterChainCallback filterChainCallback = new FilterChainCallback() {
@Override
public void onRequestSuccess(RestLiRequestData requestData, RestLiCallback<Object> restLiCallback) {
// only invoke if filter chain's requests were successful
invokerWithFilters.invoke(requestData, routingResult, mockBuilder, restLiCallback, null);
}
@Override
public void onResponseSuccess(RestLiResponseData responseData, RestLiResponseAttachments responseAttachments) {
// unused
}
@Override
public void onError(Throwable th, RestLiResponseData responseData, RestLiResponseAttachments responseAttachments) {
// unused
}
};
final Exception exFromFilter = new RuntimeException("Exception from filter!");
if (throwExceptionFromFirstFilter) {
mockFilter.onRequest(eq(mockFilterContext));
expectLastCall().andThrow(exFromFilter);
mockCallback.onError(eq(exFromFilter), anyObject(RequestExecutionReport.class), EasyMock.isNull(RestLiAttachmentReader.class), EasyMock.isNull(RestLiResponseAttachments.class));
} else {
expect(mockFilterContext.getRequestData()).andReturn(requestData).times(3);
mockFilter.onRequest(eq(mockFilterContext));
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
FilterRequestContext filterContext = (FilterRequestContext) getCurrentArguments()[0];
RestLiRequestData data = filterContext.getRequestData();
// Verify incoming data.
assertEquals(data.getKey(), "Key");
// Update data.
data.setKey("Key-Filter1");
return CompletableFuture.completedFuture(null);
}
}).andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
FilterRequestContext filterContext = (FilterRequestContext) getCurrentArguments()[0];
RestLiRequestData data = filterContext.getRequestData();
// Verify incoming data.
assertEquals(data.getKey(), "Key-Filter1");
// Update data.
data.setKey("Key-Filter2");
return CompletableFuture.completedFuture(null);
}
});
Long[] argsArray = { 1L };
expect(mockBuilder.buildArguments(requestData, routingResult)).andReturn(argsArray);
expect(resource.get(eq(1L))).andReturn(null).once();
mockCallback.onSuccess(eq(null), anyObject(RequestExecutionReport.class), anyObject(RestLiResponseAttachments.class));
}
replay(resource, mockBuilder, mockFilterContext, mockFilter, mockCallback);
RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) routingResult.getContext());
mockFilterContext.setRequestData(mockBuilder.extractRequestData(routingResult, request));
RestLiFilterChain filterChain = new RestLiFilterChain(Arrays.asList(mockFilter, mockFilter), filterChainCallback);
filterChain.onRequest(mockFilterContext, new RestLiFilterResponseContextFactory<Object>(request, routingResult, new RestLiResponseHandler.Builder().build()));
verify(mockBuilder, mockFilterContext, mockFilter);
if (throwExceptionFromFirstFilter) {
assertEquals(requestData.getKey(), "Key");
} else {
assertEquals(requestData.getKey(), "Key-Filter2");
verify(resource);
}
EasyMock.reset(resource);
EasyMock.makeThreadSafe(resource, true);
}
use of com.linkedin.restli.server.RestLiRequestData in project rest.li by linkedin.
the class TestActionArgumentBuilder method testArgumentBuilderSuccess.
@Test(dataProvider = "successData")
public void testArgumentBuilderSuccess(String entity, List<Parameter<?>> params, Object[] expectedArgs) {
RestRequest request = RestLiArgumentBuilderTestHelper.getMockRequest(false, entity, 3);
ResourceMethodDescriptor descriptor = RestLiArgumentBuilderTestHelper.getMockResourceMethodDescriptor(null, params, null, null);
ResourceContext context = RestLiArgumentBuilderTestHelper.getMockResourceContext(null, null, null, true);
RoutingResult routingResult = RestLiArgumentBuilderTestHelper.getMockRoutingResult(descriptor, 2, context, 1);
RestLiArgumentBuilder argumentBuilder = new ActionArgumentBuilder();
RestLiRequestData requestData = argumentBuilder.extractRequestData(routingResult, request);
Object[] args = argumentBuilder.buildArguments(requestData, routingResult);
assertEquals(args, expectedArgs);
verify(request, descriptor, routingResult);
}
Aggregations