Search in sources :

Example 1 with RestLiServiceException

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

the class CollectionResponseBuilder method buildRestLiResponseData.

private static RestLiResponseData buildRestLiResponseData(final RestRequest request, final RoutingResult routingResult, final List<? extends RecordTemplate> elements, final PageIncrement pageIncrement, final RecordTemplate customMetadata, final Integer totalResults, final Map<String, String> headers, final List<HttpCookie> cookies) {
    //Extract the resource context that contains projection information for root object entities, metadata and paging.
    final ResourceContext resourceContext = routingResult.getContext();
    //Calculate paging metadata and apply projection
    final CollectionMetadata paging = RestUtils.buildMetadata(request.getURI(), resourceContext, routingResult.getResourceMethod(), elements, pageIncrement, totalResults);
    //PagingMetadata cannot be null at this point so we skip the null check. Notice here that we are using automatic
    //intentionally since resource methods cannot explicitly project paging. However, it should be noted that client
    //resource methods have the option of selectively setting the total to null. This happens if a client decides
    //that they want the total in the paging response, which the resource method will see in their paging path spec,
    //and then specify total when they create CollectionResult. Restli will then also subsequently separately project
    //paging using this same path spec.
    //Note that there is no chance of potential data loss here:
    //If the client decides they don't want total in their paging response, then the resource method will
    //see the lack of total in their paging path spec and then decide to set total to null. We will then also exclude it
    //when we project paging.
    //If the client decides they want total in their paging response, then the resource method will see total in their
    //paging path spec and then decide to set total to a non null value. We will then also include it when we project
    //paging.
    final CollectionMetadata projectedPaging = new CollectionMetadata(RestUtils.projectFields(paging.data(), ProjectionMode.AUTOMATIC, resourceContext.getPagingProjectionMask()));
    //For root object entities
    List<AnyRecord> processedElements = new ArrayList<AnyRecord>(elements.size());
    for (RecordTemplate entry : elements) {
        //We don't permit null elements in our lists. If so, this is a developer error.
        if (entry == null) {
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null element inside of a List returned by the resource method: " + routingResult.getResourceMethod());
        }
        processedElements.add(new AnyRecord(RestUtils.projectFields(entry.data(), resourceContext.getProjectionMode(), resourceContext.getProjectionMask())));
    }
    //Now for custom metadata
    final AnyRecord projectedCustomMetadata;
    if (customMetadata != null) {
        projectedCustomMetadata = new AnyRecord(RestUtils.projectFields(customMetadata.data(), resourceContext.getMetadataProjectionMode(), resourceContext.getMetadataProjectionMask()));
    } else {
        projectedCustomMetadata = null;
    }
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, headers, cookies);
    RestLiResponseEnvelope responseEnvelope;
    switch(routingResult.getResourceMethod().getType()) {
        case GET_ALL:
            responseEnvelope = new GetAllResponseEnvelope(processedElements, projectedPaging, projectedCustomMetadata, responseData);
            break;
        case FINDER:
            responseEnvelope = new FinderResponseEnvelope(processedElements, projectedPaging, projectedCustomMetadata, responseData);
            break;
        default:
            throw new IllegalStateException("Resource method is invalid for CollectionResponseBuilder");
    }
    responseData.setResponseEnvelope(responseEnvelope);
    return responseData;
}
Also used : CollectionMetadata(com.linkedin.restli.common.CollectionMetadata) ResourceContext(com.linkedin.restli.server.ResourceContext) AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) ArrayList(java.util.ArrayList)

Example 2 with RestLiServiceException

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

the class RestLiResponseHandler method buildRestLiResponseData.

/**
   * Build a RestLiResponseDataInternal from response object, incoming RestRequest and RoutingResult.
   *
   * @param request
   *          {@link RestRequest}
   * @param routingResult
   *          {@link RoutingResult}
   * @param responseObject
   *          response value
   * @return {@link RestLiResponseEnvelope}
   * @throws IOException
   *           if cannot build response
   */
public RestLiResponseData buildRestLiResponseData(final RestRequest request, final RoutingResult routingResult, final Object responseObject) throws IOException {
    ServerResourceContext context = (ServerResourceContext) routingResult.getContext();
    final ProtocolVersion protocolVersion = context.getRestliProtocolVersion();
    Map<String, String> responseHeaders = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    responseHeaders.putAll(context.getResponseHeaders());
    responseHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
    List<HttpCookie> responseCookies = context.getResponseCookies();
    if (responseObject == null) {
        //If we have a null result, we have to assign the correct response status
        if (routingResult.getResourceMethod().getType().equals(ResourceMethod.ACTION)) {
            RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, responseHeaders, responseCookies);
            responseData.setResponseEnvelope(new ActionResponseEnvelope(null, responseData));
            return responseData;
        } else if (routingResult.getResourceMethod().getType().equals(ResourceMethod.GET)) {
            throw new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "Requested entity not found: " + routingResult.getResourceMethod());
        } else {
            //All other cases do not permit null to be returned
            throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null returned by the resource method: " + routingResult.getResourceMethod());
        }
    }
    RestLiResponseBuilder responseBuilder = chooseResponseBuilder(responseObject, routingResult);
    if (responseBuilder == null) {
        // this should not happen if valid return types are specified
        ResourceMethodDescriptor resourceMethod = routingResult.getResourceMethod();
        String fqMethodName = resourceMethod.getResourceModel().getResourceClass().getName() + '#' + routingResult.getResourceMethod().getMethod().getName();
        throw new RestLiInternalException("Invalid return type '" + responseObject.getClass() + " from method '" + fqMethodName + '\'');
    }
    return responseBuilder.buildRestLiResponseData(request, routingResult, responseObject, responseHeaders, responseCookies);
}
Also used : ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) TreeMap(java.util.TreeMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) HttpCookie(java.net.HttpCookie)

Example 3 with RestLiServiceException

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

the class UpdateResponseBuilder method buildRestLiResponseData.

@Override
public RestLiResponseData buildRestLiResponseData(RestRequest request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
    UpdateResponse updateResponse = (UpdateResponse) result;
    //Verify that the status in the UpdateResponse is not null. If so, this is a developer error.
    if (updateResponse.getStatus() == null) {
        throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. HttpStatus is null inside of a UpdateResponse returned by the resource method: " + routingResult.getResourceMethod());
    }
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(updateResponse.getStatus(), headers, cookies);
    responseData.setResponseEnvelope(new UpdateResponseEnvelope(responseData));
    return responseData;
}
Also used : UpdateResponse(com.linkedin.restli.server.UpdateResponse) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException)

Example 4 with RestLiServiceException

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

the class RestLiValidationFilter method validateBatchResponse.

private void validateBatchResponse(RestLiDataValidator validator, Map<?, BatchResponseEnvelope.BatchResponseEntry> batchResponseMap, MaskTree projectionMask) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<?, ? extends BatchResponseEnvelope.BatchResponseEntry> entry : batchResponseMap.entrySet()) {
        if (entry.getValue().hasException()) {
            continue;
        }
        ValidationResult result = validator.validateOutput(entry.getValue().getRecord(), projectionMask);
        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_500_INTERNAL_SERVER_ERROR, sb.toString());
    }
}
Also used : RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) Map(java.util.Map) BatchResponseEnvelope(com.linkedin.restli.internal.server.response.BatchResponseEnvelope)

Example 5 with RestLiServiceException

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

the class TestRestLiResponseData method testEmptyResponseEnvelopeUpdates.

@Test(dataProvider = "emptyResponseEnvelopesProvider")
public void testEmptyResponseEnvelopeUpdates(RestLiResponseDataImpl responseData) {
    Assert.assertFalse(responseData.isErrorResponse());
    responseData.setException(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
    Assert.assertTrue(responseData.isErrorResponse());
    Assert.assertEquals(responseData.getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
    responseData.setStatus(HttpStatus.S_200_OK);
    Assert.assertFalse(responseData.isErrorResponse());
    Assert.assertEquals(responseData.getStatus(), HttpStatus.S_200_OK);
}
Also used : RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) Test(org.testng.annotations.Test)

Aggregations

RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)145 Test (org.testng.annotations.Test)55 HashMap (java.util.HashMap)39 DataMap (com.linkedin.data.DataMap)29 RecordTemplate (com.linkedin.data.template.RecordTemplate)21 Map (java.util.Map)21 RoutingException (com.linkedin.restli.server.RoutingException)20 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)18 UpdateResponse (com.linkedin.restli.server.UpdateResponse)18 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)17 BeforeTest (org.testng.annotations.BeforeTest)17 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)16 ArrayList (java.util.ArrayList)16 RestException (com.linkedin.r2.message.rest.RestException)14 FilterResponseContext (com.linkedin.restli.server.filter.FilterResponseContext)13 RestRequest (com.linkedin.r2.message.rest.RestRequest)12 ByteString (com.linkedin.data.ByteString)11 ProtocolVersion (com.linkedin.restli.common.ProtocolVersion)11 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)11 BatchResult (com.linkedin.restli.server.BatchResult)11