Search in sources :

Example 1 with RestLiRequestData

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);
}
Also used : RestLiRequestData(com.linkedin.restli.server.RestLiRequestData)

Example 2 with RestLiRequestData

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);
}
Also used : RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RestLiDataValidator(com.linkedin.restli.common.validation.RestLiDataValidator) RecordTemplate(com.linkedin.data.template.RecordTemplate) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) PatchRequest(com.linkedin.restli.common.PatchRequest) ResourceMethod(com.linkedin.restli.common.ResourceMethod) RestLiRequestData(com.linkedin.restli.server.RestLiRequestData)

Example 3 with RestLiRequestData

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);
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RoutingException(com.linkedin.restli.server.RoutingException) RestRequest(com.linkedin.r2.message.rest.RestRequest) ResourceContext(com.linkedin.restli.server.ResourceContext) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) RestLiRequestData(com.linkedin.restli.server.RestLiRequestData) Test(org.testng.annotations.Test)

Example 4 with RestLiRequestData

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);
}
Also used : RestLiMethodInvoker(com.linkedin.restli.internal.server.RestLiMethodInvoker) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) EngineBuilder(com.linkedin.parseq.EngineBuilder) RestLiArgumentBuilder(com.linkedin.restli.internal.server.methods.arguments.RestLiArgumentBuilder) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ErrorResponseBuilder(com.linkedin.restli.internal.server.response.ErrorResponseBuilder) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ByteString(com.linkedin.data.ByteString) CustomString(com.linkedin.restli.server.custom.types.CustomString) URI(java.net.URI) RestLiFilterChain(com.linkedin.restli.internal.server.filter.RestLiFilterChain) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RestLiResponseHandler(com.linkedin.restli.internal.server.response.RestLiResponseHandler) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) TaskStatusCollectionResource(com.linkedin.restli.server.twitter.TaskStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) CustomStatusCollectionResource(com.linkedin.restli.server.twitter.CustomStatusCollectionResource) PromiseStatusCollectionResource(com.linkedin.restli.server.twitter.PromiseStatusCollectionResource) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) ErrorResponseBuilder(com.linkedin.restli.internal.server.response.ErrorResponseBuilder) RestLiResponseData(com.linkedin.restli.server.RestLiResponseData) RestLiArgumentBuilder(com.linkedin.restli.internal.server.methods.arguments.RestLiArgumentBuilder) 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) IAnswer(org.easymock.IAnswer) FilterRequestContextInternal(com.linkedin.restli.internal.server.filter.FilterRequestContextInternal) RestRequest(com.linkedin.r2.message.rest.RestRequest) Filter(com.linkedin.restli.server.filter.Filter) CustomLong(com.linkedin.restli.server.custom.types.CustomLong) EasyMock.anyObject(org.easymock.EasyMock.anyObject) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) RestLiRequestData(com.linkedin.restli.server.RestLiRequestData) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 5 with RestLiRequestData

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);
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RestRequest(com.linkedin.r2.message.rest.RestRequest) ResourceContext(com.linkedin.restli.server.ResourceContext) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) RestLiRequestData(com.linkedin.restli.server.RestLiRequestData) Test(org.testng.annotations.Test)

Aggregations

RestLiRequestData (com.linkedin.restli.server.RestLiRequestData)27 RestRequest (com.linkedin.r2.message.rest.RestRequest)24 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)24 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)22 Test (org.testng.annotations.Test)22 ResourceContext (com.linkedin.restli.server.ResourceContext)20 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)11 Parameter (com.linkedin.restli.internal.server.model.Parameter)10 MyComplexKey (com.linkedin.restli.common.test.MyComplexKey)9 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)9 AnnotationSet (com.linkedin.restli.internal.server.model.AnnotationSet)8 RoutingException (com.linkedin.restli.server.RoutingException)7 Annotation (java.lang.annotation.Annotation)6 ComplexResourceKey (com.linkedin.restli.common.ComplexResourceKey)4 CompoundKey (com.linkedin.restli.common.CompoundKey)4 Key (com.linkedin.restli.server.Key)4 HashSet (java.util.HashSet)4 IntegerDataSchema (com.linkedin.data.schema.IntegerDataSchema)3 RequestContext (com.linkedin.r2.message.RequestContext)3 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)3