Search in sources :

Example 26 with RoutingException

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

the class ArgumentBuilder method buildArrayArgument.

/**
   * Build a method argument from a request parameter that is an array
   *
   * @param context {@link ResourceContext}
   * @param param {@link Parameter}
   * @return argument value in the correct type
   */
private static Object buildArrayArgument(final ResourceContext context, final Parameter<?> param) {
    final Object convertedValue;
    if (DataTemplate.class.isAssignableFrom(param.getItemType())) {
        final DataList itemsList = (DataList) context.getStructuredParameter(param.getName());
        convertedValue = Array.newInstance(param.getItemType(), itemsList.size());
        int j = 0;
        for (Object paramData : itemsList) {
            final DataTemplate<?> itemsElem = DataTemplateUtil.wrap(paramData, param.getItemType().asSubclass(DataTemplate.class));
            ValidateDataAgainstSchema.validate(itemsElem.data(), itemsElem.schema(), new ValidationOptions(RequiredMode.CAN_BE_ABSENT_IF_HAS_DEFAULT, CoercionMode.STRING_TO_PRIMITIVE));
            Array.set(convertedValue, j++, itemsElem);
        }
    } else {
        final List<String> itemStringValues = context.getParameterValues(param.getName());
        ArrayDataSchema parameterSchema = null;
        if (param.getDataSchema() instanceof ArrayDataSchema) {
            parameterSchema = (ArrayDataSchema) param.getDataSchema();
        } else {
            throw new RoutingException("An array schema is expected.", HttpStatus.S_400_BAD_REQUEST.getCode());
        }
        convertedValue = Array.newInstance(param.getItemType(), itemStringValues.size());
        int j = 0;
        for (String itemStringValue : itemStringValues) {
            if (itemStringValue == null) {
                throw new RoutingException("Parameter '" + param.getName() + "' cannot contain null values", HttpStatus.S_400_BAD_REQUEST.getCode());
            }
            try {
                Array.set(convertedValue, j++, ArgumentUtils.convertSimpleValue(itemStringValue, parameterSchema.getItems(), param.getItemType()));
            } catch (NumberFormatException e) {
                Class<?> targetClass = DataSchemaUtil.dataSchemaTypeToPrimitiveDataSchemaClass(parameterSchema.getItems().getDereferencedType());
                // thrown from Integer.valueOf or Long.valueOf
                throw new RoutingException(String.format("Array parameter '%s' value '%s' must be of type '%s'", param.getName(), itemStringValue, targetClass.getName()), HttpStatus.S_400_BAD_REQUEST.getCode());
            } catch (IllegalArgumentException e) {
                // thrown from Enum.valueOf
                throw new RoutingException(String.format("Array parameter '%s' value '%s' is invalid", param.getName(), itemStringValue), HttpStatus.S_400_BAD_REQUEST.getCode());
            } catch (TemplateRuntimeException e) {
                // thrown from DataTemplateUtil.coerceOutput
                throw new RoutingException(String.format("Array parameter '%s' value '%s' is invalid. Reason: %s", param.getName(), itemStringValue, e.getMessage()), HttpStatus.S_400_BAD_REQUEST.getCode());
            }
        }
    }
    return convertedValue;
}
Also used : RoutingException(com.linkedin.restli.server.RoutingException) DataTemplate(com.linkedin.data.template.DataTemplate) ValidationOptions(com.linkedin.data.schema.validation.ValidationOptions) DataList(com.linkedin.data.DataList) ArrayDataSchema(com.linkedin.data.schema.ArrayDataSchema) TemplateRuntimeException(com.linkedin.data.template.TemplateRuntimeException)

Example 27 with RoutingException

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

the class RestLiResponseDataImpl method setException.

/**
   * Sets the top level exception of this response.
   * Each inheriting class must maintain invariant unique to its type.
   *
   * This method is for internal use only. If you wish to set an exception in a filter, please do so by either throwing
   * an exception or by completing the future exceptionally. For more information see {@link com.linkedin.restli.server.filter.Filter}.
   *
   * @param throwable to set this response to.
   */
public void setException(Throwable throwable) {
    if (throwable == null) {
        throw new UnsupportedOperationException("Null is not permitted in setting an exception.");
    }
    RestLiServiceException restLiServiceException;
    if (throwable instanceof RestLiServiceException) {
        restLiServiceException = (RestLiServiceException) throwable;
    } else if (throwable instanceof RoutingException) {
        RoutingException routingException = (RoutingException) throwable;
        restLiServiceException = new RestLiServiceException(HttpStatus.fromCode(routingException.getStatus()), routingException.getMessage(), routingException);
    } else {
        restLiServiceException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, throwable.getMessage(), throwable);
    }
    setServiceException(restLiServiceException);
}
Also used : RoutingException(com.linkedin.restli.server.RoutingException) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException)

Example 28 with RoutingException

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

the class RestLiResponseHandler method encodeResult.

private RestResponseBuilder encodeResult(String mimeType, RestResponseBuilder builder, DataMap dataMap) {
    if (RestConstants.HEADER_VALUE_APPLICATION_PSON.equalsIgnoreCase(mimeType)) {
        builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_PSON);
        builder.setEntity(DataMapUtils.mapToPsonByteString(dataMap));
    } else if (RestConstants.HEADER_VALUE_APPLICATION_JSON.equalsIgnoreCase(mimeType)) {
        builder.setHeader(RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_JSON);
        builder.setEntity(DataMapUtils.mapToByteString(dataMap));
    } else {
        throw new RoutingException("No acceptable types can be returned", HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
    }
    return builder;
}
Also used : RoutingException(com.linkedin.restli.server.RoutingException)

Example 29 with RoutingException

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

the class TestRestLiRouting method expectRoutingExceptionWithStatus.

private void expectRoutingExceptionWithStatus(String uri, ProtocolVersion version, String httpMethod, String restliMethod, HttpStatus status) throws URISyntaxException {
    RestRequestBuilder builder = createRequestBuilder(uri, httpMethod, version);
    if (restliMethod != null) {
        builder.setHeader("X-RestLi-Method", restliMethod);
    }
    RestRequest request = builder.build();
    try {
        RoutingResult r = _router.process(request, new RequestContext(), null);
        fail("Expected RoutingException, got: " + r.toString());
    } catch (RoutingException e) {
        // expected a certain httpStatus code
        assertEquals(e.getStatus(), status.getCode());
    }
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RoutingException(com.linkedin.restli.server.RoutingException) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext)

Example 30 with RoutingException

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

the class RestLiHTMLDocumentationRenderer method renderResource.

@Override
public void renderResource(String resourceName, OutputStream out) {
    final ResourceSchema resourceSchema = _resourceSchemas.getResource(resourceName);
    final List<ResourceSchema> parentResources = _resourceSchemas.getParentResources(resourceSchema);
    ExampleRequestResponseGenerator generator = new ExampleRequestResponseGenerator(parentResources, resourceSchema, _schemaResolver);
    if (resourceSchema == null) {
        throw new RoutingException(String.format("Resource \"%s\" does not exist", resourceName), HttpStatus.S_404_NOT_FOUND.getCode());
    }
    final Map<String, Object> pageModel = createPageModel();
    pageModel.put("resource", resourceSchema);
    pageModel.put("resourceName", resourceName);
    pageModel.put("resourceFullName", ResourceSchemaUtil.getFullName(resourceSchema));
    pageModel.put("resourceType", getResourceType(resourceSchema));
    pageModel.put("subResources", _resourceSchemas.getSubResources(resourceSchema));
    final List<ResourceMethodDocView> restMethods = new ArrayList<ResourceMethodDocView>();
    final List<ResourceMethodDocView> finders = new ArrayList<ResourceMethodDocView>();
    final List<ResourceMethodDocView> actions = new ArrayList<ResourceMethodDocView>();
    final MethodGatheringResourceSchemaVisitor visitor = new MethodGatheringResourceSchemaVisitor(resourceName);
    ResourceSchemaCollection.visitResources(_resourceSchemas.getResources().values(), visitor);
    for (RecordTemplate methodSchema : visitor.getAllMethods()) {
        final ExampleRequestResponse capture;
        if (methodSchema instanceof RestMethodSchema) {
            RestMethodSchema restMethodSchema = (RestMethodSchema) methodSchema;
            capture = generator.method(ResourceMethod.valueOf(restMethodSchema.getMethod().toUpperCase()));
        } else if (methodSchema instanceof FinderSchema) {
            FinderSchema finderMethodSchema = (FinderSchema) methodSchema;
            capture = generator.finder(finderMethodSchema.getName());
        } else if (methodSchema instanceof ActionSchema) {
            ActionSchema actionMethodSchema = (ActionSchema) methodSchema;
            final ResourceLevel resourceLevel = (visitor.getCollectionActions().contains(methodSchema) ? ResourceLevel.COLLECTION : ResourceLevel.ENTITY);
            capture = generator.action(actionMethodSchema.getName(), resourceLevel);
        } else {
            capture = null;
        }
        String requestEntity = null;
        String responseEntity = null;
        if (capture != null) {
            try {
                DataMap entityMap;
                if (capture.getRequest().getEntity().length() > 0) {
                    entityMap = DataMapUtils.readMap(capture.getRequest());
                    requestEntity = new String(_codec.mapToBytes(entityMap));
                }
                if (capture.getResponse() != null && capture.getResponse().getEntity() != null && capture.getResponse().getEntity().length() > 0) {
                    entityMap = DataMapUtils.readMap(capture.getResponse());
                    responseEntity = new String(_codec.mapToBytes(entityMap));
                }
            } catch (IOException e) {
                throw new RestLiInternalException(e);
            }
        }
        final ResourceMethodDocView docView = new ResourceMethodDocView(methodSchema, capture, getDoc(methodSchema, resourceSchema.hasSimple()), requestEntity, responseEntity);
        if (methodSchema instanceof RestMethodSchema) {
            restMethods.add(docView);
        } else if (methodSchema instanceof FinderSchema) {
            finders.add(docView);
        } else if (methodSchema instanceof ActionSchema) {
            actions.add(docView);
        }
    }
    pageModel.put("restMethods", restMethods);
    pageModel.put("finders", finders);
    pageModel.put("actions", actions);
    addRelated(resourceSchema, pageModel);
    _templatingEngine.render("resource.vm", pageModel, out);
}
Also used : RoutingException(com.linkedin.restli.server.RoutingException) ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) ExampleRequestResponse(com.linkedin.restli.docgen.examplegen.ExampleRequestResponse) ResourceLevel(com.linkedin.restli.server.ResourceLevel) ArrayList(java.util.ArrayList) RestMethodSchema(com.linkedin.restli.restspec.RestMethodSchema) FinderSchema(com.linkedin.restli.restspec.FinderSchema) IOException(java.io.IOException) ActionSchema(com.linkedin.restli.restspec.ActionSchema) DataMap(com.linkedin.data.DataMap) ExampleRequestResponseGenerator(com.linkedin.restli.docgen.examplegen.ExampleRequestResponseGenerator) RecordTemplate(com.linkedin.data.template.RecordTemplate) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException)

Aggregations

RoutingException (com.linkedin.restli.server.RoutingException)41 RestRequest (com.linkedin.r2.message.rest.RestRequest)15 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)15 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)15 Test (org.testng.annotations.Test)15 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)12 DataMap (com.linkedin.data.DataMap)7 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)7 TemplateRuntimeException (com.linkedin.data.template.TemplateRuntimeException)6 ResourceContext (com.linkedin.restli.server.ResourceContext)6 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)6 RequestContext (com.linkedin.r2.message.RequestContext)5 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)5 CompoundKey (com.linkedin.restli.common.CompoundKey)5 RestLiRequestData (com.linkedin.restli.server.RestLiRequestData)5 ByteString (com.linkedin.data.ByteString)4 ResourceContextImpl (com.linkedin.restli.internal.server.ResourceContextImpl)4 RestLiInternalException (com.linkedin.restli.internal.server.RestLiInternalException)4 CustomString (com.linkedin.restli.server.custom.types.CustomString)4 RestLiTestHelper.buildResourceModel (com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel)4