Search in sources :

Example 21 with AnyRecord

use of com.linkedin.restli.internal.server.methods.AnyRecord in project rest.li by linkedin.

the class CollectionResponseBuilder method buildResponse.

@Override
public RestLiResponse buildResponse(RoutingResult routingResult, D responseData) {
    CollectionResponseEnvelope response = responseData.getResponseEnvelope();
    RestLiResponse.Builder builder = new RestLiResponse.Builder();
    CollectionResponse<AnyRecord> collectionResponse = new CollectionResponse<>(AnyRecord.class);
    collectionResponse.setPaging(response.getCollectionResponsePaging());
    DataList elementsMap = (DataList) collectionResponse.data().get(CollectionResponse.ELEMENTS);
    for (RecordTemplate entry : response.getCollectionResponse()) {
        CheckedUtil.addWithoutChecking(elementsMap, entry.data());
    }
    if (response.getCollectionResponseCustomMetadata() != null) {
        collectionResponse.setMetadataRaw(response.getCollectionResponseCustomMetadata().data());
    }
    builder.entity(collectionResponse);
    return builder.headers(responseData.getHeaders()).cookies(responseData.getCookies()).build();
}
Also used : DataList(com.linkedin.data.DataList) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) CollectionResponse(com.linkedin.restli.common.CollectionResponse) RecordTemplate(com.linkedin.data.template.RecordTemplate)

Example 22 with AnyRecord

use of com.linkedin.restli.internal.server.methods.AnyRecord in project rest.li by linkedin.

the class GetResponseBuilder method buildRestLiResponseData.

/**
 * {@inheritDoc}
 *
 * @param result The result of a Rest.li GET method. It can be the entity itself, or the entity wrapped in a
 *               {@link GetResult}.
 */
@Override
public RestLiResponseData<GetResponseEnvelope> buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    final RecordTemplate record;
    final HttpStatus status;
    if (result instanceof GetResult) {
        final GetResult<?> getResult = (GetResult<?>) result;
        record = getResult.getValue();
        status = getResult.getStatus();
    } else {
        record = (RecordTemplate) result;
        status = HttpStatus.S_200_OK;
    }
    final ResourceContext resourceContext = routingResult.getContext();
    DataMap rawData = record.data();
    RecordDataSchema schema = record.schema();
    if (resourceContext.isFillInDefaultsRequested()) {
        rawData = (DataMap) ResponseUtils.fillInDataDefault(schema, rawData);
    }
    TimingContextUtil.beginTiming(resourceContext.getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
    final DataMap data = RestUtils.projectFields(rawData, resourceContext);
    TimingContextUtil.endTiming(resourceContext.getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
    return new RestLiResponseDataImpl<>(new GetResponseEnvelope(status, new AnyRecord(data)), headers, cookies);
}
Also used : ResourceContext(com.linkedin.restli.server.ResourceContext) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) GetResult(com.linkedin.restli.server.GetResult) HttpStatus(com.linkedin.restli.common.HttpStatus) RecordTemplate(com.linkedin.data.template.RecordTemplate) RecordDataSchema(com.linkedin.data.schema.RecordDataSchema) DataMap(com.linkedin.data.DataMap)

Example 23 with AnyRecord

use of com.linkedin.restli.internal.server.methods.AnyRecord in project rest.li by linkedin.

the class TestCreateResponseBuilder method testReturnEntityInBuildRestLiResponseData.

@Test(dataProvider = "returnEntityData")
public void testReturnEntityInBuildRestLiResponseData(CreateResponse createResponse, boolean isReturnEntityRequested, boolean expectEntityReturned) throws URISyntaxException {
    ServerResourceContext mockContext = EasyMock.createMock(ServerResourceContext.class);
    EasyMock.expect(mockContext.isReturnEntityRequested()).andReturn(isReturnEntityRequested);
    EasyMock.expect(mockContext.getProjectionMask()).andReturn(null);
    EasyMock.expect(mockContext.getProjectionMode()).andReturn(ProjectionMode.AUTOMATIC);
    EasyMock.expect(mockContext.getRawRequestContext()).andReturn(new RequestContext()).anyTimes();
    EasyMock.expect(mockContext.getAlwaysProjectedFields()).andReturn(Collections.emptySet()).anyTimes();
    EasyMock.replay(mockContext);
    RoutingResult routingResult = new RoutingResult(mockContext, null);
    CreateResponseBuilder responseBuilder = new CreateResponseBuilder();
    RestLiResponseData<CreateResponseEnvelope> envelope = responseBuilder.buildRestLiResponseData(new RestRequestBuilder(new URI("/foo")).build(), routingResult, createResponse, Collections.emptyMap(), Collections.emptyList());
    RecordTemplate record = envelope.getResponseEnvelope().getRecord();
    if (expectEntityReturned) {
        Assert.assertTrue(record instanceof AnyRecord, "Entity in response envelope should be of type AnyRecord.");
        Assert.assertEquals(record, ((CreateKVResponse) createResponse).getEntity(), "Entity in response envelope should match the original.");
        Assert.assertTrue(envelope.getResponseEnvelope().isGetAfterCreate(), "Response envelope should be get after create.");
    } else {
        Assert.assertTrue(record instanceof IdResponse, "Entity in response envelope should be of type IdResponse.");
        Assert.assertNull(((IdResponse) record).getId(), "IdResponse in response envelope should have same ID.");
    }
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) IdResponse(com.linkedin.restli.common.IdResponse) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RecordTemplate(com.linkedin.data.template.RecordTemplate) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) URI(java.net.URI) Test(org.testng.annotations.Test)

Example 24 with AnyRecord

use of com.linkedin.restli.internal.server.methods.AnyRecord in project rest.li by linkedin.

the class TestRestLiResponseEnvelope method testSetNewEnvelopeData.

@Test(dataProvider = "envelopeResourceMethodDataProvider")
public void testSetNewEnvelopeData(RestLiResponseEnvelope responseEnvelope, ResourceMethod resourceMethod) {
    // If response type is dynamically determined, directly cast to resource method response envelope
    if (ResponseTypeUtil.isDynamicallyDetermined(resourceMethod)) {
        switch(resourceMethod) {
            case PARTIAL_UPDATE:
                PartialUpdateResponseEnvelope partialUpdateResponseEnvelope = (PartialUpdateResponseEnvelope) responseEnvelope;
                RecordTemplate oldRecord = partialUpdateResponseEnvelope.getRecord();
                RecordTemplate newRecord = new AnyRecord(new DataMap());
                newRecord.data().put("test", "testing");
                partialUpdateResponseEnvelope.setRecord(newRecord, HttpStatus.S_200_OK);
                Assert.assertNotEquals(partialUpdateResponseEnvelope.getRecord(), oldRecord);
                break;
            default:
                throw new IllegalStateException();
        }
    } else // Otherwise, cast to response type response envelope
    {
        ResponseType responseType = ResponseTypeUtil.fromMethodType(resourceMethod);
        switch(responseType) {
            case SINGLE_ENTITY:
                RecordResponseEnvelope recordResponseEnvelope = (RecordResponseEnvelope) responseEnvelope;
                RecordTemplate oldRecord = recordResponseEnvelope.getRecord();
                RecordTemplate newRecord = new AnyRecord(new DataMap());
                newRecord.data().put("test", "testing");
                recordResponseEnvelope.setRecord(newRecord, HttpStatus.S_200_OK);
                Assert.assertNotEquals(recordResponseEnvelope.getRecord(), oldRecord);
                break;
            case GET_COLLECTION:
                CollectionResponseEnvelope collectionResponseEnvelope = (CollectionResponseEnvelope) responseEnvelope;
                List<? extends RecordTemplate> oldResponses = collectionResponseEnvelope.getCollectionResponse();
                RecordTemplate oldResponseMetadata = collectionResponseEnvelope.getCollectionResponseCustomMetadata();
                CollectionMetadata oldPagingMetadata = collectionResponseEnvelope.getCollectionResponsePaging();
                RecordTemplate newResponseMetadata = new AnyRecord(new DataMap());
                newResponseMetadata.data().put("test", "testing");
                CollectionMetadata newResponsesPaging = new CollectionMetadata();
                List<? extends RecordTemplate> newResponses = Arrays.asList(new AnyRecord(new DataMap()));
                collectionResponseEnvelope.setCollectionResponse(newResponses, newResponsesPaging, newResponseMetadata, HttpStatus.S_200_OK);
                Assert.assertNotEquals(collectionResponseEnvelope.getCollectionResponse(), oldResponses);
                Assert.assertNotEquals(collectionResponseEnvelope.getCollectionResponseCustomMetadata(), oldResponseMetadata);
                Assert.assertNotEquals(collectionResponseEnvelope.getCollectionResponsePaging(), oldPagingMetadata);
                Assert.assertEquals(collectionResponseEnvelope.getCollectionResponse(), newResponses);
                Assert.assertEquals(collectionResponseEnvelope.getCollectionResponseCustomMetadata(), newResponseMetadata);
                Assert.assertEquals(collectionResponseEnvelope.getCollectionResponsePaging(), newResponsesPaging);
                break;
            case CREATE_COLLECTION:
                BatchCreateResponseEnvelope batchCreateResponseEnvelope = (BatchCreateResponseEnvelope) responseEnvelope;
                List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> oldCreateResponses = batchCreateResponseEnvelope.getCreateResponses();
                CreateIdStatus<String> newCreateIdStatus = new CreateIdStatus<>(HttpStatus.S_201_CREATED.getCode(), "key", null, AllProtocolVersions.RESTLI_PROTOCOL_2_0_0.getProtocolVersion());
                RestLiServiceException newException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
                BatchCreateResponseEnvelope.CollectionCreateResponseItem successCreateItem = new BatchCreateResponseEnvelope.CollectionCreateResponseItem(newCreateIdStatus);
                BatchCreateResponseEnvelope.CollectionCreateResponseItem exceptionCreateItem = new BatchCreateResponseEnvelope.CollectionCreateResponseItem(newException);
                List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> newCreateResponses = Arrays.asList(successCreateItem, exceptionCreateItem);
                batchCreateResponseEnvelope.setCreateResponse(newCreateResponses, HttpStatus.S_200_OK);
                Assert.assertNotEquals(batchCreateResponseEnvelope.getCreateResponses(), oldCreateResponses);
                Assert.assertEquals(batchCreateResponseEnvelope.getCreateResponses(), newCreateResponses);
                BatchCreateResponseEnvelope.CollectionCreateResponseItem successItem = batchCreateResponseEnvelope.getCreateResponses().get(0);
                Assert.assertEquals(successItem.getRecord(), newCreateIdStatus);
                Assert.assertEquals(successItem.getId(), "key");
                Assert.assertFalse(successItem.isErrorResponse());
                Assert.assertNull(successItem.getException());
                Assert.assertEquals(successItem.getStatus(), HttpStatus.S_201_CREATED);
                BatchCreateResponseEnvelope.CollectionCreateResponseItem errorItem = batchCreateResponseEnvelope.getCreateResponses().get(1);
                Assert.assertNull(errorItem.getRecord());
                Assert.assertNull(errorItem.getId());
                Assert.assertTrue(errorItem.isErrorResponse());
                Assert.assertEquals(errorItem.getException(), newException);
                Assert.assertEquals(errorItem.getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
                break;
            case BATCH_ENTITIES:
                BatchResponseEnvelope batchResponseEnvelope = (BatchResponseEnvelope) responseEnvelope;
                Map<?, BatchResponseEnvelope.BatchResponseEntry> oldBatchResponses = batchResponseEnvelope.getBatchResponseMap();
                RecordTemplate newResponseRecord = new EmptyRecord();
                RestLiServiceException newResponseException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
                Map<String, BatchResponseEnvelope.BatchResponseEntry> newBatchResponses = new HashMap<>();
                newBatchResponses.put("id1", new BatchResponseEnvelope.BatchResponseEntry(HttpStatus.S_200_OK, newResponseRecord));
                newBatchResponses.put("id2", new BatchResponseEnvelope.BatchResponseEntry(HttpStatus.S_500_INTERNAL_SERVER_ERROR, newResponseException));
                batchResponseEnvelope.setBatchResponseMap(newBatchResponses, HttpStatus.S_200_OK);
                Map<?, BatchResponseEnvelope.BatchResponseEntry> envelopeMap = batchResponseEnvelope.getBatchResponseMap();
                Assert.assertNotEquals(envelopeMap, oldBatchResponses);
                Assert.assertEquals(envelopeMap, newBatchResponses);
                BatchResponseEnvelope.BatchResponseEntry id1Entry = envelopeMap.get("id1");
                Assert.assertEquals(id1Entry.getStatus(), HttpStatus.S_200_OK);
                Assert.assertEquals(id1Entry.getRecord(), newResponseRecord);
                Assert.assertFalse(id1Entry.hasException());
                Assert.assertNull(id1Entry.getException());
                BatchResponseEnvelope.BatchResponseEntry id2Entry = envelopeMap.get("id2");
                Assert.assertEquals(id2Entry.getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
                Assert.assertNull(id2Entry.getRecord());
                Assert.assertTrue(id2Entry.hasException());
                Assert.assertEquals(id2Entry.getException(), newResponseException);
                break;
            case BATCH_COLLECTION:
                BatchFinderResponseEnvelope batchFinderResponseEnvelope = (BatchFinderResponseEnvelope) responseEnvelope;
                List<BatchFinderResponseEnvelope.BatchFinderEntry> oldItems = batchFinderResponseEnvelope.getItems();
                List<BatchFinderResponseEnvelope.BatchFinderEntry> newItems = new ArrayList<>(2);
                RestLiServiceException newBFResponseException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
                newItems.add(new BatchFinderResponseEnvelope.BatchFinderEntry(newBFResponseException));
                RecordTemplate newBFResponseRecord = new EmptyRecord();
                List<RecordTemplate> elements = Arrays.asList(newBFResponseRecord);
                RecordTemplate newBFResponseMetadata = new AnyRecord(new DataMap());
                newBFResponseMetadata.data().put("test", "testing");
                CollectionMetadata newBFResponsesPaging = new CollectionMetadata();
                newItems.add(new BatchFinderResponseEnvelope.BatchFinderEntry(elements, newBFResponsesPaging, newBFResponseMetadata));
                batchFinderResponseEnvelope.setItems(newItems);
                Assert.assertNotEquals(batchFinderResponseEnvelope.getItems(), oldItems);
                Assert.assertEquals(batchFinderResponseEnvelope.getItems(), newItems);
                Assert.assertEquals(batchFinderResponseEnvelope.getItems().get(0).getException(), newBFResponseException);
                Assert.assertEquals(batchFinderResponseEnvelope.getItems().get(1).getElements(), elements);
                Assert.assertEquals(batchFinderResponseEnvelope.getItems().get(1).getPaging(), newBFResponsesPaging);
                Assert.assertEquals(batchFinderResponseEnvelope.getItems().get(1).getCustomMetadata(), newBFResponseMetadata);
                break;
            case STATUS_ONLY:
                // status only envelopes are blank by default since they have no data fields
                break;
            default:
                throw new IllegalStateException();
        }
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DataMap(com.linkedin.data.DataMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) CollectionMetadata(com.linkedin.restli.common.CollectionMetadata) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) ResponseType(com.linkedin.restli.internal.server.ResponseType) Test(org.testng.annotations.Test)

Example 25 with AnyRecord

use of com.linkedin.restli.internal.server.methods.AnyRecord in project rest.li by linkedin.

the class ExampleRequestResponseGenerator method batchFinder.

public ExampleRequestResponse batchFinder(String name) {
    BatchFinderSchema batchFinderSchema = _resourceSchema.getBatchFinder(name);
    if (batchFinderSchema == null) {
        throw new IllegalArgumentException("No such batch finder for resource: " + name);
    }
    RecordDataSchema metadataSchema = null;
    if (batchFinderSchema.hasMetadata()) {
        metadataSchema = (RecordDataSchema) RestSpecCodec.textToSchema(batchFinderSchema.getMetadata().getType(), _schemaResolver);
    }
    Request<?> request = buildBatchFinderRequest(batchFinderSchema);
    RestRequest restRequest = buildRequest(request);
    try {
        ServerResourceContext context = new ResourceContextImpl(new PathKeysImpl(), restRequest, new RequestContext());
        DataList criteriaParams = (DataList) context.getStructuredParameter(batchFinderSchema.getBatchParam());
        // Since batchFinder has 2 kinds of responses. One is successful CollectionResponse. The other one is ErrorResponse.
        // When BatchFinderResponseBuilder cannot find a search criteria, it will return an ErrorResponse.
        // To include only one criteria in BatchFinderResult will make the response example diverse.
        // guarantee batchFinder request and response has a same criteria
        AnyRecord batchFinderCriteria = new AnyRecord((DataMap) criteriaParams.get(0));
        return buildRequestResponse(request, buildBatchFinderResult(metadataSchema, batchFinderCriteria), buildResourceMethodDescriptorForBatchFinder(name, batchFinderSchema.getBatchParam()));
    } catch (RestLiSyntaxException e) {
        throw new ExampleGenerationException("Internal error during example generation", e);
    }
}
Also used : AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) RestLiSyntaxException(com.linkedin.restli.internal.server.util.RestLiSyntaxException) PathKeysImpl(com.linkedin.restli.internal.server.PathKeysImpl) BatchFinderSchema(com.linkedin.restli.restspec.BatchFinderSchema) DataList(com.linkedin.data.DataList) RestRequest(com.linkedin.r2.message.rest.RestRequest) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RecordDataSchema(com.linkedin.data.schema.RecordDataSchema) RequestContext(com.linkedin.r2.message.RequestContext) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl)

Aggregations

AnyRecord (com.linkedin.restli.internal.server.methods.AnyRecord)25 DataMap (com.linkedin.data.DataMap)18 RecordTemplate (com.linkedin.data.template.RecordTemplate)17 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)10 ResourceContext (com.linkedin.restli.server.ResourceContext)8 HashMap (java.util.HashMap)8 ProtocolVersion (com.linkedin.restli.common.ProtocolVersion)7 ArrayList (java.util.ArrayList)7 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)6 BatchResponseEntry (com.linkedin.restli.internal.server.response.BatchResponseEnvelope.BatchResponseEntry)6 Map (java.util.Map)6 DataList (com.linkedin.data.DataList)5 CollectionMetadata (com.linkedin.restli.common.CollectionMetadata)4 HttpStatus (com.linkedin.restli.common.HttpStatus)4 CreateResponse (com.linkedin.restli.server.CreateResponse)4 RecordDataSchema (com.linkedin.data.schema.RecordDataSchema)3 RequestContext (com.linkedin.r2.message.RequestContext)3 CreateIdStatus (com.linkedin.restli.common.CreateIdStatus)3 UpdateStatus (com.linkedin.restli.common.UpdateStatus)3 ResourceContextImpl (com.linkedin.restli.internal.server.ResourceContextImpl)3