Search in sources :

Example 36 with UpdateResponse

use of com.linkedin.restli.server.UpdateResponse in project rest.li by linkedin.

the class BatchResponseBuilder method buildRestLiResponseData.

/**
 * {@inheritDoc}
 *
 * @param result The result of a Rest.li BATCH_UPDATE, BATCH_PARTIAL_UPDATE, or BATCH_DELETE method. It is a
 *               {@link BatchUpdateResult} object.
 */
@SuppressWarnings("unchecked")
@Override
public D buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    @SuppressWarnings({ "unchecked" }) final BatchUpdateResult<Object, ?> /* constrained by signature of {@link com.linkedin.restli.server.resources.CollectionResource#batchUpdate(java.util.Map)} */
    updateResult = (BatchUpdateResult<Object, ?>) result;
    final Map<Object, UpdateResponse> results = updateResult.getResults();
    // Verify the map is not null. If so, this is a developer error.
    if (results == null) {
        throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null Map found inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod());
    }
    final Map<Object, RestLiServiceException> serviceErrors = updateResult.getErrors();
    if (serviceErrors == null) {
        throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null errors Map found inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod());
    }
    TimingContextUtil.beginTiming(routingResult.getContext().getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
    Map<Object, BatchResponseEntry> batchResponseMap = new HashMap<>();
    for (Map.Entry<Object, UpdateResponse> entry : results.entrySet()) {
        if (entry.getKey() == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key inside of the Map returned inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        if (!serviceErrors.containsKey(entry.getKey())) {
            Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entry.getKey(), routingResult);
            UpdateStatus updateStatus = buildUpdateStatus(routingResult.getContext(), entry.getValue());
            batchResponseMap.put(finalKey, new BatchResponseEntry(entry.getValue().getStatus(), updateStatus));
        }
    }
    TimingContextUtil.endTiming(routingResult.getContext().getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
    for (Map.Entry<Object, RestLiServiceException> entry : serviceErrors.entrySet()) {
        if (entry.getKey() == null || entry.getValue() == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key or value inside of the Map returned inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entry.getKey(), routingResult);
        batchResponseMap.put(finalKey, new BatchResponseEntry(entry.getValue().getStatus(), entry.getValue()));
    }
    for (Map.Entry<Object, RestLiServiceException> entry : routingResult.getContext().getBatchKeyErrors().entrySet()) {
        Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entry.getKey(), routingResult);
        batchResponseMap.put(finalKey, new BatchResponseEntry(entry.getValue().getStatus(), entry.getValue()));
    }
    return buildResponseData(HttpStatus.S_200_OK, batchResponseMap, headers, cookies);
}
Also used : UpdateStatus(com.linkedin.restli.common.UpdateStatus) HashMap(java.util.HashMap) UpdateResponse(com.linkedin.restli.server.UpdateResponse) BatchResponseEntry(com.linkedin.restli.internal.server.response.BatchResponseEnvelope.BatchResponseEntry) BatchUpdateResult(com.linkedin.restli.server.BatchUpdateResult) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap) Map(java.util.Map)

Example 37 with UpdateResponse

use of com.linkedin.restli.server.UpdateResponse in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testAsyncDelete.

@Test
public void testAsyncDelete() throws Exception {
    Map<String, ResourceModel> resourceModelMap = buildResourceModels(AsyncStatusCollectionResource.class, AsyncLocationResource.class, AsyncDiscoveredItemsResource.class);
    ResourceModel statusResourceModel = resourceModelMap.get("/asyncstatuses");
    ResourceModel locationResourceModel = statusResourceModel.getSubResource("asynclocation");
    ResourceModel discoveredItemsResourceModel = resourceModelMap.get("/asyncdiscovereditems");
    RestLiCallback callback = getCallback();
    ResourceMethodDescriptor methodDescriptor;
    AsyncStatusCollectionResource statusResource;
    AsyncLocationResource locationResource;
    AsyncDiscoveredItemsResource discoveredItemsResource;
    // #1 Delete on collection resource
    methodDescriptor = statusResourceModel.findMethod(ResourceMethod.DELETE);
    statusResource = getMockResource(AsyncStatusCollectionResource.class);
    statusResource.delete(eq(1L), EasyMock.anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[1];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(statusResource);
    checkAsyncInvocation(statusResource, callback, methodDescriptor, "DELETE", version, "/asyncstatuses/1", buildPathKeys("statusID", 1L));
    // #2 Delete on simple resource
    methodDescriptor = locationResourceModel.findMethod(ResourceMethod.DELETE);
    locationResource = getMockResource(AsyncLocationResource.class);
    locationResource.delete(EasyMock.anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[0];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(locationResource);
    checkAsyncInvocation(locationResource, callback, methodDescriptor, "DELETE", version, "/asyncstatuses/1/asynclocation", buildPathKeys("statusID", 1L));
    // #3 Delete on complex-key resource
    methodDescriptor = discoveredItemsResourceModel.findMethod(ResourceMethod.DELETE);
    discoveredItemsResource = getMockResource(AsyncDiscoveredItemsResource.class);
    ComplexResourceKey<DiscoveredItemKey, DiscoveredItemKeyParams> key = getDiscoveredItemComplexKey(1L, 2, 3L);
    discoveredItemsResource.delete(eq(key), EasyMock.anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[1];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(discoveredItemsResource);
    checkAsyncInvocation(discoveredItemsResource, callback, methodDescriptor, "DELETE", version, "/asyncdiscovereditems/(itemId:1,type:2,userId:3)", buildPathKeys("asyncDiscoveredItemId", key));
}
Also used : AsyncLocationResource(com.linkedin.restli.server.twitter.AsyncLocationResource) AsyncDiscoveredItemsResource(com.linkedin.restli.server.twitter.AsyncDiscoveredItemsResource) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ByteString(com.linkedin.data.ByteString) CustomString(com.linkedin.restli.server.custom.types.CustomString) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) UpdateResponse(com.linkedin.restli.server.UpdateResponse) Callback(com.linkedin.common.callback.Callback) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) DiscoveredItemKeyParams(com.linkedin.restli.server.twitter.TwitterTestDataModels.DiscoveredItemKeyParams) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) DiscoveredItemKey(com.linkedin.restli.server.twitter.TwitterTestDataModels.DiscoveredItemKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 38 with UpdateResponse

use of com.linkedin.restli.server.UpdateResponse in project rest.li by linkedin.

the class TestRestLiResponseHandler method testBasicResponses.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "statusData")
public void testBasicResponses(AcceptTypeData acceptTypeData, String expectedStatus, ProtocolVersion protocolVersion, String errorResponseHeaderName, String idHeaderName) throws Exception {
    RestLiResponse response;
    // #1 simple record template
    response = invokeResponseHandler("/test", buildStatusRecord(), ResourceMethod.GET, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 200, 1, true, errorResponseHeaderName);
    if (acceptTypeData != AcceptTypeData.PSON && acceptTypeData != AcceptTypeData.PROTOBUF) {
        assertEquals(DataMapUtils.mapToByteString(response.getDataMap(), response.getHeaders()).asAvroString(), expectedStatus);
    }
    RestRequest req = buildRequest("/test", acceptTypeData.acceptHeaders, protocolVersion);
    RoutingResult routing = buildRoutingResult(ResourceMethod.GET, req, acceptTypeData.acceptHeaders);
    RestResponse restResponse = ResponseUtils.buildResponse(routing, response);
    assertEquals(restResponse.getEntity().asAvroString(), expectedStatus);
    // #2 create (with id)
    response = invokeResponseHandler("/test", new CreateResponse(1), ResourceMethod.CREATE, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 201, 3, false, errorResponseHeaderName);
    assertEquals(response.getHeader(RestConstants.HEADER_LOCATION), "/test/1");
    assertEquals(response.getHeader(idHeaderName), "1");
    // #2.1 create (without id)
    response = invokeResponseHandler("/test", new CreateResponse(HttpStatus.S_201_CREATED), ResourceMethod.CREATE, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 201, 1, false, errorResponseHeaderName);
    // #2.2 create (with id and slash at the end of uri)
    response = invokeResponseHandler("/test/", new CreateResponse(1), ResourceMethod.CREATE, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 201, 3, false, errorResponseHeaderName);
    assertEquals(response.getHeader(RestConstants.HEADER_LOCATION), "/test/1");
    assertEquals(response.getHeader(idHeaderName), "1");
    // #2.3 create (without id and slash at the end of uri)
    response = invokeResponseHandler("/test/", new CreateResponse(HttpStatus.S_201_CREATED), ResourceMethod.CREATE, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 201, 1, false, errorResponseHeaderName);
    // #3 update
    response = invokeResponseHandler("/test", new UpdateResponse(HttpStatus.S_204_NO_CONTENT), ResourceMethod.UPDATE, acceptTypeData.acceptHeaders, protocolVersion);
    checkResponse(response, 204, 1, false, errorResponseHeaderName);
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) UpdateResponse(com.linkedin.restli.server.UpdateResponse) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) CreateResponse(com.linkedin.restli.server.CreateResponse) RestLiResponse(com.linkedin.restli.internal.server.response.RestLiResponse) Test(org.testng.annotations.Test)

Example 39 with UpdateResponse

use of com.linkedin.restli.server.UpdateResponse in project rest.li by linkedin.

the class TestUpdateResponseBuilder method testBuilder.

@Test(dataProvider = "builderData")
public <D extends RestLiResponseData<? extends EmptyResponseEnvelope>> void testBuilder(ResourceMethod resourceMethod) {
    HttpStatus status = HttpStatus.S_200_OK;
    UpdateResponse updateResponse = new UpdateResponse(status);
    Map<String, String> headers = ResponseBuilderUtil.getHeaders();
    ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor();
    RoutingResult routingResult = new RoutingResult(null, mockDescriptor);
    @SuppressWarnings("unchecked") EmptyResponseBuilder<D> updateResponseBuilder = (EmptyResponseBuilder<D>) BUILDERS.get(resourceMethod);
    D responseData = updateResponseBuilder.buildRestLiResponseData(null, routingResult, updateResponse, headers, Collections.emptyList());
    RestLiResponse restLiResponse = updateResponseBuilder.buildResponse(routingResult, responseData);
    EasyMock.verify(mockDescriptor);
    Assert.assertEquals(responseData.getResourceMethod(), resourceMethod);
    Assert.assertEquals(responseData.getResponseEnvelope().getResourceMethod(), resourceMethod);
    ResponseBuilderUtil.validateHeaders(restLiResponse, headers);
    Assert.assertEquals(restLiResponse.getStatus(), status);
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) UpdateResponse(com.linkedin.restli.server.UpdateResponse) HttpStatus(com.linkedin.restli.common.HttpStatus) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) Test(org.testng.annotations.Test)

Example 40 with UpdateResponse

use of com.linkedin.restli.server.UpdateResponse in project rest.li by linkedin.

the class CustomKeyAssociationResource method batchUpdate.

@Override
public BatchUpdateResult<CompoundKey, SimpleGreeting> batchUpdate(BatchUpdateRequest<CompoundKey, SimpleGreeting> entities) {
    Set<CompoundKey> keys = entities.getData().keySet();
    Map<CompoundKey, UpdateResponse> responseMap = new HashMap<>();
    for (CompoundKey key : keys) {
        responseMap.put(key, new UpdateResponse(HttpStatus.S_201_CREATED));
    }
    return new BatchUpdateResult<>(responseMap);
}
Also used : UpdateResponse(com.linkedin.restli.server.UpdateResponse) BatchUpdateResult(com.linkedin.restli.server.BatchUpdateResult) CompoundKey(com.linkedin.restli.common.CompoundKey) HashMap(java.util.HashMap)

Aggregations

UpdateResponse (com.linkedin.restli.server.UpdateResponse)55 BatchUpdateResult (com.linkedin.restli.server.BatchUpdateResult)21 HashMap (java.util.HashMap)21 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)18 DataProcessingException (com.linkedin.data.transform.DataProcessingException)12 Map (java.util.Map)11 Test (org.testng.annotations.Test)11 CompoundKey (com.linkedin.restli.common.CompoundKey)9 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)6 HttpStatus (com.linkedin.restli.common.HttpStatus)5 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)5 ByteString (com.linkedin.data.ByteString)4 PatchRequest (com.linkedin.restli.common.PatchRequest)4 UpdateStatus (com.linkedin.restli.common.UpdateStatus)4 Photo (com.linkedin.restli.example.Photo)4 ValidationDemo (com.linkedin.restli.examples.greetings.api.ValidationDemo)4 BatchPatchRequest (com.linkedin.restli.server.BatchPatchRequest)4 Callback (com.linkedin.common.callback.Callback)3 DataMap (com.linkedin.data.DataMap)3 ComplexResourceKey (com.linkedin.restli.common.ComplexResourceKey)3