Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
     Copyright (c) 2012 LinkedIn Corp.
  
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
         http://www.apache.org/licenses/LICENSE-2.0
  
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */
 
 package com.linkedin.restli.docgen;
 
 
 
 import java.net.URI;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
Generates a example requests for a given Resource IDL. Uses com.linkedin.data.schema.generator.SchemaSampleDataGenerator to build example data models for input/output.

Author(s):
dellamag, Keren Jin
 
 public class RestLiExampleGenerator
 {
   static class RequestGenerationSpec
   {
     public boolean includeOptionalParameters = true;
     public boolean useDefaultValues = true;
   }

  

Parameters:
resourceSchemas resource schemas created with rootResources
rootResources root resources from its resource path. subresource models will be discovered
schemaResolver resolver that resolves related com.linkedin.restli.restspec.ResourceSchema
                                Map<StringResourceModelrootResources,
                                DataSchemaResolver schemaResolver)
  {
     = resourceSchemas;
     = new TreeMap<StringResourceModel>(rootResources);
     = schemaResolver;
    for (ResourceModel modelrootResources.values())
    {
      buildSubModels(model.getName(), model.getSubResources());
    }
  }

  
Generate request-response pair with example data for REST method characterized by the specified specification

Parameters:
resourceSchema schema of the subject resource
restMethodSchema schema of the subject REST method
spec specification of the generated example data
Returns:
request-response pair that captures the generated example data
                                                       RestMethodSchema restMethodSchema,
                                                       RequestGenerationSpec spec)
  {
    final ResourceMethod restMethod = ResourceMethod.valueOf(restMethodSchema.getMethod().toUpperCase());
    final String templatePath;
    if (resourceSchema.hasSimple() ||
        .contains(restMethod) ||
        .contains(restMethod))
    {
      templatePath = resourceSchema.getPath();
    }
    else
    {
      templatePath = getEntityMethodPath(resourceSchema);
    }
    if (templatePath == null)
    {
      return null;
    }
    final ResourceModel model = .get(resourceSchema.getPath());
    final Map<StringStringuriTemplateExampleValues = getUriTemplateExampleValues(model);
    final UriBuilder uriBuilder = UriBuilder.fromPath(new UriTemplate(templatePath).createURI(uriTemplateExampleValues));
    if (.contains(restMethod))
    {
      buildBatchRequestExampleUri(modeluriBuilder);
    }
    // TODO OFFLINE RestLiResponseHandler requires RoutingResult, which requires ResourceMethodDescriptor.
    final ResourceMethodDescriptor method = model.findMethod(restMethod);
    final ParameterSchemaArray params = restMethodSchema.getParameters();
    if (params != null)
    {
      QueryParamsDataMap.addSortedParams(uriBuildergetQueryParamMap(paramsspec));
    }
    final Class<? extends RecordTemplatevalueClass = getClass(resourceSchema.getSchema());
    final Double randomId = Math.random() * 100;
    final RecordTemplate record = buildRecordTemplate(valueClass);
    final CreateResponse cr = new CreateResponse(randomId);
    final UpdateResponse ur = new UpdateResponse(.);
    final RecordTemplate diffRecord = buildRecordTemplate(valueClass);
    final PatchRequest<?> patch = new PatchRequest<RecordTemplate>(PatchCreator.diff(recorddiffRecord).getDataMap());
    final DataMap batchData = new DataMap();
    batchData.put(randomId.toString(), record.data());
    final Map<DoubleUpdateResponsebuResponseData = new HashMap<DoubleUpdateResponse>();
    buResponseData.put(randomIdur);
    final BatchUpdateResult<Double,RecordTemplatebur = new BatchUpdateResult<DoubleRecordTemplate>(buResponseData);
    RecordTemplate requestEntity = null;
    Object responseEntity = null;
    switch (restMethod)
    {
      case :
        responseEntity = record;
        break;
      case :
        requestEntity = record;
        responseEntity = cr;
        break;
      case :
        requestEntity = record;
        responseEntity = ur;
        break;
      case :
        responseEntity = ur;
        break;
      case :
        requestEntity = patch;
        responseEntity = ur;
        break;
      case :
        final Map<DoubleRecordTemplatebgResponseData = new HashMap<DoubleRecordTemplate>();
        bgResponseData.put(randomIdrecord);
        responseEntity = new BatchResult<DoubleRecordTemplate>(bgResponseDatanew HashMap<DoubleRestLiServiceException>());
        break;
      case :
        @SuppressWarnings({"unchecked","rawtypes"})
        final CollectionRequest bcRequest = new CollectionRequest(batchDatavalueClass);
        requestEntity = bcRequest;
        responseEntity = new BatchCreateResult<LongRecordTemplate>(Arrays.asList(cr));
        break;
      case :
        @SuppressWarnings({"unchecked""rawtypes"})
        final BatchRequest buRequest = new BatchRequest(batchDatavalueClass);
        requestEntity = buRequest;
        responseEntity = bur;
        break;
      case :
        final Map<DoubleUpdateResponsebdResponseData = new HashMap<DoubleUpdateResponse>();
        bdResponseData.put(randomIdur);
        responseEntity = new BatchUpdateResult<DoubleRecordTemplate>(bdResponseData);
        break;
      case :
        final DataMap batchPartialData = new DataMap();
        batchData.put(randomId.toString(), patch.data());
        @SuppressWarnings("rawtypes")
        final BatchRequest bpuRequest = new BatchRequest<PatchRequest>(batchPartialDataPatchRequest.class);
        requestEntity = bpuRequest;
        responseEntity = bur;
        break;
    }
    return doRequest(uriBuilder,
                     requestEntity,
                     responseEntity,
                     restMethod.getHttpMethod(),
                     method);
  }

  
Generate request-response pair with example data for finder characterized by the specified specification

Parameters:
resourceSchema schema of the subject resource
finderSchema schema of the subject finder
spec specification of the generated example data
Returns:
request-response pair that captures the generated example data
                                                   FinderSchema finderSchema,
                                                   RequestGenerationSpec spec)
  {
    final String templatePath = resourceSchema.getPath();
    final ResourceModel model = .get(resourceSchema.getPath());
    final Map<StringStringuriTemplateExampleValues = getUriTemplateExampleValues(model);
    final UriBuilder uriBuilder = UriBuilder.fromPath(new UriTemplate(templatePath).createURI(uriTemplateExampleValues));
    // TODO OFFLINE RestLiResponseHandler requires RoutingResult, which requires ResourceMethodDescriptor.
    final ResourceMethodDescriptor method = model.findNamedMethod(finderSchema.getName());
    final Class<? extends RecordTemplatevalueClass = getClass(resourceSchema.getSchema());
    final Object responseEntity = buildFinderResponse(valueClassmethod.getFinderMetadataType());
    uriBuilder.queryParam(.finderSchema.getName());
    final ParameterSchemaArray params = finderSchema.getParameters();
    if (params != null)
    {
      QueryParamsDataMap.addSortedParams(uriBuildergetQueryParamMap(paramsspec));
    }
    final AssociationSchema assocSchema = resourceSchema.getAssociation();
    if (assocSchema != null)
    {
      final String singleAssocKeyName = finderSchema.getAssocKey();
      final Set<StringmultipleAssocKeyNames = (finderSchema.hasAssocKeys() ? new HashSet<String>(finderSchema.getAssocKeys()) : null);
      if (singleAssocKeyName != null || multipleAssocKeyNames != null)
      {
        final UriBuilder assocKeyBuilder = new UriBuilder();
        for (AssocKeySchema assocKeyassocSchema.getAssocKeys())
        {
          if (singleAssocKeyName != null && singleAssocKeyName.equals(assocKey.getName()))
          {
            addAssocKeyToUri(assocKeyassocKeyBuilder);
            break;
          }
          if (multipleAssocKeyNames != null && multipleAssocKeyNames.contains(assocKey.getName()))
          {
            addAssocKeyToUri(assocKeyassocKeyBuilder);
          }
        }
        final String assocKeyQuery = assocKeyBuilder.build().getQuery();
        if (assocKeyQuery == null)
        {
          throw new RestLiServiceException(.,
                                           String.format("The assocKey parameters in finder \"%s\" does match any assocKey for the collection."finderSchema.getName()));
        }
        uriBuilder.path(assocKeyQuery);
      }
    }
    return doRequest(uriBuilder,
                     null,
                     responseEntity,
                     .,
                     method);
  }

  
Generate request-response pair with example data for action characterized by the specified specification

Parameters:
resourceSchema schema of the subject resource
actionSchema schema of the subject action
resourceLevel resource level of the action
spec specification of the generated example data
Returns:
request-response pair that captures the generated example data
                                                   ActionSchema actionSchema,
                                                   ResourceLevel resourceLevel,
                                                   RequestGenerationSpec spec)
  {
    final String templatePath;
    if (resourceLevel == .)
    {
      templatePath = resourceSchema.getPath();
    }
    else if (resourceLevel == .)
    {
      if (resourceSchema.hasSimple())
      {
        templatePath = resourceSchema.getPath();
      }
      else
      {
        templatePath = getEntityMethodPath(resourceSchema);
      }
    }
    else
    {
      templatePath = resourceSchema.getPath();
    }
    if (templatePath == null)
    {
      return null;
    }
    final ResourceModel model = .get(resourceSchema.getPath());
    final Map<StringStringuriTemplateExampleValues = getUriTemplateExampleValues(model);
    final UriBuilder uriBuilder = UriBuilder.fromPath(new UriTemplate(templatePath).createURI(uriTemplateExampleValues));
    uriBuilder.queryParam(.actionSchema.getName());
    // TODO OFFLINE RestLiResponseHandler requires RoutingResult, which requires ResourceMethodDescriptor.
    final ResourceMethodDescriptor method = model.findActionMethod(actionSchema.getName(), resourceLevel);
    final DataMap requestEntity = new DataMap();
    Object responseEntity = null;
    if (actionSchema.hasParameters())
    {
      for (ParameterSchema param : actionSchema.getParameters())
      {
        assert(!param.hasItems());
        final DataSchema typeSchema = RestSpecCodec.textToSchema(param.getType(), );
        final Object value = SchemaSampleDataGenerator.buildData(typeSchema);
        requestEntity.put(param.getName(), value);
      }
    }
    if (actionSchema.hasReturns())
    {
      final DataSchema returnsSchema = RestSpecCodec.textToSchema(actionSchema.getReturns(), );
      responseEntity = SchemaSampleDataGenerator.buildData(returnsSchema);
      final Class<?> returnsClass = method.getActionReturnType();
      if (DataTemplate.class.isAssignableFrom(returnsClass))
        responseEntity = DataTemplateUtil.wrap(responseEntityreturnsClass.asSubclass(DataTemplate.class));
    }
    return doRequest(uriBuilder,
                     requestEntity,
                     responseEntity,
                     .,
                     method);
  }
  private static <R extends RecordTemplate> R buildRecordTemplate(Class<R> recordClass)
  {
    return buildRecordTemplate(recordClass);
  }
  private static <R extends RecordTemplate> R buildRecordTemplate(Class<R> recordClass,
                                                                  SchemaSampleDataGenerator.DataGenerationOptions spec)
  {
    final DataSchema schema = DataTemplateUtil.getSchema(recordClass);
    if (schema == null || !(schema instanceof RecordDataSchema))
    {
      return null;
    }
    final DataMap data = SchemaSampleDataGenerator.buildRecordData((RecordDataSchemaschemaspec);
    return DataTemplateUtil.wrap(datarecordClass);
  }
  private static String getEntityMethodPath(ResourceSchema resourceSchema)
  {
    final CollectionSchema collection = resourceSchema.getCollection();
    final AssociationSchema association = resourceSchema.getAssociation();
    EntitySchema entity = null;
    if (collection != null)
    {
      entity = collection.getEntity();
    }
    else if (association != null)
    {
      entity = association.getEntity();
    }
    if (entity == null)
    {
      return null;
    }
    return entity.getPath();
  }
  private static <R extends RecordTemplateCollectionResult<R, ? extends RecordTemplate>
  buildFinderResponse(Class<R> valueClassClass<? extends RecordTemplatemetadataClass)
  {
    final List<R> results = new ArrayList<R>();
    final int count = (int)(Math.random() * 3) + 1;
    for (int i = 0; i < counti++)
    {
      final R item = buildRecordTemplate(valueClass);
      results.add(item);
    }
    RecordTemplate metadata = null;
    if (metadataClass != null && Math.random() > 0.5)
    {
      @SuppressWarnings("unchecked")
      final RecordTemplate newMetadata = buildRecordTemplate(metadataClass);
      metadata = newMetadata;
    }
    return new CollectionResult<R, RecordTemplate>(resultscountmetadata);
  }
  private static void writeEntity(Object entityMessageBuilder<?> messageBuilder)
  {
    if (entity == null)
    {
      return;
    }
    try
    {
      if (entity instanceof DataMap)
      {
        messageBuilder.setEntity(.mapToBytes((DataMapentity));
      }
      else
      {
        messageBuilder.setEntity(.dataTemplateToBytes((RecordTemplate)entitytrue));
      }
    }
    catch (IOException e)
    {
      throw new RestLiInternalException(e);
    }
  }
  @SuppressWarnings("unchecked")
  private <T> Class<T> getClass(String className)
  {
    try
    {
      return (Class<T>) .loadClass(className);
    }
    catch (ClassNotFoundException e)
    {
      throw new RestLiInternalException(String.format("Expected to find class in classpath: %s"className));
    }
  }

  
Generate map of URI template name to its example value. This map can be used to create concrete example URI from template.

Parameters:
model com.linkedin.restli.internal.server.model.ResourceModel of which the path is generated for
Returns:
Map of URI template name to its example value
  {
    final Map<StringStringexampleValues = new HashMap<StringString>();
    if (model != null)
    {
      if (model.getKeyKeyClass() == null)
      {
        for (Key keymodel.getKeys())
        {
          final DataSchema keySchema = key.getDataSchema();
          final Object exampleKey = SchemaSampleDataGenerator.buildData(keySchema);
          exampleValues.put(key.getName(), exampleKey.toString());
        }
      }
      else
      {
        final RecordTemplate exampleKeyKey = buildRecordTemplate(model.getKeyKeyClass());
        final RecordTemplate exampleKeyParams = buildRecordTemplate(model.getKeyParamsClass());
        final ComplexResourceKey<RecordTemplateRecordTemplatecomplexKey =
            new ComplexResourceKey<RecordTemplateRecordTemplate>(exampleKeyKeyexampleKeyParams);
        exampleValues.put(model.getKeyName(), complexKey.toStringFull());
      }
      exampleValues.putAll(getUriTemplateExampleValues(model.getParentResourceModel()));
    }
    return exampleValues;
  }
  private void buildSubModels(String schemaNamePrefixIterable<ResourceModelmodels)
  {
    for (ResourceModel modelmodels)
    {
      final String schemaName = schemaNamePrefix + "." + model.getName();
      final ResourceSchema schema = .getResource(schemaName);
      assert(schema != null);
      .put(schema.getPath(), model);
      buildSubModels(schemaNamemodel.getSubResources());
    }
  }
  {
    final DataMap queryParamData = new DataMap();
    for (ParameterSchema paramparams)
    {
      if (param.hasOptional() && param.isOptional() && !spec.includeOptionalParameters)
      {
        continue;
      }
      if (spec.useDefaultValues && param.hasDefault())
      {
        queryParamData.put(param.getName(), param.getDefault());
      }
      else if (param.hasItems())
      {
        final DataSchema itemsSchema = RestSpecCodec.textToSchema(param.getItems(), );
        final int valueCount = (int)(Math.random() * 3) + 1;
        final DataList arrayData = new DataList(valueCount);
        for (int i = 0; i < valueCount; ++i)
        {
          arrayData.add(SchemaSampleDataGenerator.buildData(itemsSchema));
        }
        queryParamData.put(param.getName(), arrayData);
      }
      else
      {
        final DataSchema typeSchema = RestSpecCodec.textToSchema(param.getType(), );
        queryParamData.put(param.getName(), SchemaSampleDataGenerator.buildData(typeSchema));
      }
    }
    return QueryParamsDataMap.queryString(queryParamData);
  }
  private void buildBatchRequestExampleUri(ResourceModel modelUriBuilder uriBuilder)
  {
    if (model.getKeyKeyClass() == null)
    {
      // non-complex key case
      for (int i = 0; i < ; ++i)
      {
        if (model.getKeyClass() == CompoundKey.class)
        {
          // compound key case
          final CompoundKey exampleCompoundKey = new CompoundKey();
          for (Key keymodel.getKeys())
          {
            final DataSchema keySchema = key.getDataSchema();
            final Object exampleKey = SchemaSampleDataGenerator.buildData(keySchema);
            exampleCompoundKey.append(key.getName(), exampleKey);
          }
          uriBuilder.queryParam(.exampleCompoundKey);
        }
        else
        {
          // single key case
          final DataSchema keySchema = model.getPrimaryKey().getDataSchema();
          final Object exampleKey = SchemaSampleDataGenerator.buildData(keySchema);
          uriBuilder.queryParam(.exampleKey);
        }
      }
    }
    else
    {
      // complex key case
      final DataList exampleList = new DataList();
      for (int i = 0; i < ; ++i)
      {
        final RecordTemplate exampleKeyKey = buildRecordTemplate(model.getKeyKeyClass());
        final RecordTemplate exampleKeyParams = buildRecordTemplate(model.getKeyParamsClass());
        final ComplexResourceKey<RecordTemplateRecordTemplatecomplexKey =
            new ComplexResourceKey<RecordTemplateRecordTemplate>(exampleKeyKeyexampleKeyParams);
        exampleList.add(complexKey.toDataMap());
      }
      final DataMap batchRequestParamData = new DataMap();
      batchRequestParamData.put(.exampleList);
      QueryParamsDataMap.addSortedParams(uriBuilderbatchRequestParamData);
    }
  }
  private void addAssocKeyToUri(AssocKeySchema assocKeyUriBuilder uriBuilder)
  {
    final DataSchema typeSchema = RestSpecCodec.textToSchema(assocKey.getType(), );
    final Object exampleValue = SchemaSampleDataGenerator.buildData(typeSchema);
    uriBuilder.queryParam(assocKey.getName(), exampleValue);
  }

  
  private RequestResponsePair doRequest(UriBuilder uriBuilder,
                                        Object requestEntity,
                                        Object responseEntity,
                                        HttpMethod httpMethod,
                                        ResourceMethodDescriptor method)
  {
    final RestRequestBuilder requestBuilder = new RestRequestBuilder(uriBuilder.build());
    requestBuilder.setMethod(httpMethod.name());
    writeEntity(requestEntityrequestBuilder);
    final RestRequest request = requestBuilder.build();
    final RestResponse response;
    try
    {
      final RoutingResult routingResult = new RoutingResult(new ResourceContextImpl(), method);
      response = .buildResponse(requestroutingResultresponseEntity);
    }
    catch (RestLiSyntaxException e)
    {
      throw new RestLiInternalException();
    }
    catch (IOException e)
    {
      throw new RestLiInternalException();
    }
    return new RequestResponsePair(requestresponse);
  }
  private static final int BATCH_REQUEST_EXAMPLE_COUNT = 2;
  private static final Set<ResourceMethodMETHODS_WITHOUT_PARAMS = new HashSet<ResourceMethod>();
  private static final Set<ResourceMethodBATCH_METHODS_WITH_PARAMS = new HashSet<ResourceMethod>();
  private static final JacksonDataTemplateCodec _codec = new JacksonDataTemplateCodec();
  static
  {
  }
  private final Map<StringResourceModel_allResources;
  private final ClassLoader _schemaClassLoader;
New to GrepCode? Check out our FAQ X