Search in sources :

Example 1 with RestLiInternalException

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

the class RestLiJSONDocumentationRenderer method renderDataModel.

@Override
public void renderDataModel(String dataModelName, OutputStream out) {
    final NamedDataSchema schema = _relationships.getDataModels().get(dataModelName);
    if (schema == null) {
        throw new RoutingException(String.format("Data model named '%s' does not exist", dataModelName), 404);
    }
    final DataMap outputMap = createEmptyOutput();
    try {
        renderDataModel(schema, outputMap);
        _codec.writeMap(outputMap, out);
    } catch (IOException e) {
        throw new RestLiInternalException(e);
    }
}
Also used : NamedDataSchema(com.linkedin.data.schema.NamedDataSchema) RoutingException(com.linkedin.restli.server.RoutingException) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) IOException(java.io.IOException) DataMap(com.linkedin.data.DataMap)

Example 2 with RestLiInternalException

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

the class ResourceSchemaCollection method createFromIdls.

/**
   * Create {@link ResourceSchemaCollection} from idl files.
   *
   * @param restspecSearchPaths file system paths to search for idl files
   * @return constructed ResourceSchemaCollection
   */
public static ResourceSchemaCollection createFromIdls(String[] restspecSearchPaths) {
    final RestSpecCodec codec = new RestSpecCodec();
    final Map<String, ResourceSchema> resourceSchemaMap = new HashMap<String, ResourceSchema>();
    for (String path : restspecSearchPaths) {
        final File dir = new File(path);
        if (!dir.isDirectory()) {
            throw new IllegalArgumentException(String.format("path '%s' is not a directory", dir.getAbsolutePath()));
        }
        final File[] idlFiles = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(RestConstants.RESOURCE_MODEL_FILENAME_EXTENSION);
            }
        });
        for (File idlFile : idlFiles) {
            try {
                final FileInputStream is = new FileInputStream(idlFile);
                final ResourceSchema resourceSchema = codec.readResourceSchema(is);
                resourceSchemaMap.put(resourceSchema.getName(), resourceSchema);
            } catch (IOException e) {
                throw new RestLiInternalException(String.format("Error loading restspec IDL file '%s'", idlFile.getName()), e);
            }
        }
    }
    return new ResourceSchemaCollection(resourceSchemaMap);
}
Also used : ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) HashMap(java.util.HashMap) IdentityHashMap(java.util.IdentityHashMap) RestSpecCodec(com.linkedin.restli.restspec.RestSpecCodec) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) FileFilter(java.io.FileFilter) File(java.io.File)

Example 3 with RestLiInternalException

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

the class RestLiHTMLDocumentationRenderer method renderDataModel.

@Override
public void renderDataModel(String dataModelName, OutputStream out) {
    final NamedDataSchema schema = _relationships.getDataModels().get(dataModelName);
    if (schema == null) {
        throw new RoutingException(String.format("Data model named '%s' does not exist", dataModelName), 404);
    }
    final Map<String, Object> pageModel = createPageModel();
    pageModel.put("dataModel", schema);
    final DataMap example = SchemaSampleDataGenerator.buildRecordData(schema, new SchemaSampleDataGenerator.DataGenerationOptions());
    try {
        pageModel.put("example", new String(_codec.mapToBytes(example)));
    } catch (IOException e) {
        throw new RestLiInternalException(e);
    }
    addRelated(schema, pageModel);
    _templatingEngine.render("dataModel.vm", pageModel, out);
}
Also used : NamedDataSchema(com.linkedin.data.schema.NamedDataSchema) RoutingException(com.linkedin.restli.server.RoutingException) SchemaSampleDataGenerator(com.linkedin.data.schema.generator.SchemaSampleDataGenerator) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) IOException(java.io.IOException) DataMap(com.linkedin.data.DataMap)

Example 4 with RestLiInternalException

use of com.linkedin.restli.internal.server.RestLiInternalException 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 5 with RestLiInternalException

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

the class ArgumentUtils method parseCompoundKey.

/**
   * Parse {@link CompoundKey} from its String representation.
   *
   * @param urlString {@link CompoundKey} string representation
   * @param keys {@link CompoundKey} constituent keys' classes keyed on their names
   * @param errorMessageBuilder {@link StringBuilder} to build error message if necessary
   * @param simpleKeyDelimiterPattern delimiter of constituent keys in the compound key
   * @param keyValueDelimiterPattern delimiter of key and value in a constituent key
   * @return {@link CompoundKey} parsed from the input string
   */
public static CompoundKey parseCompoundKey(final String urlString, final Collection<Key> keys, final StringBuilder errorMessageBuilder, final Pattern simpleKeyDelimiterPattern, final Pattern keyValueDelimiterPattern) throws RoutingException {
    String[] simpleKeys = simpleKeyDelimiterPattern.split(urlString.trim());
    CompoundKey compoundKey = new CompoundKey();
    for (String simpleKey : simpleKeys) {
        String[] nameValuePair = keyValueDelimiterPattern.split(simpleKey.trim());
        if (simpleKey.trim().length() == 0 || nameValuePair.length != 2) {
            errorMessageBuilder.append("Bad key format '");
            errorMessageBuilder.append(urlString);
            errorMessageBuilder.append("'");
            return null;
        }
        // Simple key names and values are URL-encoded prior to being included in the URL on
        // the client, to prevent collision with any of the delimiter characters (bulk,
        // compound key and simple key-value). So, must decode them
        String name;
        try {
            name = URLDecoder.decode(nameValuePair[0], RestConstants.DEFAULT_CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            //should not happen, since we are using "UTF-8" as the encoding
            throw new RestLiInternalException(e);
        }
        // Key is not found in the set defined for the resource
        Key currentKey = getKeyWithName(keys, name);
        if (currentKey == null) {
            errorMessageBuilder.append("Unknown key part named '");
            errorMessageBuilder.append(name);
            errorMessageBuilder.append("'");
            return null;
        }
        String decodedStringValue;
        try {
            decodedStringValue = URLDecoder.decode(nameValuePair[1], RestConstants.DEFAULT_CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            //should not happen, since we are using "UTF-8" as the encoding
            throw new RestLiInternalException(e);
        }
        compoundKey.append(name, convertSimpleValue(decodedStringValue, currentKey.getDataSchema(), currentKey.getType()));
    }
    return compoundKey;
}
Also used : CompoundKey(com.linkedin.restli.common.CompoundKey) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ComplexResourceKey(com.linkedin.restli.common.ComplexResourceKey) AlternativeKey(com.linkedin.restli.server.AlternativeKey) Key(com.linkedin.restli.server.Key) CompoundKey(com.linkedin.restli.common.CompoundKey)

Aggregations

RestLiInternalException (com.linkedin.restli.internal.server.RestLiInternalException)19 IOException (java.io.IOException)8 DataMap (com.linkedin.data.DataMap)6 NamedDataSchema (com.linkedin.data.schema.NamedDataSchema)4 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)4 RoutingException (com.linkedin.restli.server.RoutingException)4 HashMap (java.util.HashMap)4 ResourceSchema (com.linkedin.restli.restspec.ResourceSchema)3 SomeDependency1 (com.linkedin.restli.server.resources.fixtures.SomeDependency1)3 SomeDependency2 (com.linkedin.restli.server.resources.fixtures.SomeDependency2)3 Test (org.testng.annotations.Test)3 JsonBuilder (com.linkedin.data.schema.JsonBuilder)2 PrimitiveDataSchema (com.linkedin.data.schema.PrimitiveDataSchema)2 SchemaToJsonEncoder (com.linkedin.data.schema.SchemaToJsonEncoder)2 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)2 ArrayList (java.util.ArrayList)2 DataSchema (com.linkedin.data.schema.DataSchema)1 TyperefDataSchema (com.linkedin.data.schema.TyperefDataSchema)1 UnionDataSchema (com.linkedin.data.schema.UnionDataSchema)1 SchemaSampleDataGenerator (com.linkedin.data.schema.generator.SchemaSampleDataGenerator)1