Search in sources :

Example 1 with CreateKVResponse

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

the class TestCreateResponseBuilder method testProjectionInBuildRestliResponseData.

@Test
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.getProjectionMask()).andReturn(maskTree);
    EasyMock.expect(mockContext.getProjectionMode()).andReturn(ProjectionMode.AUTOMATIC);
    EasyMock.replay(mockContext);
    RoutingResult routingResult = new RoutingResult(mockContext, null);
    Foo value = new Foo().setStringField("value").setFruitsField(Fruits.APPLE);
    CreateKVResponse<Integer, Foo> values = new CreateKVResponse<Integer, Foo>(null, value);
    CreateResponseBuilder responseBuilder = new CreateResponseBuilder();
    RestLiResponseData envelope = responseBuilder.buildRestLiResponseData(new RestRequestBuilder(new URI("/foo")).build(), routingResult, values, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    RecordTemplate record = envelope.getRecordResponseEnvelope().getRecord();
    Assert.assertEquals(record.data().size(), 1);
    Assert.assertEquals(record.data().get("fruitsField"), Fruits.APPLE.toString());
    Assert.assertTrue(envelope.getCreateResponseEnvelope().isGetAfterCreate());
    EasyMock.verify(mockContext);
}
Also used : Foo(com.linkedin.pegasus.generator.examples.Foo) RestLiResponseData(com.linkedin.restli.server.RestLiResponseData) PathSpec(com.linkedin.data.schema.PathSpec) URI(java.net.URI) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) MaskTree(com.linkedin.data.transform.filter.request.MaskTree) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RecordTemplate(com.linkedin.data.template.RecordTemplate) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse) Test(org.testng.annotations.Test)

Example 2 with CreateKVResponse

use of com.linkedin.restli.server.CreateKVResponse 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 3 with CreateKVResponse

use of com.linkedin.restli.server.CreateKVResponse 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 CreateKVResponse

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

the class TestCreateResponseBuilder method testReturnEntityException.

/**
 * We want to ensure that trying to create a Rest.li response from an empty {@link CreateKVResponse} causes an exception.
 */
@Test
public void testReturnEntityException() throws URISyntaxException {
    ServerResourceContext mockContext = EasyMock.createMock(ServerResourceContext.class);
    EasyMock.expect(mockContext.isReturnEntityRequested()).andReturn(true);
    EasyMock.expect(mockContext.getProjectionMask()).andReturn(null);
    EasyMock.expect(mockContext.getProjectionMode()).andReturn(ProjectionMode.AUTOMATIC);
    EasyMock.replay(mockContext);
    RoutingResult routingResult = new RoutingResult(mockContext, null);
    CreateKVResponse<Integer, Foo> createKVResponse = new CreateKVResponse<>(null, null);
    try {
        CreateResponseBuilder responseBuilder = new CreateResponseBuilder();
        RestLiResponseData<CreateResponseEnvelope> envelope = responseBuilder.buildRestLiResponseData(new RestRequestBuilder(new URI("/foo")).build(), routingResult, createKVResponse, Collections.emptyMap(), Collections.emptyList());
        Assert.fail("Attempting to build RestLi response data with a null entity here should cause an exception.");
    } catch (RestLiServiceException e) {
        Assert.assertEquals(e.getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR, "");
        Assert.assertTrue(e.getMessage().contains("Unexpected null encountered. Entity is null inside of a CreateKVResponse"), "Invalid exception message: \"" + e.getMessage() + "\"");
    }
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) Foo(com.linkedin.pegasus.generator.examples.Foo) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse) URI(java.net.URI) Test(org.testng.annotations.Test)

Example 5 with CreateKVResponse

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

the class CreateResponseBuilder method buildRestLiResponseData.

/**
 * {@inheritDoc}
 *
 * @param result The result of a Rest.li CREATE method. It is an instance of {@link CreateResponse}; or subclass
 *               {@link CreateKVResponse}, if the CREATE method returns the entity.
 */
@Override
public RestLiResponseData<CreateResponseEnvelope> buildRestLiResponseData(Request request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    CreateResponse createResponse = (CreateResponse) result;
    boolean isGetAfterCreate = createResponse instanceof CreateKVResponse;
    if (createResponse.hasError()) {
        RestLiServiceException exception = createResponse.getError();
        return new RestLiResponseDataImpl<>(new CreateResponseEnvelope(exception, isGetAfterCreate), headers, cookies);
    }
    Object id = null;
    if (createResponse.hasId()) {
        id = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(createResponse.getId(), routingResult);
        final ProtocolVersion protocolVersion = routingResult.getContext().getRestliProtocolVersion();
        String stringKey = URIParamUtils.encodeKeyForUri(id, UriComponent.Type.PATH_SEGMENT, protocolVersion);
        UriBuilder uribuilder = UriBuilder.fromUri(request.getURI());
        uribuilder.path(stringKey);
        uribuilder.replaceQuery(null);
        if (routingResult.getContext().hasParameter(RestConstants.ALT_KEY_PARAM)) {
            // add altkey param to location URI
            uribuilder.queryParam(RestConstants.ALT_KEY_PARAM, routingResult.getContext().getParameter(RestConstants.ALT_KEY_PARAM));
        }
        headers.put(RestConstants.HEADER_LOCATION, uribuilder.build((Object) null).toString());
        headers.put(HeaderUtil.getIdHeaderName(protocolVersion), URIParamUtils.encodeKeyForHeader(id, protocolVersion));
    }
    // Verify that a null status was not passed into the CreateResponse. If so, this is a developer error.
    if (createResponse.getStatus() == null) {
        throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. HttpStatus is null inside of a CreateResponse from the resource method: " + routingResult.getResourceMethod());
    }
    final ResourceContext resourceContext = routingResult.getContext();
    RecordTemplate idResponse;
    if (createResponse instanceof CreateKVResponse && resourceContext.isReturnEntityRequested()) {
        RecordTemplate entity = ((CreateKVResponse<?, ?>) createResponse).getEntity();
        // Verify that a null entity was not passed into the CreateKVResponse. If so, this is a developer error.
        if (entity == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Entity is null inside of a CreateKVResponse when the entity should be returned. In resource method: " + routingResult.getResourceMethod());
        }
        DataMap entityData = entity.data();
        TimingContextUtil.beginTiming(resourceContext.getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
        final DataMap data = RestUtils.projectFields(entityData, resourceContext);
        TimingContextUtil.endTiming(resourceContext.getRawRequestContext(), FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key());
        idResponse = new AnyRecord(data);
    // Ideally, we should set an IdEntityResponse to the envelope. But we are keeping AnyRecord
    // to make sure the runtime object is backwards compatible.
    // idResponse = new IdEntityResponse<>(id, new AnyRecord(data));
    } else // Instance of idResponse
    {
        idResponse = new IdResponse<>(id);
    }
    return new RestLiResponseDataImpl<>(new CreateResponseEnvelope(createResponse.getStatus(), idResponse, isGetAfterCreate), headers, cookies);
}
Also used : ResourceContext(com.linkedin.restli.server.ResourceContext) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) CreateResponse(com.linkedin.restli.server.CreateResponse) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) DataMap(com.linkedin.data.DataMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse) UriBuilder(com.linkedin.jersey.api.uri.UriBuilder)

Aggregations

CreateKVResponse (com.linkedin.restli.server.CreateKVResponse)13 Foo (com.linkedin.pegasus.generator.examples.Foo)7 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)6 BatchCreateKVResult (com.linkedin.restli.server.BatchCreateKVResult)6 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)6 ArrayList (java.util.ArrayList)6 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)5 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)5 CreateResponse (com.linkedin.restli.server.CreateResponse)5 URI (java.net.URI)5 Test (org.testng.annotations.Test)5 DataMap (com.linkedin.data.DataMap)4 RecordTemplate (com.linkedin.data.template.RecordTemplate)4 PathSpec (com.linkedin.data.schema.PathSpec)3 MaskTree (com.linkedin.data.transform.filter.request.MaskTree)3 RequestContext (com.linkedin.r2.message.RequestContext)3 CreateIdEntityStatus (com.linkedin.restli.common.CreateIdEntityStatus)3 AnyRecord (com.linkedin.restli.internal.server.methods.AnyRecord)3 ReturnEntity (com.linkedin.restli.server.annotations.ReturnEntity)3 UriBuilder (com.linkedin.jersey.api.uri.UriBuilder)2