Search in sources :

Example 1 with CreateIdEntityStatus

use of com.linkedin.restli.common.CreateIdEntityStatus in project rest.li by linkedin.

the class BatchCreateResponseBuilder method buildRestLiResponseData.

@Override
public RestLiResponseData buildRestLiResponseData(RestRequest request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    if (result instanceof BatchCreateKVResult) {
        BatchCreateKVResult<?, ?> list = (BatchCreateKVResult<?, ?>) result;
        if (list.getResults() == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null List inside of a BatchCreateKVResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> collectionCreateList = new ArrayList<BatchCreateResponseEnvelope.CollectionCreateResponseItem>(list.getResults().size());
        for (CreateKVResponse e : list.getResults()) {
            if (e == null) {
                throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null element inside of List inside of a BatchCreateResult returned by the resource method: " + routingResult.getResourceMethod());
            } else {
                Object id = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(e.getId(), routingResult);
                if (e.getError() == null) {
                    final ResourceContext resourceContext = routingResult.getContext();
                    DataMap entityData = e.getEntity() != null ? e.getEntity().data() : null;
                    final DataMap data = RestUtils.projectFields(entityData, resourceContext.getProjectionMode(), resourceContext.getProjectionMask());
                    CreateIdEntityStatus<Object, RecordTemplate> entry = new CreateIdEntityStatus<Object, RecordTemplate>(e.getStatus().getCode(), id, new AnyRecord(data), null, ProtocolVersionUtil.extractProtocolVersion(headers));
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(entry));
                } else {
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(e.getError(), id));
                }
            }
        }
        RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, headers, cookies);
        responseData.setResponseEnvelope(new BatchCreateResponseEnvelope(collectionCreateList, true, responseData));
        return responseData;
    } else {
        BatchCreateResult<?, ?> list = (BatchCreateResult<?, ?>) result;
        //Verify that a null list was not passed into the BatchCreateResult. If so, this is a developer error.
        if (list.getResults() == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null List inside of a BatchCreateResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> collectionCreateList = new ArrayList<BatchCreateResponseEnvelope.CollectionCreateResponseItem>(list.getResults().size());
        for (CreateResponse e : list.getResults()) {
            //Verify that a null element was not passed into the BatchCreateResult list. If so, this is a developer error.
            if (e == null) {
                throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null element inside of List inside of a BatchCreateResult returned by the resource method: " + routingResult.getResourceMethod());
            } else {
                Object id = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(e.getId(), routingResult);
                if (e.getError() == null) {
                    CreateIdStatus<Object> entry = new CreateIdStatus<Object>(e.getStatus().getCode(), id, null, ProtocolVersionUtil.extractProtocolVersion(headers));
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(entry));
                } else {
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(e.getError(), id));
                }
            }
        }
        RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, headers, cookies);
        responseData.setResponseEnvelope(new BatchCreateResponseEnvelope(collectionCreateList, responseData));
        return responseData;
    }
}
Also used : ResourceContext(com.linkedin.restli.server.ResourceContext) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) CreateResponse(com.linkedin.restli.server.CreateResponse) ArrayList(java.util.ArrayList) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) DataMap(com.linkedin.data.DataMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) BatchCreateResult(com.linkedin.restli.server.BatchCreateResult) BatchCreateKVResult(com.linkedin.restli.server.BatchCreateKVResult) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse)

Example 2 with CreateIdEntityStatus

use of com.linkedin.restli.common.CreateIdEntityStatus in project rest.li by linkedin.

the class CreateIdEntityStatusDecoder method makeValue.

@SuppressWarnings("unchecked")
@Override
public CreateIdEntityStatus<K, V> makeValue(DataMap dataMap) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    CreateIdStatus<K> idStatus = super.makeValue(dataMap);
    K key = idStatus.getKey();
    DataMap finalMap = new DataMap(idStatus.data());
    DataList listElements = new DataList();
    V entity = null;
    if (dataMap.get("error") == null && dataMap.get("entity") != null) {
        entity = _valueType.getType().getConstructor(DataMap.class).newInstance(dataMap.get("entity"));
        CheckedUtil.addWithoutChecking(listElements, entity.data());
    }
    finalMap.put("entity", listElements);
    return new CreateIdEntityStatus<>(finalMap, key, entity);
}
Also used : DataList(com.linkedin.data.DataList) CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) DataMap(com.linkedin.data.DataMap)

Example 3 with CreateIdEntityStatus

use of com.linkedin.restli.common.CreateIdEntityStatus in project rest.li by linkedin.

the class TestBatchCreateResponseBuilder method testProjectionInBuildRestLiResponseData.

@Test
@SuppressWarnings("unchecked")
public void testProjectionInBuildRestLiResponseData() throws URISyntaxException {
    MaskTree maskTree = new MaskTree();
    maskTree.addOperation(new PathSpec("fruitsField"), MaskOperation.POSITIVE_MASK_OP);
    ServerResourceContext mockContext = EasyMock.createMock(ServerResourceContext.class);
    EasyMock.expect(mockContext.hasParameter(RestConstants.ALT_KEY_PARAM)).andReturn(false).atLeastOnce();
    EasyMock.expect(mockContext.isReturnEntityRequested()).andReturn(true);
    EasyMock.expect(mockContext.getProjectionMode()).andReturn(ProjectionMode.AUTOMATIC);
    EasyMock.expect(mockContext.getProjectionMask()).andReturn(maskTree);
    EasyMock.expect(mockContext.getRawRequestContext()).andReturn(new RequestContext()).anyTimes();
    EasyMock.expect(mockContext.getAlwaysProjectedFields()).andReturn(Collections.emptySet()).anyTimes();
    EasyMock.replay(mockContext);
    ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(null);
    RoutingResult routingResult = new RoutingResult(mockContext, mockDescriptor);
    List<CreateKVResponse<Long, Foo>> createKVResponses = new ArrayList<>();
    Foo foo = new Foo();
    foo.setStringField("foo1");
    foo.setFruitsField(Fruits.APPLE);
    createKVResponses.add(new CreateKVResponse<>(1L, foo));
    BatchCreateKVResult<Long, Foo> results = new BatchCreateKVResult<>(createKVResponses);
    BatchCreateResponseBuilder responseBuilder = new BatchCreateResponseBuilder(new ErrorResponseBuilder());
    RestRequest request = new RestRequestBuilder(new URI("/foo")).build();
    RestLiResponseData<BatchCreateResponseEnvelope> responseData = responseBuilder.buildRestLiResponseData(request, routingResult, results, Collections.emptyMap(), Collections.emptyList());
    Assert.assertTrue(responseData.getResponseEnvelope().isGetAfterCreate());
    CreateIdEntityStatus<Long, Foo> item = (CreateIdEntityStatus<Long, Foo>) responseData.getResponseEnvelope().getCreateResponses().get(0).getRecord();
    Assert.assertEquals(item.getLocation(), "/foo/1");
    DataMap dataMap = item.data().getDataMap("entity");
    Assert.assertEquals(dataMap.size(), 1);
    Assert.assertEquals(dataMap.get("fruitsField"), Fruits.APPLE.toString());
    EasyMock.verify(mockContext);
}
Also used : CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) Foo(com.linkedin.pegasus.generator.examples.Foo) ArrayList(java.util.ArrayList) PathSpec(com.linkedin.data.schema.PathSpec) URI(java.net.URI) DataMap(com.linkedin.data.DataMap) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RestRequest(com.linkedin.r2.message.rest.RestRequest) MaskTree(com.linkedin.data.transform.filter.request.MaskTree) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) BatchCreateKVResult(com.linkedin.restli.server.BatchCreateKVResult) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse) Test(org.testng.annotations.Test)

Example 4 with CreateIdEntityStatus

use of com.linkedin.restli.common.CreateIdEntityStatus in project rest.li by linkedin.

the class BatchCreateResponseBuilder method buildRestLiResponseData.

/**
 * {@inheritDoc}
 *
 * @param result The result for a Rest.li BATCH_CREATE method. It's an instance of {@link BatchCreateResult}, if the
 *               BATCH_CREATE method doesn't return the entity; or an instance of {@link BatchCreateKVResult}, if it
 *               does.
 */
@Override
public RestLiResponseData<BatchCreateResponseEnvelope> buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    Object altKey = null;
    if (routingResult.getContext().hasParameter(RestConstants.ALT_KEY_PARAM)) {
        altKey = routingResult.getContext().getParameter(RestConstants.ALT_KEY_PARAM);
    }
    final ProtocolVersion protocolVersion = ProtocolVersionUtil.extractProtocolVersion(headers);
    final ResourceContext resourceContext = routingResult.getContext();
    if (result instanceof BatchCreateKVResult && resourceContext.isReturnEntityRequested()) {
        BatchCreateKVResult<?, ?> list = (BatchCreateKVResult<?, ?>) result;
        if (list.getResults() == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null List inside of a BatchCreateKVResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> collectionCreateList = new ArrayList<>(list.getResults().size());
        TimingContextUtil.beginTiming(routingResult.getContext().getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
        for (CreateKVResponse<?, ?> createKVResponse : list.getResults()) {
            if (createKVResponse == null) {
                throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null element inside of List inside of a BatchCreateKVResult returned by the resource method: " + routingResult.getResourceMethod());
            } else {
                Object id = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(createKVResponse.getId(), routingResult);
                if (createKVResponse.getError() == null) {
                    DataMap entityData = createKVResponse.getEntity() != null ? createKVResponse.getEntity().data() : null;
                    final DataMap data = RestUtils.projectFields(entityData, resourceContext);
                    CreateIdEntityStatus<Object, RecordTemplate> entry = new CreateIdEntityStatus<>(createKVResponse.getStatus().getCode(), id, new AnyRecord(data), // location uri
                    getLocationUri(request, id, altKey, protocolVersion), null, protocolVersion);
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(entry));
                } else {
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(createKVResponse.getError()));
                }
            }
        }
        TimingContextUtil.endTiming(routingResult.getContext().getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
        return new RestLiResponseDataImpl<>(new BatchCreateResponseEnvelope(HttpStatus.S_200_OK, collectionCreateList, true), headers, cookies);
    } else {
        List<? extends CreateResponse> createResponses = extractCreateResponseList(result);
        // Verify that a null list was not passed into the BatchCreateResult. If so, this is a developer error.
        if (createResponses == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null List inside of a BatchCreateResult returned by the resource method: " + routingResult.getResourceMethod());
        }
        List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> collectionCreateList = new ArrayList<>(createResponses.size());
        for (CreateResponse createResponse : createResponses) {
            // Verify that a null element was not passed into the BatchCreateResult list. If so, this is a developer error.
            if (createResponse == null) {
                throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null element inside of List inside of a BatchCreateResult returned by the resource method: " + routingResult.getResourceMethod());
            } else {
                Object id = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(createResponse.getId(), routingResult);
                if (createResponse.getError() == null) {
                    CreateIdStatus<Object> entry = new CreateIdStatus<>(createResponse.getStatus().getCode(), id, // location uri
                    getLocationUri(request, id, altKey, protocolVersion), null, protocolVersion);
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(entry));
                } else {
                    collectionCreateList.add(new BatchCreateResponseEnvelope.CollectionCreateResponseItem(createResponse.getError()));
                }
            }
        }
        return new RestLiResponseDataImpl<>(new BatchCreateResponseEnvelope(HttpStatus.S_200_OK, collectionCreateList, false), headers, cookies);
    }
}
Also used : ResourceContext(com.linkedin.restli.server.ResourceContext) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) CreateResponse(com.linkedin.restli.server.CreateResponse) ArrayList(java.util.ArrayList) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) DataMap(com.linkedin.data.DataMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) BatchCreateKVResult(com.linkedin.restli.server.BatchCreateKVResult)

Example 5 with CreateIdEntityStatus

use of com.linkedin.restli.common.CreateIdEntityStatus in project rest.li by linkedin.

the class TestParseqBasedFluentClientApiWithProjections method testBatchCreateAndGetWithProjection.

@Test
public void testBatchCreateAndGetWithProjection() throws Exception {
    CreateGreeting greetings = new CreateGreetingFluentClient(_parSeqRestliClient, _parSeqUnitTestHelper.getEngine());
    String msg1 = Double.toString(Math.random());
    String msg2 = Double.toString(Math.random());
    CompletionStage<List<CreateIdEntityStatus<Long, Greeting>>> result = greetings.batchCreateAndGet(Arrays.asList(getGreeting(msg1), getGreeting(msg2)), optionalParams -> optionalParams.withMask(mask -> mask.withId()));
    CompletableFuture<List<CreateIdEntityStatus<Long, Greeting>>> future = result.toCompletableFuture();
    List<CreateIdEntityStatus<Long, Greeting>> entities = future.get(5000, TimeUnit.MILLISECONDS);
    Assert.assertEquals(entities.size(), 2);
    Assert.assertNotNull(entities.get(0).getEntity());
    Assert.assertFalse(entities.get(0).getEntity().hasMessage());
    Assert.assertTrue(entities.get(0).getEntity().hasId());
    Assert.assertNotNull(entities.get(1).getEntity());
    Assert.assertFalse(entities.get(1).getEntity().hasMessage());
    Assert.assertTrue(entities.get(1).getEntity().hasId());
}
Also used : PagingMetadataProjections(com.linkedin.restli.examples.greetings.client.PagingMetadataProjections) Arrays(java.util.Arrays) RestLiValidationFilter(com.linkedin.restli.server.validation.RestLiValidationFilter) CollectionResponse(com.linkedin.restli.common.CollectionResponse) AutoValidationWithProjectionFluentClient(com.linkedin.restli.examples.greetings.client.AutoValidationWithProjectionFluentClient) Test(org.testng.annotations.Test) PatchGenerator(com.linkedin.restli.client.util.PatchGenerator) EntityResponse(com.linkedin.restli.common.EntityResponse) Map(java.util.Map) CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) BatchfindersFluentClient(com.linkedin.restli.examples.greetings.client.BatchfindersFluentClient) ManualProjections(com.linkedin.restli.examples.greetings.client.ManualProjections) Greetings(com.linkedin.restli.examples.greetings.client.Greetings) BeforeClass(org.testng.annotations.BeforeClass) Set(java.util.Set) ParSeqRestliClientConfigBuilder(com.linkedin.restli.client.ParSeqRestliClientConfigBuilder) CollectionMetadata(com.linkedin.restli.common.CollectionMetadata) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ParSeqRestliClientBuilder(com.linkedin.restli.client.ParSeqRestliClientBuilder) CreateGreeting(com.linkedin.restli.examples.greetings.client.CreateGreeting) AutoValidationWithProjection(com.linkedin.restli.examples.greetings.client.AutoValidationWithProjection) GreetingsFluentClient(com.linkedin.restli.examples.greetings.client.GreetingsFluentClient) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) com.linkedin.restli.examples.greetings.api.myRecord(com.linkedin.restli.examples.greetings.api.myRecord) PatchRequest(com.linkedin.restli.common.PatchRequest) Assert(org.testng.Assert) UpdateEntityStatus(com.linkedin.restli.common.UpdateEntityStatus) ManualProjectionsFluentClient(com.linkedin.restli.examples.greetings.client.ManualProjectionsFluentClient) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) ParSeqUnitTestHelper(com.linkedin.parseq.ParSeqUnitTestHelper) Tone(com.linkedin.restli.examples.greetings.api.Tone) PartialUpdateGreetingFluentClient(com.linkedin.restli.examples.greetings.client.PartialUpdateGreetingFluentClient) IdEntityResponse(com.linkedin.restli.common.IdEntityResponse) AfterClass(org.testng.annotations.AfterClass) ValidationDemo(com.linkedin.restli.examples.greetings.api.ValidationDemo) BatchFinderCriteriaResult(com.linkedin.restli.common.BatchFinderCriteriaResult) PartialUpdateGreeting(com.linkedin.restli.examples.greetings.client.PartialUpdateGreeting) GreetingCriteria(com.linkedin.restli.examples.greetings.api.GreetingCriteria) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CreateGreetingFluentClient(com.linkedin.restli.examples.greetings.client.CreateGreetingFluentClient) PagingMetadataProjectionsFluentClient(com.linkedin.restli.examples.greetings.client.PagingMetadataProjectionsFluentClient) ParSeqRestliClient(com.linkedin.restli.client.ParSeqRestliClient) BatchCollectionResponse(com.linkedin.restli.common.BatchCollectionResponse) com.linkedin.restli.examples.greetings.api.myItem(com.linkedin.restli.examples.greetings.api.myItem) Batchfinders(com.linkedin.restli.examples.greetings.client.Batchfinders) Sets(org.testng.collections.Sets) CreateGreeting(com.linkedin.restli.examples.greetings.client.CreateGreeting) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) PartialUpdateGreeting(com.linkedin.restli.examples.greetings.client.PartialUpdateGreeting) CreateGreetingFluentClient(com.linkedin.restli.examples.greetings.client.CreateGreetingFluentClient) CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) CreateGreeting(com.linkedin.restli.examples.greetings.client.CreateGreeting) List(java.util.List) Test(org.testng.annotations.Test)

Aggregations

CreateIdEntityStatus (com.linkedin.restli.common.CreateIdEntityStatus)10 ArrayList (java.util.ArrayList)7 Test (org.testng.annotations.Test)6 DataMap (com.linkedin.data.DataMap)4 Foo (com.linkedin.pegasus.generator.examples.Foo)4 CreateIdStatus (com.linkedin.restli.common.CreateIdStatus)4 RestRequest (com.linkedin.r2.message.rest.RestRequest)3 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)3 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)3 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)3 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)3 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)3 BatchCreateKVResult (com.linkedin.restli.server.BatchCreateKVResult)3 URI (java.net.URI)3 RecordTemplate (com.linkedin.data.template.RecordTemplate)2 RequestContext (com.linkedin.r2.message.RequestContext)2 CreateGreeting (com.linkedin.restli.examples.greetings.client.CreateGreeting)2 CreateGreetingFluentClient (com.linkedin.restli.examples.greetings.client.CreateGreetingFluentClient)2 PartialUpdateGreeting (com.linkedin.restli.examples.greetings.client.PartialUpdateGreeting)2 AnyRecord (com.linkedin.restli.internal.server.methods.AnyRecord)2