Add support for Apex API client (#5669)

* Salesforce Apex support

* typo in function name

* comments for clarification

* DoubleProperty and FloatProperty are both DecimalProperty

* test models with default and provided example property values

* adding some more default example values
This commit is contained in:
wing328 2017-05-19 23:18:52 +08:00 committed by GitHub
parent ef2028e53f
commit a0482a4038
28 changed files with 3563 additions and 0 deletions

View File

@ -0,0 +1,454 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Info;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
public class ApexClientCodegen extends AbstractJavaCodegen {
private static final String CLASS_PREFIX = "classPrefix";
private static final String API_VERSION = "apiVersion";
private static final Logger LOGGER = LoggerFactory.getLogger(ApexClientCodegen.class);
private String classPrefix = "Swag";
private String apiVersion = "36.0";
public ApexClientCodegen() {
super();
importMapping.clear();
embeddedTemplateDir = templateDir = "apex";
outputFolder = "generated-code" + File.separator + "apex";
testFolder = sourceFolder = "deploy";
apiPackage = "classes";
modelPackage = "classes";
testPackage = "deploy.classes";
modelNamePrefix = classPrefix;
dateLibrary = "";
apiTemplateFiles.put("api.mustache", ".cls");
apiTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
apiTestTemplateFiles.put("api_test.mustache", ".cls");
apiTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
modelTemplateFiles.put("model.mustache", ".cls");
modelTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
modelTestTemplateFiles.put("model_test.mustache", ".cls");
modelTestTemplateFiles.put("cls-meta.mustache", ".cls-meta.xml");
cliOptions.add(CliOption.newString(CLASS_PREFIX, "Prefix for generated classes. Set this to avoid overwriting existing classes in your org."));
cliOptions.add(CliOption.newString(API_VERSION, "The Metadata API version number to use for components in this package."));
supportingFiles.add(new SupportingFile("package.mustache", "deploy", "package.xml"));
supportingFiles.add(new SupportingFile("package.mustache", "undeploy", "destructiveChanges.xml"));
supportingFiles.add(new SupportingFile("build.mustache", "build.xml"));
supportingFiles.add(new SupportingFile("build.properties", "build.properties"));
supportingFiles.add(new SupportingFile("remove.package.mustache", "undeploy", "package.xml"));
supportingFiles.add(new SupportingFile("Swagger.cls", "deploy/classes", "Swagger.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "Swagger.cls-meta.xml"));
supportingFiles.add(new SupportingFile("SwaggerTest.cls", "deploy/classes", "SwaggerTest.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "SwaggerTest.cls-meta.xml"));
supportingFiles.add(new SupportingFile("SwaggerResponseMock.cls", "deploy/classes", "SwaggerResponseMock.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes", "SwaggerResponseMock.cls-meta.xml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "README.md"));
typeMapping.put("BigDecimal", "Double");
typeMapping.put("binary", "String");
typeMapping.put("ByteArray", "Blob");
typeMapping.put("date", "Date");
typeMapping.put("DateTime", "Datetime");
typeMapping.put("file", "Blob");
typeMapping.put("float", "Double");
typeMapping.put("number", "Double");
typeMapping.put("short", "Integer");
typeMapping.put("UUID", "String");
setReservedWordsLowerCase(
Arrays.asList("abstract", "activate", "and", "any", "array", "as", "asc", "autonomous",
"begin", "bigdecimal", "blob", "break", "bulk", "by", "byte", "case", "cast",
"catch", "char", "class", "collect", "commit", "const", "continue",
"convertcurrency", "date", "decimal", "default", "delete", "desc", "do", "else",
"end", "enum", "exception", "exit", "export", "extends", "false", "final",
"finally", "float", "for", "from", "future", "global", "goto", "group", "having",
"hint", "if", "implements", "import", "inner", "insert", "instanceof", "int",
"interface", "into", "join", "last_90_days", "last_month", "last_n_days",
"last_week", "like", "limit", "list", "long", "loop", "map", "merge", "new",
"next_90_days", "next_month", "next_n_days", "next_week", "not", "null", "nulls",
"number", "object", "of", "on", "or", "outer", "override", "package", "parallel",
"pragma", "private", "protected", "public", "retrieve", "return", "returning",
"rollback", "savepoint", "search", "select", "set", "short", "sort", "stat",
"static", "super", "switch", "synchronized", "system", "testmethod", "then", "this",
"this_month", "this_week", "throw", "today", "tolabel", "tomorrow", "transaction",
"trigger", "true", "try", "type", "undelete", "update", "upsert", "using",
"virtual", "webservice", "when", "where", "while", "yesterday"
));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("Blob", "Boolean", "Date", "Datetime", "Decimal", "Double", "ID",
"Integer", "Long", "Object", "String", "Time"
));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CLASS_PREFIX)) {
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
}
additionalProperties.put(CLASS_PREFIX, classPrefix);
if (additionalProperties.containsKey(API_VERSION)) {
setApiVersion(toApiVersion((String) additionalProperties.get(API_VERSION)));
}
additionalProperties.put(API_VERSION, apiVersion);
postProcessOpts();
}
@Override
public String escapeReservedWord(String name) {
// Identifiers must start with a letter
return "r" + super.escapeReservedWord(name);
}
@Override
public String toModelName(String name) {
String modelName = super.toModelName(name);
// Max length is 40; save the last 4 for "Test"
if (modelName.length() > 36) {
modelName = modelName.substring(0, 36);
}
return modelName;
}
@Override
public String toDefaultValue(Property p) {
String out = null;
if (p instanceof ArrayProperty) {
Property inner = ((ArrayProperty) p).getItems();
out = String.format(
"new List<%s>()",
inner == null ? "Object" : getTypeDeclaration(inner)
);
} else if (p instanceof BooleanProperty) {
// true => "true", false => "false", null => "null"
out = String.valueOf(((BooleanProperty) p).getDefault());
} else if (p instanceof LongProperty) {
Long def = ((LongProperty) p).getDefault();
out = def == null ? out : def.toString() + "L";
} else if (p instanceof MapProperty) {
Property inner = ((MapProperty) p).getAdditionalProperties();
String s = inner == null ? "Object" : getTypeDeclaration(inner);
out = String.format("new Map<String, %s>()", s);
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
String def = sp.getDefault();
if (def != null) {
out = sp.getEnum() == null ? String.format("'%s'", escapeText(def)) : def;
}
} else {
out = super.toDefaultValue(p);
}
// we'll skip over null defaults in the model template to avoid redundant initialization
return "null".equals(out) ? null : out;
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
if (Boolean.TRUE.equals(p.isLong)) {
p.example = "2147483648L";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "Blob.valueOf('Sample text file\\nContents')";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "Date.newInstance(1960, 2, 17)";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
p.example = "Datetime.newInstanceGmt(2013, 11, 12, 3, 3, 3)";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
p.example = "new " + p.dataType + "{" + p.items.example + "}";
} else if (Boolean.TRUE.equals(p.isString)) {
p.example = "'" + p.example + "'";
} else if ("".equals(p.example) || p.example == null) {
// Get an example object from the generated model
p.example = p.dataType + ".getExample()";
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel cm = super.fromModel(name, model, allDefinitions);
if (cm.interfaces == null) {
cm.interfaces = new ArrayList<String>();
}
Boolean hasDefaultValues = false;
// for (de)serializing properties renamed for Apex (e.g. reserved words)
List<Map<String, String>> propertyMappings = new ArrayList<>();
for (CodegenProperty p : cm.allVars) {
hasDefaultValues |= p.defaultValue != null;
if (!p.baseName.equals(p.name)) {
Map<String, String> mapping = new HashMap<>();
mapping.put("externalName", p.baseName);
mapping.put("internalName", p.name);
propertyMappings.add(mapping);
}
}
cm.vendorExtensions.put("hasPropertyMappings", !propertyMappings.isEmpty());
cm.vendorExtensions.put("hasDefaultValues", hasDefaultValues);
cm.vendorExtensions.put("propertyMappings", propertyMappings);
if (!propertyMappings.isEmpty()) {
cm.interfaces.add("Swagger.MappedProperties");
}
return cm;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
if (parameter.isBodyParam && parameter.isListContainer) {
// items of array bodyParams are being nested an extra level too deep for some reason
parameter.items = parameter.items.items;
setParameterExampleValue(parameter);
}
}
@Override
public void preprocessSwagger(Swagger swagger) {
Info info = swagger.getInfo();
String description = info.getDescription();
String sanitized = sanitizeName(info.getTitle());
additionalProperties.put("sanitizedName", sanitized);
supportingFiles.add(new SupportingFile("remoteSite.mustache", "deploy/remoteSiteSettings",
sanitized + ".remoteSite"
));
// max length for description for a Remote Site setting
if (description != null && description.length() > 255) {
description = description.substring(0, 255);
}
additionalProperties.put("shortDescription", description);
}
@Override
public CodegenOperation fromOperation(String path,
String httpMethod,
Operation operation,
Map<String, Model> definitions,
Swagger swagger) {
Boolean hasFormParams = false;
for (Parameter p : operation.getParameters()) {
if ("formData".equals(p.getIn())) {
hasFormParams = true;
break;
}
}
// only support serialization into JSON and urlencoded forms for now
operation.setConsumes(
Collections.singletonList(hasFormParams
? "application/x-www-form-urlencoded"
: "application/json"));
// only support deserialization from JSON for now
operation.setProduces(Collections.singletonList("application/json"));
CodegenOperation op = super.fromOperation(
path, httpMethod, operation, definitions, swagger);
if (op.getHasExamples()) {
// prepare examples for Apex test classes
Property responseProperty = findMethodResponse(operation.getResponses()).getSchema();
String deserializedExample = toExampleValue(responseProperty);
for (Map<String, String> example : op.examples) {
example.put("example", escapeText(example.get("example")));
example.put("deserializedExample", deserializedExample);
}
}
return op;
}
@Override
public String escapeQuotationMark(String input) {
return input.replace("'", "\\'");
}
public void setClassPrefix(String classPrefix) {
// the best thing we can do without namespacing in Apex
modelNamePrefix = classPrefix;
this.classPrefix = classPrefix;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
private String toApiVersion(String apiVersion) {
if (apiVersion.matches("^\\d{2}(\\.0)?$")) {
return apiVersion.substring(0, 2) + ".0";
} else {
LOGGER.warn(String.format("specified API version is invalid: %s - defaulting to %s", apiVersion, this.apiVersion));
return this.apiVersion;
}
}
private void postProcessOpts() {
supportingFiles.add(
new SupportingFile("client.mustache", "deploy/classes", classPrefix + "Client.cls"));
supportingFiles.add(new SupportingFile("cls-meta.mustache", "deploy/classes",
classPrefix + "Client.cls-meta.xml"
));
}
@Override
public String escapeText(String input) {
if (input == null) {
return input;
}
return input.replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r");
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + "Test";
}
@Override
public String toExampleValue(Property p) {
if (p == null) {
return "";
}
Object obj = p.getExample();
String example = obj == null ? "" : obj.toString();
if (p instanceof ArrayProperty) {
example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
((ArrayProperty) p).getItems()) + "}";
} else if (p instanceof BooleanProperty) {
example = String.valueOf(!"false".equals(example));
} else if (p instanceof ByteArrayProperty) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
}
((ByteArrayProperty) p).setExample(example);
example = "EncodingUtil.base64Decode('" + example + "')";
} else if (p instanceof DateProperty) {
if (example.matches("^\\d{4}(-\\d{2}){2}")) {
example = example.substring(0, 10).replaceAll("-0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p
.getName(), example));
example = "2000, 1, 23";
}
example = "Date.newInstance(" + example + ")";
} else if (p instanceof DateTimeProperty) {
if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
} else if (example.isEmpty()) {
example = "2000, 1, 23, 4, 56, 7";
} else {
LOGGER.warn(String.format("The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p
.getName(), example));
example = "2000, 1, 23, 4, 56, 7";
}
example = "Datetime.newInstanceGmt(" + example + ")";
} else if (p instanceof DecimalProperty) {
example = example.replaceAll("[^-0-9.]", "");
example = example.isEmpty() ? "1.3579" : example;
} else if (p instanceof FileProperty) {
if (example.isEmpty()) {
example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
((FileProperty) p).setExample(example);
}
example = "EncodingUtil.base64Decode(" + example + ")";
} else if (p instanceof EmailProperty) {
if (example.isEmpty()) {
example = "example@example.com";
((EmailProperty) p).setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof LongProperty) {
example = example.isEmpty() ? "123456789L" : example + "L";
} else if (p instanceof MapProperty) {
example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(
((MapProperty) p).getAdditionalProperties()) + "}";
} else if (p instanceof ObjectProperty) {
example = example.isEmpty() ? "null" : example;
} else if (p instanceof PasswordProperty) {
example = example.isEmpty() ? "password123" : escapeText(example);
((PasswordProperty) p).setExample(example);
example = "'" + example + "'";
} else if (p instanceof RefProperty) {
example = getTypeDeclaration(p) + ".getExample()";
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
List<String> enums = sp.getEnum();
if (enums != null && example.isEmpty()) {
example = enums.get(0);
sp.setExample(example);
} else if (example.isEmpty()) {
example = "aeiou";
} else {
example = escapeText(example);
sp.setExample(example);
}
example = "'" + example + "'";
} else if (p instanceof UUIDProperty) {
example = example.isEmpty()
? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
: "'" + escapeText(example) + "'";
} else if (p instanceof BaseIntegerProperty) {
example = example.matches("^-?\\d+$") ? example : "123";
}
return example;
}
@Override
public String toApiName(String name) {
return camelize(classPrefix + super.toApiName(name));
}
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
super.updateCodegenPropertyEnum(var);
if (var.isEnum && var.example != null) {
String example = var.example.replace("'", "");
example = toEnumVarName(example, var.datatype);
var.example = toEnumDefaultValue(example, var.datatypeWithEnum);
}
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "apex";
}
@Override
public String getHelp() {
return "Generates an Apex client library.";
}
}

View File

@ -1,4 +1,5 @@
io.swagger.codegen.languages.AndroidClientCodegen
io.swagger.codegen.languages.ApexClientCodegen
io.swagger.codegen.languages.AspNet5ServerCodegen
io.swagger.codegen.languages.AspNetCoreServerCodegen
io.swagger.codegen.languages.AsyncScalaClientCodegen

View File

@ -0,0 +1,182 @@
# {{appName}} API Client
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## Requirements
- [Java 8 JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html)
- [Apache Ant](http://ant.apache.org/) version 1.6 or later
- [Force.com Migration Tool](https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_install.htm)
- The `ant-salesforce.jar` file included with the Force.com Migration Tool must be placed in the root directory of this project (in the same directory as this README and `build.xml`)
- `ANT_HOME` and `JAVA_HOME` environment variables must be set accordingly
- On Windows, `JAVA_HOME` will probably look something like this:
```
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_121
```
- The `bin` directory from Ant must be on your `PATH`
If everything is set correctly:
- Running `java -version` in a command prompt should output something like:
```bash
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
```
- Running `ant -version` should output something like:
```bash
Apache Ant(TM) version 1.10.1 compiled on February 2 2017
```
For more information, see <https://developer.salesforce.com/docs/atlas.en-us.daas.meta/daas/forcemigrationtool_prereq.htm>
## Installation
{{#gitRepoId}}{{#gitUserId}}
1. Clone the repo from GitHub
```bash
$ git clone git@github.com:{{gitUserId}}/{{gitRepoId}}.git
```
Or, [download](https://github.com/{{gitUserId}}/{{gitRepoId}}/archive/master.zip) the repo as a ZIP and extract it to `{{gitRepoId}}`
{{/gitUserId}}{{/gitRepoId}}
1. Set the `SF_USERNAME` and `SF_PASSWORD` environment variables to your Salesforce username and password. Alternatively, they may be set in `build.properties`. Environment variables will override the values in `build.properties` if set.
`SF_SESSIONID` may also be set instead of `SF_USERNAME` and `SF_PASSWORD` (more info in `build.properties`)
2. Open up a command prompt in the root project directory {{#gitRepoId}}`{{gitRepoId}}` {{/gitRepoId}}(the same directory as this README and `build.xml`)
3. Deploy to your Salesforce org
```bash
$ ant deploy
```
This command will:
- deploy all classes in the `deploy/classes` directory to your Salesforce org
- create a new [unmanaged package](https://help.salesforce.com/articleView?id=sharing_apps.htm) called **{{appName}} API Client**
- execute all of the unit tests included in this package (at least 75% code coverage required)
- create a new [remote site](https://help.salesforce.com/articleView?id=configuring_remoteproxy.htm) called **{{sanitizedName}}** configured for the endpoint: <{{basePath}}>
- rolls back any changes upon any error
A successful deployment will look like this:
```bash
[sf:deploy] Request Status: Succeeded
[sf:deploy] *********** DEPLOYMENT SUCCEEDED ***********
[sf:deploy] Finished request 0Af7A00000Ebd5oSAB successfully.
BUILD SUCCESSFUL
Total time: 34 seconds
```
### Test deployment only
To perform a test deployment without committing changes:
```bash
$ ant deployCheckOnly
```
All of the included tests will run as if it were a real deployment. Tests and other validations will report back while leaving your org untouched, allowing you to verify that a deployment will succeed without affecting anything in the org.
### Uninstallation
```bash
$ ant undeploy
```
Removes all classes and the Remote Site created by this package.
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Apex code:
```java{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
{{classname}} api = new {{classname}}();
{{#hasAuthMethods}}
{{classPrefix}}Client client = api.getClient();
{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setUsername('YOUR USERNAME');
{{{name}}}.setPassword('YOUR PASSWORD');
// You can also set your username and password in one line
{{{name}}}.setCredentials('YOUR USERNAME', 'YOUR PASSWORD');{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setApiKey('YOUR API KEY');{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Swagger.OAuth {{{name}}} = (Swagger.OAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setAccessToken('YOUR ACCESS TOKEN');{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{{paramName}}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
try {
// cross your fingers
{{#returnType}}{{{returnType}}} result = {{/returnType}}api.{{{operationId}}}({{#hasParams}}params{{/hasParams}});
{{#returnType}}
System.debug(result);
{{/returnType}}
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
{{/authMethods}}Authentication schemes defined for the API:
{{#authMethods}}### {{name}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorizatoin URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -0,0 +1,395 @@
public class Swagger {
private static final String HEADER_CONTENT_TYPE = 'Content-Type';
private static final String HEADER_ACCEPT = 'Accept';
private static final String HEADER_ACCEPT_DELIMITER = ',';
private static final Map<String, String> DELIMITERS = new Map<String, String> {
'csv' => ',',
'ssv' => ' ',
'tsv' => '\t',
'pipes' => '|'
};
public class Param {
private String name, value;
public Param(String name, String value) {
this.name = name;
this.value = value;
}
public override String toString() {
return EncodingUtil.urlEncode(name, 'UTF-8') + '='
+ EncodingUtil.urlEncode(value, 'UTF-8');
}
}
public interface Authentication {
void apply(Map<String, Object> headers, List<Param> query);
}
public interface MappedProperties {
Map<String, String> getPropertyMappings();
}
public abstract class ApiKeyAuth implements Authentication {
protected final String paramName;
protected String key = '';
public void setApiKey(String key) {
this.key = key;
}
@TestVisible
private String getApiKey() {
return key;
}
}
public class ApiKeyQueryAuth extends ApiKeyAuth {
public ApiKeyQueryAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
query.add(new Param(paramName, key));
}
}
public class ApiKeyHeaderAuth extends ApiKeyAuth {
public ApiKeyHeaderAuth(String paramName) {
this.paramName = paramName;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put(paramName, key);
}
}
public class HttpBasicAuth implements Authentication {
private String username = '';
private String password = '';
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setCredentials(String username, String password) {
setUsername(username);
setPassword(password);
}
@TestVisible
private String getHeaderValue() {
return 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' + password));
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class OAuth2 implements Authentication {
private String accessToken = '';
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@TestVisible
private String getHeaderValue() {
return 'Bearer ' + accessToken;
}
public void apply(Map<String, Object> headers, List<Param> query) {
headers.put('Authorization', getHeaderValue());
}
}
public class ApiException extends Exception {
private final Integer code;
private final String status;
private final Map<String, String> headers;
private final String body;
public ApiException(Integer code, String status, Map<String, String> headers, String body) {
this('API returned HTTP ' + code + ': ' + status);
this.code = code;
this.status = status;
this.headers = headers;
this.body = body;
}
public Integer getStatusCode() {
return code;
}
public String getStatus() {
return status;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}
public virtual class ApiClient {
protected String preferredContentType = 'application/json';
protected String preferredAccept = 'application/json';
protected final String basePath;
@TestVisible
protected final Map<String, Authentication> authentications = new Map<String, Authentication>();
public virtual Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
public virtual void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setCredentials(String username, String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setCredentials(username, password);
return;
}
}
throw new NoSuchElementException('No HTTP basic authentication configured!');
}
public virtual void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new NoSuchElementException('No API key authentication configured!');
}
public virtual void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth2) {
((OAuth2) auth).setAccessToken(accessToken);
return;
}
}
throw new NoSuchElementException('No OAuth2 authentication configured!');
}
public List<Param> makeParams(String name, List<Object> values) {
List<Param> pairs = new List<Param>();
for (Object value : new List<Object>(values)) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public List<Param> makeParam(String name, List<Object> values, String format) {
List<Param> pairs = new List<Param>();
if (values != null) {
String delimiter = DELIMITERS.get(format);
pairs.add(new Param(name, String.join(values, delimiter)));
}
return pairs;
}
public List<Param> makeParam(String name, Object value) {
List<Param> pairs = new List<Param>();
if (value != null) {
pairs.add(new Param(name, String.valueOf(value)));
}
return pairs;
}
public virtual void assertNotNull(Object required, String parameterName) {
if (required == null) {
Exception e = new NullPointerException();
e.setMessage('Argument cannot be null: ' + parameterName);
throw e;
}
}
public virtual Object invoke(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods, Type returnType) {
HttpResponse res = getResponse(method, path, body, query, form, pathParams, headers,
accepts, contentTypes, authMethods);
Integer code = res.getStatusCode();
Boolean isFailure = code / 100 != 2;
if (isFailure) {
throw new ApiException(code, res.getStatus(), getHeaders(res), res.getBody());
} else if (returnType != null) {
return toReturnValue(res.getBody(), returnType, res.getHeader('Content-Type'));
}
return null;
}
@TestVisible
protected virtual Map<String, String> getHeaders(HttpResponse res) {
Map<String, String> headers = new Map<String, String>();
List<String> headerKeys = res.getHeaderKeys();
for (String headerKey : headerKeys) {
headers.put(headerKey, res.getHeader(headerKey));
}
return headers;
}
@TestVisible
protected virtual Object toReturnValue(String body, Type returnType, String contentType) {
if (contentType == 'application/json') {
Object o = returnType.newInstance();
if (o instanceof MappedProperties) {
Map<String, String> propertyMappings = ((MappedProperties) o).getPropertyMappings();
for (String baseName : propertyMappings.keySet()) {
body = body.replaceAll('"' + baseName + '"\\s*:',
'"' + propertyMappings.get(baseName) + '":');
}
}
JsonParser parser = Json.createParser(body);
parser.nextToken();
return parser.readValueAs(returnType);
}
return body;
}
@TestVisible
protected virtual HttpResponse getResponse(
String method, String path, Object body, List<Param> query, List<Param> form,
Map<String, Object> pathParams, Map<String, Object> headers, List<String> accepts,
List<String> contentTypes, List<String> authMethods) {
HttpRequest req = new HttpRequest();
applyAuthentication(authMethods, headers, query);
req.setMethod(method);
req.setEndpoint(toEndpoint(path, pathParams, query));
String contentType = setContentTypeHeader(contentTypes, headers);
setAcceptHeader(accepts, headers);
setHeaders(req, headers);
if (method != 'GET') {
req.setBody(toBody(contentType, body, form));
}
return new Http().send(req);
}
@TestVisible
protected virtual void setHeaders(HttpRequest req, Map<String, Object> headers) {
for (String headerName : headers.keySet()) {
req.setHeader(headerName, String.valueOf(headers.get(headerName)));
}
}
@TestVisible
protected virtual String toBody(String contentType, Object body, List<Param> form) {
if (contentType.contains('application/x-www-form-urlencoded')) {
return paramsToString(form);
} else if (contentType.contains('application/json')) {
return Json.serialize(body);
}
return String.valueOf(body);
}
@TestVisible
protected virtual String setContentTypeHeader(List<String> contentTypes,
Map<String, Object> headers) {
if (contentTypes.isEmpty()) {
headers.put(HEADER_CONTENT_TYPE, preferredContentType);
return preferredContentType;
}
for (String contentType : contentTypes) {
if (preferredContentType == contentType) {
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
}
String contentType = contentTypes.get(0);
headers.put(HEADER_CONTENT_TYPE, contentType);
return contentType;
}
@TestVisible
protected virtual void setAcceptHeader(List<String> accepts, Map<String, Object> headers) {
for (String accept : accepts) {
if (preferredAccept == accept) {
headers.put(HEADER_ACCEPT, accept);
return;
}
}
if (!accepts.isEmpty()) {
headers.put(HEADER_ACCEPT, String.join(accepts, HEADER_ACCEPT_DELIMITER));
}
}
@TestVisible
protected virtual void applyAuthentication(List<String> names, Map<String, Object> headers,
List<Param> query) {
for (Authentication auth : getAuthMethods(names)) {
auth.apply(headers, query);
}
}
@TestVisible
protected virtual List<Authentication> getAuthMethods(List<String> names) {
List<Authentication> authMethods = new List<Authentication>();
for (String name : names) {
authMethods.add(authentications.get(name));
}
return authMethods;
}
@TestVisible
protected virtual String toPath(String path, Map<String, Object> params) {
String formatted = path;
for (String key : params.keySet()) {
formatted = formatted.replace('{' + key + '}', String.valueOf(params.get(key)));
}
return formatted;
}
@TestVisible
protected virtual String toEndpoint(String path, Map<String, Object> params,
List<Param> queryParams) {
String query = '?' + paramsToString(queryParams);
return basePath + toPath(path, params) + query.removeEnd('?');
}
@TestVisible
protected virtual String paramsToString(List<Param> params) {
String s = '';
for (Param p : params) {
s += '&' + p;
}
return s.removeStart('&');
}
}
}

View File

@ -0,0 +1,18 @@
@isTest
public class SwaggerResponseMock implements HttpCalloutMock {
private final HttpResponse response;
private HttpRequest request;
public SwaggerResponseMock(HttpResponse response) {
this.response = response;
}
public HttpResponse respond(HttpRequest request) {
this.request = request;
return response;
}
public HttpRequest getRequest() {
return request;
}
}

View File

@ -0,0 +1,782 @@
@isTest
private class SwaggerTest {
@isTest
private static void Param_urlEncodeKeyValuePairUtf8() {
String toEncodeLeft = 'Hello +%-_.!~*\'()@';
String toEncodeRight = 'World +%-_.!~*\'()@';
String expected = 'Hello+%2B%25-_.%21%7E*%27%28%29%40=World+%2B%25-_.%21%7E*%27%28%29%40';
String result = new Swagger.Param(toEncodeLeft, toEncodeRight).toString();
System.assertEquals(expected, result);
}
@isTest
private static void ApiKeyHeaderAuth_keyInHeaderWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyHeaderAuth auth = new Swagger.ApiKeyHeaderAuth('X-Authenticate');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authenticate'));
}
@isTest
private static void ApiKeyQueryAuth_keyInQueryParamWithGivenName() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.ApiKeyQueryAuth auth = new Swagger.ApiKeyQueryAuth('auth_token');
auth.setApiKey('foo-bar-api-key');
auth.apply(headers, query);
System.assert(headers.isEmpty());
System.assertEquals(1, query.size());
System.assertEquals('auth_token=foo-bar-api-key', query.get(0).toString());
}
@isTest
private static void HttpBasicAuth_base64EncodeCredentials() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setCredentials('username', 'password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void HttpBasicAuth_base64EncodeUsernamePassword() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.HttpBasicAuth auth = new Swagger.HttpBasicAuth();
auth.setUsername('username');
auth.setPassword('password');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', headers.get('Authorization'));
}
@isTest
private static void OAuth2_tokenInAuthorizationHeaderWithBearerPrefix() {
Map<String, Object> headers = new Map<String, String>();
List<Swagger.Param> query = new List<Swagger.Param>();
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-api-key');
auth.apply(headers, query);
System.assert(query.isEmpty());
System.assertEquals(1, headers.size());
System.assertEquals('Bearer foo-bar-api-key', headers.get('Authorization'));
}
@isTest
private static void ApiClient_returnAuthenticationMatchingInput() {
MockApiClient client = new MockApiClient();
Swagger.ApiKeyHeaderAuth auth1 = new Swagger.ApiKeyHeaderAuth('foo');
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('foo');
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
System.assertEquals(auth1, client.getAuthentication('auth1'));
System.assertEquals(auth2, client.getAuthentication('auth2'));
System.assertEquals(auth3, client.getAuthentication('auth3'));
System.assertEquals(auth4, client.getAuthentication('auth4'));
}
@isTest
private static void ApiClient_noAuthenticationsMatchInputReturnNull() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth = new Swagger.OAuth2();
client.authentications.put('auth', auth);
System.assertEquals(auth, client.getAuthentication('auth'));
System.assertEquals(null, client.getAuthentication('no-auth'));
}
@isTest
private static void ApiClient_setUsernamePasswordFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setUsername('username');
client.setPassword('password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setUsernameExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setUsername('username');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setPasswordExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setPassword('password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setCredentialsFirstBasicAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.HttpBasicAuth auth4 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth5 = new Swagger.HttpBasicAuth();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setCredentials('username', 'password');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Basic dXNlcm5hbWU6cGFzc3dvcmQ=', auth4.getHeaderValue());
System.assertEquals('Basic Og==', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setCredentialsExceptionNoBasicAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setCredentials('username', 'password');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setApiKeyFirstKeyAuthOnly() {
MockApiClient client = new MockApiClient();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.HttpBasicAuth auth2 = new Swagger.HttpBasicAuth();
Swagger.HttpBasicAuth auth3 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth4 = new Swagger.ApiKeyQueryAuth('auth4');
Swagger.ApiKeyHeaderAuth auth5 = new Swagger.ApiKeyHeaderAuth('auth5');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setApiKey('foo-bar-api-key');
System.assertEquals('Bearer ', auth1.getHeaderValue());
System.assertEquals('Basic Og==', auth2.getHeaderValue());
System.assertEquals('Basic Og==', auth3.getHeaderValue());
System.assertEquals('foo-bar-api-key', auth4.getApiKey());
System.assertEquals('', auth5.getApiKey());
}
@isTest
private static void ApiClient_setApiKeyExceptionNoKeyAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setApiKey('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_setAccessTokenFirstOauthOnly() {
MockApiClient client = new MockApiClient();
Swagger.HttpBasicAuth auth1 = new Swagger.HttpBasicAuth();
Swagger.ApiKeyQueryAuth auth2 = new Swagger.ApiKeyQueryAuth('auth2');
Swagger.ApiKeyHeaderAuth auth3 = new Swagger.ApiKeyHeaderAuth('auth3');
Swagger.OAuth2 auth4 = new Swagger.OAuth2();
Swagger.OAuth2 auth5 = new Swagger.OAuth2();
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.authentications.put('auth3', auth3);
client.authentications.put('auth4', auth4);
client.authentications.put('auth5', auth5);
client.setAccessToken('foo-bar-api-key');
System.assertEquals('Basic Og==', auth1.getHeaderValue());
System.assertEquals('', auth2.getApiKey());
System.assertEquals('', auth3.getApiKey());
System.assertEquals('Bearer foo-bar-api-key', auth4.getHeaderValue());
System.assertEquals('Bearer ', auth5.getHeaderValue());
}
@isTest
private static void ApiClient_setAccessTokenExceptionNoOAuth() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.setAccessToken('foo-bar-api-key');
} catch (NoSuchElementException e) {
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_oneKeyValuePairForEachValueInList() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', values);
System.assertEquals(5, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=4', params.get(1).toString());
System.assertEquals('foo=false', params.get(2).toString());
System.assertEquals('foo=12.4', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
}
@isTest
private static void ApiClient_nullMultiValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParams('foo', null);
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_valuesListToSingleCsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'csv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%2C4%2Cfalse%2C12.4%2C', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleSsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'ssv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar+4+false+12.4+', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSingleTsvKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'tsv');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%094%09false%0912.4%09', params.get(0).toString());
}
@isTest
private static void ApiClient_valuesListToSinglePipeSeparatedKeyValuePair() {
List<Object> values = new List<Object>{'bar', 4, false, 12.4, ''};
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', values, 'pipes');
System.assertEquals(1, params.size());
System.assertEquals('foo=bar%7C4%7Cfalse%7C12.4%7C', params.get(0).toString());
}
@isTest
private static void ApiClient_nullValuesListToEmptyParamsList() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = client.makeParam('foo', null, 'csv');
System.assert(params.isEmpty());
}
@isTest
private static void ApiClient_paramsFromAnyPrimitiveTypeDiscardNull() {
Swagger.ApiClient client = new Swagger.ApiClient();
List<Swagger.Param> params = new List<Swagger.Param>();
params.addAll(client.makeParam('foo', 'bar'));
params.addAll(client.makeParam('foo', 10));
params.addAll(client.makeParam('foo', 12.6));
params.addAll(client.makeParam('foo', true));
params.addAll(client.makeParam('foo', ''));
params.addAll(client.makeParam('foo', Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0)));
params.addAll(client.makeParam('foo', null));
System.assertEquals(6, params.size());
System.assertEquals('foo=bar', params.get(0).toString());
System.assertEquals('foo=10', params.get(1).toString());
System.assertEquals('foo=12.6', params.get(2).toString());
System.assertEquals('foo=true', params.get(3).toString());
System.assertEquals('foo=', params.get(4).toString());
System.assertEquals('foo=2017-01-01+15%3A00%3A00', params.get(5).toString());
}
@isTest
private static void ApiClient_requiredParameterPasses() {
Swagger.ApiClient client = new Swagger.ApiClient();
client.assertNotNull('foo', 'bar');
}
@isTest
private static void ApiClient_requiredParameterFails() {
Swagger.ApiClient client = new Swagger.ApiClient();
try {
client.assertNotNull(null, 'bar');
} catch (NullPointerException e) {
System.assertEquals('Argument cannot be null: bar', e.getMessage());
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_extractHeadersFromResponse() {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'private, max-age=0');
Map<String, String> headers = new MockApiClient().getHeaders(res);
System.assertEquals(2, headers.size());
System.assertEquals('application/json', headers.get('Content-Type'));
System.assertEquals('private, max-age=0', headers.get('Cache-Control'));
}
@isTest
private static void ApiClient_deserializeResponseBodyByContentType() {
MockApiClient client = new MockApiClient();
String jsonBody = '{"red":"apple","yellow":"banana","orange":"orange"}';
Map<String, String> result1 = (Map<String, String>) client
.toReturnValue(jsonBody, Map<String, String>.class, 'application/json');
System.assertEquals(3, result1.size());
System.assertEquals('apple', result1.get('red'));
System.assertEquals('banana', result1.get('yellow'));
System.assertEquals('orange', result1.get('orange'));
String result2 = (String) client
.toReturnValue('Hello, World!', String.class, 'text/plain');
System.assertEquals('Hello, World!', result2);
}
@isTest
private static void ApiClient_addStringifiedHeadersToRequest() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>{
'Content-Type' => 'application/json',
'Max-Forwards' => 10
};
HttpRequest req = new HttpRequest();
client.setHeaders(req, headers);
System.assertEquals('application/json', req.getHeader('Content-Type'));
System.assertEquals('10', req.getHeader('Max-Forwards'));
}
@isTest
private static void ApiClient_serializeRequestBodyOrFormByContentType() {
MockApiClient client = new MockApiClient();
Map<String, Object> body1 = new Map<String, Object>{
'hello' => 'world',
'foo' => 15,
'bar' => Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0),
'bat' => false
};
Set<String> expected1 = new Set<String>{
'"hello":"world"',
'"foo":15',
'"bar":"2017-01-01T15:00:00.000Z"',
'"bat":false'
};
Set<String> actual1 = new Set<String>(client
.toBody('application/json', body1, new List<Swagger.Param>())
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(expected1, actual1);
String body2 = 'Hello, World!';
String actual2 = client.toBody('text/plain', body2, new List<Swagger.Param>());
System.assertEquals(body2, actual2);
List<Swagger.Param> form = new List<Swagger.Param>{
new Swagger.Param('hello', 'world'),
new Swagger.Param('date', '2017-01-01 15:00:00')
};
String expected3 = 'hello=world&date=2017-01-01+15%3A00%3A00';
String actual3 = client.toBody('application/x-www-form-urlencoded', '', form);
System.assertEquals(expected3, actual3);
}
@isTest
private static void ApiClient_usePreferredContentTypeOrFirstInList() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
String result1 = client.setContentTypeHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Content-Type'));
System.assertEquals('application/json', result1);
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
String result2 = client.setContentTypeHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml', headers2.get('Content-Type'));
System.assertEquals('application/xml', result2);
Map<String, Object> headers3 = new Map<String, Object>();
String result3 = client.setContentTypeHeader(new List<String>(), headers3);
System.assertEquals(1, headers3.size());
System.assertEquals('application/json', headers3.get('Content-Type'));
System.assertEquals('application/json', result3);
}
@isTest
private static void ApiClient_usePreferredAcceptOrAllInListNoDefault() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers1 = new Map<String, Object>();
List<String> types1 = new List<String>{'application/xml', 'application/json', 'text/plain'};
client.setAcceptHeader(types1, headers1);
System.assertEquals(1, headers1.size());
System.assertEquals('application/json', headers1.get('Accept'));
Map<String, Object> headers2 = new Map<String, Object>();
List<String> types2 = new List<String>{'application/xml', 'text/plain'};
client.setAcceptHeader(types2, headers2);
System.assertEquals(1, headers2.size());
System.assertEquals('application/xml,text/plain', headers2.get('Accept'));
Map<String, Object> headers3 = new Map<String, Object>();
client.setAcceptHeader(new List<String>(), headers3);
System.assert(headers3.isEmpty());
}
@isTest
private static void ApiClient_applyOnlyGivenAuthMethodsToParams() {
MockApiClient client = new MockApiClient();
Map<String, Object> headers = new Map<String, Object>();
Swagger.OAuth2 auth1 = new Swagger.OAuth2();
Swagger.ApiKeyHeaderAuth auth2 = new Swagger.ApiKeyHeaderAuth('X-Authentication-Token');
auth1.setAccessToken('boo-bat-api-key');
auth2.setApiKey('foo-bar-api-key');
client.authentications.put('auth1', auth1);
client.authentications.put('auth2', auth2);
client.applyAuthentication(new List<String>{'auth2'}, headers, new List<Swagger.Param>());
System.assertEquals(1, headers.size());
System.assertEquals('foo-bar-api-key', headers.get('X-Authentication-Token'));
}
@isTest
private static void ApiClient_formUrlWithQueryParamsPathParams() {
MockApiClient client = new MockApiClient();
String path = '/departments/{department}';
Map<String, Object> params = new Map<String, Object>{'department' => 'finance'};
List<Swagger.Param> queryParams = new List<Swagger.Param>{
new Swagger.Param('foo', 'bar'),
new Swagger.Param('bat', '123')
};
String expected = 'https://www.mccombs.utexas.edu/departments/finance?foo=bar&bat=123';
String actual = client.toEndpoint(path, params, queryParams);
System.assertEquals(expected, actual);
}
@isTest
private static void ApiClient_setupRequestWithBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}',
new Map<String, Object> {
'title' => 'Chapter 4 quiz',
'timed' => true,
'time' => 60,
'points' => 20.5,
'due' => Datetime.newInstanceGmt(2016, 5, 10, 23, 59, 59),
'description' => ''
},
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'application/json', 'application/xml'},
new List<String>{'application/json', 'application/xml'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req
.getBody()
.removeStart('{')
.removeEnd('}')
.split(',')
);
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('"title":"Chapter 4 quiz"'));
System.assert(body.contains('"timed":true'));
System.assert(body.contains('"time":60'));
System.assert(body.contains('"points":20.5'));
System.assert(body.contains('"due":"2016-05-10T23:59:59.000Z"'));
System.assert(body.contains('"description":""'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('application/json', req.getHeader('Accept'));
System.assertEquals('application/json', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithForm() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'PUT', '/courses/{course}/assignments/{assignmentId}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>{
new Swagger.Param('title', 'Chapter 4 quiz'),
new Swagger.Param('timed', 'true'),
new Swagger.Param('time', '60'),
new Swagger.Param('points', '20.5'),
new Swagger.Param('due', '2016-05-10 18:59:59'),
new Swagger.Param('description', 'complete & upload \'section1: advanced\'')
},
new Map<String, Object>{
'course' => 'acc321',
'assignmentId' => 5
},
new Map<String, Object>{
'X-Session' => 'foo-bar-444'
},
new List<String>{'text/html', 'application/xml'},
new List<String>{'application/x-www-form-urlencoded'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5';
Set<String> body = new Set<String>(req.getBody().split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, req.getEndpoint());
System.assertEquals(6, body.size());
System.assert(body.contains('title=Chapter+4+quiz'));
System.assert(body.contains('timed=true'));
System.assert(body.contains('time=60'));
System.assert(body.contains('points=20.5'));
System.assert(body.contains('due=2016-05-10+18%3A59%3A59'));
System.assert(body.contains('description=complete+%26+upload+%27section1%3A+advanced%27'));
System.assertEquals('PUT', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('foo-bar-444', req.getHeader('X-Session'));
System.assertEquals('text/html,application/xml', req.getHeader('Accept'));
System.assertEquals('application/x-www-form-urlencoded', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_setupRequestWithQuery() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse returned = client.getResponse(
'GET', '/courses/{course}/assignments', '',
new List<Swagger.Param>{
new Swagger.Param('title', '#chapter1:section2'),
new Swagger.Param('due', '2016-05-10 18:59:59')
},
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/xml'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'}
);
HttpRequest req = mock.getRequest();
List<String> splitUrl = req.getEndpoint().split('\\?');
String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments';
Set<String> query = new Set<String>(splitUrl.get(1).split('&'));
System.assertEquals(res, returned);
System.assertEquals(expectedUrl, splitUrl.get(0));
System.assertEquals(2, query.size());
System.assert(query.contains('title=%23chapter1%3Asection2'));
System.assert(query.contains('due=2016-05-10+18%3A59%3A59'));
System.assertEquals('GET', req.getMethod());
System.assertEquals('Bearer foo-bar-access-token', req.getHeader('Authorization'));
System.assertEquals('application/xml', req.getHeader('Accept'));
System.assertEquals('text/plain', req.getHeader('Content-Type'));
}
@isTest
private static void ApiClient_nonSuccessfulStatusCodeException() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Swagger.OAuth2 auth = new Swagger.OAuth2();
auth.setAccessToken('foo-bar-access-token');
client.authentications.put('oauth_method', auth);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('Not Found');
res.setStatusCode(404);
res.setHeader('X-Request-ID', '1234567890');
res.setHeader('Content-Type', 'application/json');
res.setBody('{"error":"the specified course does not exist"}');
try {
client.invoke(
'GET', '/courses/{course}', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>{
'course' => 'acc321'
},
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>{'oauth_method'},
null
);
} catch (Swagger.ApiException e) {
Map<String, String> headers = e.getHeaders();
System.assertEquals('API returned HTTP 404: Not Found', e.getMessage());
System.assertEquals(404, e.getStatusCode());
System.assertEquals('Not Found', e.getStatus());
System.assertEquals('{"error":"the specified course does not exist"}', e.getBody());
System.assertEquals(2, headers.size());
System.assertEquals('1234567890', headers.get('X-Request-ID'));
System.assertEquals('application/json', headers.get('Content-Type'));
return;
}
System.assert(false);
}
@isTest
private static void ApiClient_returnParsedBody() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody('{'
+ '"city":"Austin","country":"United States","latitude":30.28403639999999,'
+ '"longitude":-97.73789449999998,"postalCode":"78705","state":"Texas",'
+ '"street":"2110 Speedway"}');
Address a = (Address) client.invoke(
'GET', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
Address.class
);
System.assertEquals('Austin', a.getCity());
System.assertEquals('United States', a.getCountry());
System.assertEquals(30.28403639999999, a.getLatitude());
System.assertEquals(-97.73789449999998, a.getLongitude());
System.assertEquals('78705', a.getPostalCode());
System.assertEquals('Texas', a.getState());
System.assertEquals('2110 Speedway', a.getStreet());
}
@isTest
private static void ApiClient_noReturnTypeReturnsNull() {
MockApiClient client = new MockApiClient();
HttpResponse res = new HttpResponse();
SwaggerResponseMock mock = new SwaggerResponseMock(res);
Test.setMock(HttpCalloutMock.class, mock);
res.setStatus('OK');
res.setStatusCode(200);
Object o = client.invoke(
'POST', '/address', '',
new List<Swagger.Param>(),
new List<Swagger.Param>(),
new Map<String, Object>(),
new Map<String, Object>(),
new List<String>{'application/json'},
new List<String>{'text/plain'},
new List<String>(),
null
);
System.assertEquals(null, o);
}
private class MockApiClient extends Swagger.ApiClient {
public MockApiClient() {
basePath = 'https://www.mccombs.utexas.edu';
}
}
}

View File

@ -0,0 +1,118 @@
{{>licenseInfo}}
{{#operations}}
public class {{classname}} {
{{classPrefix}}Client client;
public {{classname}}({{classPrefix}}Client client) {
this.client = client;
}
public {{classname}}() {
this.client = new {{classPrefix}}Client();
}
public {{classPrefix}}Client getClient() {
return this.client;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}
{{#returnType}}
* @return {{{returnType}}}
{{/returnType}}
* @throws Swagger.ApiException if fails to make API call
*/
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#hasParams}}Map<String, Object> params{{/hasParams}}) {
{{#allParams}}
{{#required}}
client.assertNotNull(params.get('{{paramName}}'), '{{paramName}}');
{{/required}}
{{/allParams}}
List<Swagger.Param> query = new List<Swagger.Param>();
{{#hasQueryParams}}
// cast query params to verify their expected type
{{/hasQueryParams}}
{{#queryParams}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
query.addAll(client.makeParams('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
query.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}'), '{{collectionFormat}}'));
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
query.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isListContainer}}
{{^hasMore}}
{{/hasMore}}
{{/queryParams}}
List<Swagger.Param> form = new List<Swagger.Param>();
{{#hasFormParams}}
// cast form params to verify their expected type
{{/hasFormParams}}
{{#formParams}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
form.addAll(client.makeParams('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
form.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}'), '{{collectionFormat}}'));
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
form.addAll(client.makeParam('{{baseName}}', ({{{dataType}}}) params.get('{{paramName}}')));
{{/isListContainer}}
{{/formParams}}
{{#returnType}}return ({{{returnType}}}) {{/returnType}}client.invoke(
'{{httpMethod}}', '{{path}}',{{#bodyParam}}
({{{dataType}}}) params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}} ''{{/bodyParam}},
query, form,
new Map<String, Object>{{#hasPathParams}}{
{{#pathParams}}
'{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}}
{{/pathParams}}
}{{/hasPathParams}}{{^hasPathParams}}(){{/hasPathParams}},
new Map<String, Object>{{#hasHeaderParams}}{
{{#headerParams}}
'{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}}
{{/headerParams}}
}{{/hasHeaderParams}}{{^hasHeaderParams}}(){{/hasHeaderParams}},
{{#hasProduces}}
new List<String>{ {{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}} },
{{/hasProduces}}
{{^hasProduces}}
new List<String>(),
{{/hasProduces}}
{{#hasConsumes}}
new List<String>{ {{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}} },
{{/hasConsumes}}
{{^hasConsumes}}
new List<String>(),
{{/hasConsumes}}
{{#hasAuthMethods}}
new List<String> { {{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}} },
{{/hasAuthMethods}}
{{^hasAuthMethods}}
new List<String>(),
{{/hasAuthMethods}}
{{#returnType}}
{{{returnType}}}.class
{{/returnType}}
{{^returnType}}
null
{{/returnType}}
);
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,83 @@
# {{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
<a name="{{operationId}}"></a>
# **{{operationId}}**
> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{{summary}}{{#notes}}
{{notes}}{{/notes}}
### Example
```java
{{classname}} api = new {{classname}}();
{{#hasAuthMethods}}
{{classPrefix}}Client client = api.getClient();
{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setUsername('YOUR USERNAME');
{{{name}}}.setPassword('YOUR PASSWORD');
// You can also set your username and password in one line
{{{name}}}.setCredentials('YOUR USERNAME', 'YOUR PASSWORD');{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setApiKey('YOUR API KEY');{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Swagger.OAuth {{{name}}} = (Swagger.OAuth) client.getAuthentication('{{{name}}}');
{{{name}}}.setAccessToken('YOUR ACCESS TOKEN');{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{{paramName}}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
try {
// cross your fingers
{{#returnType}}{{{returnType}}} result = {{/returnType}}api.{{{operationId}}}({{#hasParams}}params{{/hasParams}});
{{#returnType}}
System.debug(result);
{{/returnType}}
} catch (Swagger.ApiException e) {
// ...handle your exceptions
}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,87 @@
@isTest
private class {{classname}}Test {
{{#operations}}
{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*/
@isTest
private static void {{operationId}}Test() {
HttpResponse res = new HttpResponse();
{{#restfulCreate}}
res.setStatusCode(201);
res.setStatus('Created');
{{/restfulCreate}}
{{^restfulCreate}}
res.setStatusCode(200);
res.setStatus('OK');
{{/restfulCreate}}
Test.setMock(HttpCalloutMock.class, new SwaggerResponseMock(res));
{{#hasParams}}
Map<String, Object> params = new Map<String, Object>{
{{#allParams}}
'{{paramName}}' => {{{example}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
};
{{/hasParams}}
{{classPrefix}}Client client;
{{classname}} api;
{{#returnType}}
{{{returnType}}} response;
{{{returnType}}} expectedResponse;
{{/returnType}}
{{#authMethods}}
client = new {{classPrefix}}Client();
api = new {{classname}}(client);{{#isBasic}}
((Swagger.HttpBasicAuth){{/isBasic}}{{#isOAuth}}
((Swagger.OAuth2){{/isOAuth}}{{#isApiKey}}
((Swagger.ApiKeyAuth){{/isApiKey}} client.getAuthentication('{{name}}'))
{{#isBasic}}
.setCredentials('username', 'password');
{{/isBasic}}
{{#isOAuth}}
.setAccessToken('foo-bar-access-token');
{{/isOAuth}}
{{#isApiKey}}
.setApiKey('foo-bar-api-key');
{{/isApiKey}}
{{#examples}}
res.setHeader('Content-Type', '{{contentType}}');
res.setBody('{{{example}}}');
expectedResponse = {{{deserializedExample}}};
response = ({{{returnType}}}) api.{{operationId}}({{#hasParams}}params{{/hasParams}});
System.assertEquals(expectedResponse, response);
{{/examples}}
{{^examples}}
api.{{operationId}}({{#hasParams}}params{{/hasParams}});
{{/examples}}
{{/authMethods}}
{{^authMethods}}
api = new {{classname}}(new {{classPrefix}}Client());
{{#examples}}
res.setHeader('Content-Type', '{{contentType}}');
res.setBody('{{{example}}}');
expectedResponse = {{{deserializedExample}}};
response = ({{{returnType}}}) api.{{operationId}}({{#hasParams}}params{{/hasParams}});
System.assertEquals(expectedResponse, response);
{{/examples}}
{{^examples}}
api.{{operationId}}({{#hasParams}}params{{/hasParams}});
{{/examples}}
{{/authMethods}}
}
{{#hasMore}}
{{/hasMore}}
{{/operation}}
{{/operations}}
}

View File

@ -0,0 +1,98 @@
<project name="{{appName}}" default="deploy" basedir="." xmlns:sf="antlib:com.salesforce">
<property environment="env"/>
<property file="build.properties"/>
<condition property="SF_USERNAME" value="">
<not>
<isset property="SF_USERNAME"></isset>
</not>
</condition>
<condition property="SF_PASSWORD" value="">
<not>
<isset property="SF_PASSWORD"></isset>
</not>
</condition>
<condition property="SF_SESSIONID" value="">
<not>
<isset property="SF_SESSIONID"></isset>
</not>
</condition>
<condition property="sf.serverurl" value="login.salesforce.com">
<not>
<isset property="sf.serverurl"></isset>
</not>
</condition>
<condition property="sf.maxPoll" value="200">
<not>
<isset property="sf.maxPoll"></isset>
</not>
</condition>
<condition property="sf.username" value="${env.SF_USERNAME}" else="${SF_USERNAME}">
<isset property="env.SF_USERNAME"/>
</condition>
<condition property="sf.password" value="${env.SF_PASSWORD}" else="${SF_PASSWORD}">
<isset property="env.SF_PASSWORD"/>
</condition>
<condition property="sf.sessionId" value="${env.SF_SESSIONID}" else="${SF_SESSIONID}">
<isset property="env.SF_SESSIONID"/>
</condition>
<taskdef resource="com/salesforce/antlib.xml" uri="antlib:com.salesforce">
<classpath>
<pathelement location="./ant-salesforce.jar"/>
</classpath>
</taskdef>
<target name="deploy"
description="Deploys the API client library to your Salesforce organization">
<echo message="Deploying the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
rollbackOnError="true">
{{#apiInfo}}
{{#apis}}
<runTest>{{classname}}Test</runTest>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<runTest>{{classname}}Test</runTest>
{{/model}}
{{/models}}
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
<target name="undeploy"
description="Removes the API client library from your Salesforce organization">
<echo message="Removing the API client library..."/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="undeploy"/>
</target>
<target name="deployCheckOnly"
description="Deploys the API client library in check-only mode, without saving changes">
<echo message="Run 'ant deploy' to deploy this library to your organization."/>
<echo message="Testing deployment of this API client library without saving changes"/>
<sf:deploy username="${sf.username}" password="${sf.password}"
sessionId="${sf.sessionId}" serverurl="${sf.serverurl}"
maxPoll="${sf.maxPoll}" deployRoot="deploy" testLevel="RunSpecifiedTests"
checkOnly="true">
{{#apiInfo}}
{{#apis}}
<runTest>{{classname}}Test</runTest>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<runTest>{{classname}}Test</runTest>
{{/model}}
{{/models}}
<runTest>SwaggerTest</runTest>
</sf:deploy>
</target>
</project>

View File

@ -0,0 +1,37 @@
# build.properties
#
# The first three properties (SF_USERNAME, SF_PASSWORD, SF_SESSIONID) may either be specified below
# or set from environment variables of the same names. The remaining non-uppercase properties, which
# have the "sf." prefix (e.g.: sf.serverurl) may only be specified in this file and not from
# environment variables.
# Required if sessionId isnt specified. The Salesforce username for login. The username associated
# with this connection must have the “Modify All Data” permission. Typically, this is only enabled
# for System Administrator users.
#
# SF_USERNAME = username@example.com
# Required if sessionId isnt specified. The password you use to log in to the org associated with
# this project. If you are using a security token, paste the 25-digit token value to the end of your
# password.
#
# SF_PASSWORD = password123
# Required if username and password arent specified. The ID of an active Salesforce session or the
# OAuth access token. A session is created after a user logs in to Salesforce successfully with a
# username and password. Use a session ID for logging in to an existing session instead of creating
# a new session. Alternatively, use an access token for OAuth authentication. For more information,
# see Authenticating Apps with OAuth in the Salesforce Help.
#
# SF_SESSIONID = 0000...
# Optional. The Salesforce server URL (if blank, defaults to login.salesforce.com). To connect to a
# sandbox instance, change this to test.salesforce.com.
#
sf.serverurl = test.salesforce.com
# Optional. Defaults to 200. The number of times to poll the server for the results of the deploy
# request. Note that deployment can succeed even if you stop waiting.
#
sf.maxPoll = 200

View File

@ -0,0 +1,30 @@
public class {{classPrefix}}Client extends Swagger.ApiClient {
{{#hasAuthMethods}}
public {{classPrefix}}Client() {
basePath = '{{basePath}}';
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
authentications.put('{{name}}', new Swagger.ApiKeyQueryAuth('{{keyParamName}}'));
{{/isKeyInQuery}}
{{^isKeyInQuery}}
authentications.put('{{name}}', new Swagger.ApiKeyHeaderAuth('{{keyParamName}}'));
{{/isKeyInQuery}}
{{/isApiKey}}
{{^isApiKey}}
{{#isBasic}}
authentications.put('{{name}}', new Swagger.HttpBasicAuth());
{{/isBasic}}
{{^isBasic}}
authentications.put('{{name}}', new Swagger.OAuth2());
{{/isBasic}}
{{/isApiKey}}
{{/authMethods}}
}
{{/hasAuthMethods}}
{{^hasAuthMethods}}
public {{classPrefix}}Client() {
basePath = '{{basePath}}';
}
{{/hasAuthMethods}}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>{{apiVersion}}</apiVersion>
<status>Active</status>
</ApexClass>

View File

@ -0,0 +1,7 @@
# {{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,27 @@
*DS_Store*
/Referenced Packages
/salesforce.schema
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse
.project
.externalToolBuilders/
*.launch
*.iml
.idea
*.sublime*
config

View File

@ -0,0 +1,11 @@
/*
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/

View File

@ -0,0 +1,6 @@
{{>licenseInfo}}
{{#models}}
{{#model}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,10 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{name}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -0,0 +1,10 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -0,0 +1,3 @@
{{#models}}{{#model}}
{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}}
{{/model}}{{/models}}

View File

@ -0,0 +1,130 @@
{{#models}}
{{#model}}
@isTest
private class {{classname}}Test {
{{#isEnum}}
{{#allowableValues}}
@isTest
private static void allowableValues() {
Set<{{classname}}> expected = new Set<{{classname}}>{
{{#enumVars}}
{{classname}}.{{name}}{{^-last}},{{/-last}}
{{/enumVars}}
};
Set<{{classname}}> actual = new Set<{{classname}}>({{classname}}.values());
System.assertEquals(expected, actual);
}
{{/allowableValues}}
{{/isEnum}}
{{^isEnum}}
@isTest
private static void equalsSameInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classVarName}}1;
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = {{classVarName}}3;
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}2.equals({{classVarName}}1));
System.assert({{classVarName}}1.equals({{classVarName}}1));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assert({{classVarName}}4.equals({{classVarName}}3));
System.assert({{classVarName}}3.equals({{classVarName}}3));
}
@isTest
private static void equalsIdenticalInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classname}}.getExample();
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = new {{classname}}();
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}2.equals({{classVarName}}1));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assert({{classVarName}}4.equals({{classVarName}}3));
}
@isTest
private static void notEqualsUnlikeInstance() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals(false, {{classVarName}}1.equals({{classVarName}}2));
System.assertEquals(false, {{classVarName}}2.equals({{classVarName}}1));
}
@isTest
private static void notEqualsDifferentType() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals(false, {{classVarName}}1.equals('foo'));
System.assertEquals(false, {{classVarName}}2.equals('foo'));
}
@isTest
private static void notEqualsNull() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
{{classname}} {{classVarName}}3;
System.assertEquals(false, {{classVarName}}1.equals({{classVarName}}3));
System.assertEquals(false, {{classVarName}}2.equals({{classVarName}}3));
}
@isTest
private static void consistentHashCodeValue() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = new {{classname}}();
System.assertEquals({{classVarName}}1.hashCode(), {{classVarName}}1.hashCode());
System.assertEquals({{classVarName}}2.hashCode(), {{classVarName}}2.hashCode());
}
@isTest
private static void equalInstancesHaveSameHashCode() {
{{classname}} {{classVarName}}1 = {{classname}}.getExample();
{{classname}} {{classVarName}}2 = {{classname}}.getExample();
{{classname}} {{classVarName}}3 = new {{classname}}();
{{classname}} {{classVarName}}4 = new {{classname}}();
System.assert({{classVarName}}1.equals({{classVarName}}2));
System.assert({{classVarName}}3.equals({{classVarName}}4));
System.assertEquals({{classVarName}}1.hashCode(), {{classVarName}}2.hashCode());
System.assertEquals({{classVarName}}3.hashCode(), {{classVarName}}4.hashCode());
}
{{#vendorExtensions}}
{{#hasPropertyMappings}}
@isTest
private static void maintainRenamedProperties() {
{{classname}} {{classVarName}} = new {{classname}}();
Map<String, String> propertyMappings = {{classVarName}}.getPropertyMappings();
{{#propertyMappings}}
System.assertEquals('{{internalName}}', propertyMappings.get('{{externalName}}'));
{{/propertyMappings}}
}
{{/hasPropertyMappings}}
{{#hasDefaultValues}}
@isTest
private static void defaultValuesPopulated() {
{{classname}} {{classVarName}} = new {{classname}}();
{{#vars}}
{{#defaultValue}}
System.assertEquals({{{defaultValue}}}, {{classVarName}}.{{name}});
{{/defaultValue}}
{{/vars}}
{{#vars}}
{{^defaultValue}}
System.assertEquals(null, {{classVarName}}.{{name}});
{{/defaultValue}}
{{/vars}}
}
{{/hasDefaultValues}}
{{/vendorExtensions}}
{{/isEnum}}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>{{appName}} API Client</fullName>
<description>Client library for calling the {{appName}} API.{{#appDescription}}
{{{appDescription}}}{{/appDescription}}
Generated with Swagger Codegen (github.com/swagger-api/swagger-codegen)</description>
<types>
{{#apiInfo}}
{{#apis}}
<members>{{classname}}</members>
<members>{{classname}}Test</members>
{{/apis}}
{{/apiInfo}}
{{#models}}
{{#model}}
<members>{{classname}}</members>
<members>{{classname}}Test</members>
{{/model}}
{{/models}}
<members>{{classPrefix}}Client</members>
<members>Swagger</members>
<members>SwaggerTest</members>
<members>SwaggerResponseMock</members>
<name>ApexClass</name>
</types>
<types>
<members>{{sanitizedName}}</members>
<name>RemoteSiteSetting</name>
</types>
<version>{{apiVersion}}</version>
</Package>

View File

@ -0,0 +1,84 @@
/**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/
public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{#interfaces}}{{#-first}} implements {{/-first}}{{^-first}}, {{/-first}}{{.}}{{/interfaces}} {
{{#vars}}
{{#isEnum}}
{{^isContainer}}
{{>modelInnerEnum}}
{{/isContainer}}
{{/isEnum}}
{{#items.isEnum}}
{{#items}}
{{^isContainer}}
{{>modelInnerEnum}}
{{/isContainer}}
{{/items}}
{{/items.isEnum}}
/**
{{#description}}
* {{{description}}}
{{/description}}
{{^description}}
* Get {{name}}
{{/description}}
{{#minimum}}
* minimum: {{minimum}}
{{/minimum}}
{{#maximum}}
* maximum: {{maximum}}
{{/maximum}}
* @return {{name}}
*/
public {{{datatypeWithEnum}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; }
{{/vars}}
{{#vendorExtensions}}
{{#hasPropertyMappings}}
private static final Map<String, String> propertyMappings = new Map<String, String>{
{{#propertyMappings}}
'{{externalName}}' => '{{internalName}}'{{^-last}},{{/-last}}
{{/propertyMappings}}
};
public Map<String, String> getPropertyMappings() {
return propertyMappings;
}
{{/hasPropertyMappings}}
{{#hasDefaultValues}}
public {{classname}}() {
{{#vars}}
{{#defaultValue}}
{{name}} = {{{defaultValue}}};
{{/defaultValue}}
{{/vars}}
}
{{/hasDefaultValues}}
{{/vendorExtensions}}
public static {{classname}} getExample() {
{{classname}} {{classVarName}} = new {{classname}}();
{{#vars}}
{{classVarName}}.{{name}} = {{{example}}};
{{/vars}}
return {{classVarName}};
}
public Boolean equals(Object obj) {
if (obj instanceof {{classname}}) {
{{classname}} {{classVarName}} = ({{classname}}) obj;
return {{#vars}}this.{{name}} == {{classVarName}}.{{name}}{{#hasMore}}
&& {{/hasMore}}{{/vars}};
}
return false;
}
public Integer hashCode() {
Integer hashCode = 43;
{{#vars}}
hashCode = (17 * hashCode) + ({{name}} == null ? 0 : System.hashCode({{name}}));
{{/vars}}
return hashCode;
}
}

View File

@ -0,0 +1,15 @@
# {{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#readOnly}} [readonly]{{/readOnly}}
{{/vars}}
{{#vars}}{{#isEnum}}
<a name="{{{datatypeWithEnum}}}"></a>
## Enum: {{datatypeWithEnum}}
Name | Value
---- | -----{{#allowableValues}}{{#enumVars}}
{{name}} | {{value}}{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{/vars}}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">{{#shortDescription}}
<description>{{{shortDescription}}}</description>{{/shortDescription}}
<disableProtocolSecurity>false</disableProtocolSecurity>
<isActive>true</isActive>
<url>{{basePath}}</url>
</RemoteSiteSetting>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>{{classPrefix}} API Client</fullName>
<version>{{apiVersion}}</version>
</Package>

View File

@ -0,0 +1,875 @@
package io.swagger.codegen.apex;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.languages.ApexClientCodegen;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
@SuppressWarnings("static-method")
public class ApexModelTest {
@Test(description = "convert a simple apex model with provided examples")
public void examplesProvidedTest() {
BaseIntegerProperty baseIntProp = new BaseIntegerProperty();
baseIntProp.setExample(5);
PasswordProperty passwordProp = new PasswordProperty();
passwordProp.setExample("password");
UUIDProperty uuidProp = new UUIDProperty();
uuidProp.setExample("793574b2-3a8e-4f6c-bfa5-c6929dc29f8a");
final Model model = new ModelImpl()
.property("boolProp", new BooleanProperty().example(false))
.property("dateProp", new DateProperty().example("1985-04-12"))
.property("dateTimeProp", new DateTimeProperty().example("1985-04-12T23:20:50.52Z"))
.property("decimalProp", new DecimalProperty().example("19.99"))
.property("doubleProp", new DoubleProperty().example(2.95))
.property("emailProp", new EmailProperty().example("info@example.com"))
.property("floatProp", new FloatProperty().example(3.49f))
.property("intProp", new IntegerProperty().example(10))
.property("longProp", new LongProperty().example(100000L))
.property("stringProp", new StringProperty().example("foo"))
.property("baseIntProp", baseIntProp)
.property("passwordProp", passwordProp)
.property("uuidProp", uuidProp);
final ApexClientCodegen codegen = new ApexClientCodegen();
codegen.setClassPrefix("Prefix");
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "PrefixSample");
Assert.assertEquals(cm.vars.size(), 13);
final List<CodegenProperty> vars = cm.vars;
final CodegenProperty property1 = vars.get(0);
Assert.assertEquals(property1.name, "boolProp");
Assert.assertEquals(property1.baseName, "boolProp");
Assert.assertEquals(property1.datatype, "Boolean");
Assert.assertEquals(property1.baseType, "Boolean");
Assert.assertEquals(property1.example, "false");
Assert.assertNull(property1.defaultValue);
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertTrue(property1.isNotContainer);
Assert.assertTrue(property1.isBoolean);
final CodegenProperty property2 = vars.get(1);
Assert.assertEquals(property2.name, "dateProp");
Assert.assertEquals(property2.baseName, "dateProp");
Assert.assertEquals(property2.datatype, "Date");
Assert.assertEquals(property2.baseType, "Date");
Assert.assertEquals(property2.example, "Date.newInstance(1985, 4, 12)");
Assert.assertNull(property2.defaultValue);
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isNotContainer);
Assert.assertTrue(property2.isDate);
final CodegenProperty property3 = vars.get(2);
Assert.assertEquals(property3.name, "dateTimeProp");
Assert.assertEquals(property3.baseName, "dateTimeProp");
Assert.assertEquals(property3.datatype, "Datetime");
Assert.assertEquals(property3.baseType, "Datetime");
Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(1985, 4, 12, 23, 20, 50)");
Assert.assertNull(property3.defaultValue);
Assert.assertTrue(property3.hasMore);
Assert.assertTrue(property3.isPrimitiveType);
Assert.assertTrue(property3.isNotContainer);
Assert.assertTrue(property3.isDateTime);
final CodegenProperty property4 = vars.get(3);
Assert.assertEquals(property4.name, "decimalProp");
Assert.assertEquals(property4.baseName, "decimalProp");
Assert.assertEquals(property4.datatype, "Double");
Assert.assertEquals(property4.baseType, "Double");
Assert.assertEquals(property4.example, "19.99");
Assert.assertNull(property4.defaultValue);
Assert.assertTrue(property4.hasMore);
Assert.assertTrue(property4.isPrimitiveType);
Assert.assertTrue(property4.isNotContainer);
final CodegenProperty property5 = vars.get(4);
Assert.assertEquals(property5.name, "doubleProp");
Assert.assertEquals(property5.baseName, "doubleProp");
Assert.assertEquals(property5.datatype, "Double");
Assert.assertEquals(property5.baseType, "Double");
Assert.assertEquals(property5.example, "2.95");
Assert.assertNull(property5.defaultValue);
Assert.assertTrue(property5.hasMore);
Assert.assertTrue(property5.isPrimitiveType);
Assert.assertTrue(property5.isNotContainer);
Assert.assertTrue(property5.isDouble);
final CodegenProperty property6 = vars.get(5);
Assert.assertEquals(property6.name, "emailProp");
Assert.assertEquals(property6.baseName, "emailProp");
Assert.assertEquals(property6.datatype, "String");
Assert.assertEquals(property6.baseType, "String");
Assert.assertEquals(property6.example, "'info@example.com'");
Assert.assertNull(property6.defaultValue);
Assert.assertTrue(property6.hasMore);
Assert.assertTrue(property6.isPrimitiveType);
Assert.assertTrue(property6.isNotContainer);
Assert.assertTrue(property6.isString);
final CodegenProperty property7 = vars.get(6);
Assert.assertEquals(property7.name, "floatProp");
Assert.assertEquals(property7.baseName, "floatProp");
Assert.assertEquals(property7.datatype, "Double");
Assert.assertEquals(property7.baseType, "Double");
Assert.assertEquals(property7.example, "3.49");
Assert.assertNull(property7.defaultValue);
Assert.assertTrue(property7.hasMore);
Assert.assertTrue(property7.isPrimitiveType);
Assert.assertTrue(property7.isNotContainer);
Assert.assertTrue(property7.isFloat);
final CodegenProperty property8 = vars.get(7);
Assert.assertEquals(property8.name, "intProp");
Assert.assertEquals(property8.baseName, "intProp");
Assert.assertEquals(property8.datatype, "Integer");
Assert.assertEquals(property8.baseType, "Integer");
Assert.assertEquals(property8.example, "10");
Assert.assertNull(property8.defaultValue);
Assert.assertTrue(property8.hasMore);
Assert.assertTrue(property8.isPrimitiveType);
Assert.assertTrue(property8.isNotContainer);
Assert.assertTrue(property8.isInteger);
final CodegenProperty property9 = vars.get(8);
Assert.assertEquals(property9.name, "longProp");
Assert.assertEquals(property9.baseName, "longProp");
Assert.assertEquals(property9.datatype, "Long");
Assert.assertEquals(property9.baseType, "Long");
Assert.assertEquals(property9.example, "100000L");
Assert.assertNull(property9.defaultValue);
Assert.assertTrue(property9.hasMore);
Assert.assertTrue(property9.isPrimitiveType);
Assert.assertTrue(property9.isNotContainer);
Assert.assertTrue(property9.isLong);
final CodegenProperty property10 = vars.get(9);
Assert.assertEquals(property10.name, "stringProp");
Assert.assertEquals(property10.baseName, "stringProp");
Assert.assertEquals(property10.datatype, "String");
Assert.assertEquals(property10.baseType, "String");
Assert.assertEquals(property10.example, "'foo'");
Assert.assertNull(property10.defaultValue);
Assert.assertTrue(property10.hasMore);
Assert.assertTrue(property10.isPrimitiveType);
Assert.assertTrue(property10.isNotContainer);
Assert.assertTrue(property10.isString);
final CodegenProperty property11 = vars.get(10);
Assert.assertEquals(property11.name, "baseIntProp");
Assert.assertEquals(property11.baseName, "baseIntProp");
Assert.assertEquals(property11.datatype, "Integer");
Assert.assertEquals(property11.baseType, "Integer");
Assert.assertEquals(property11.example, "5");
Assert.assertNull(property11.defaultValue);
Assert.assertTrue(property11.hasMore);
Assert.assertTrue(property11.isPrimitiveType);
Assert.assertTrue(property11.isNotContainer);
Assert.assertTrue(property11.isInteger);
final CodegenProperty property12 = vars.get(11);
Assert.assertEquals(property12.name, "passwordProp");
Assert.assertEquals(property12.baseName, "passwordProp");
Assert.assertEquals(property12.datatype, "String");
Assert.assertEquals(property12.baseType, "String");
Assert.assertEquals(property12.example, "'password'");
Assert.assertNull(property12.defaultValue);
Assert.assertTrue(property12.hasMore);
Assert.assertTrue(property12.isPrimitiveType);
Assert.assertTrue(property12.isNotContainer);
final CodegenProperty property13 = vars.get(12);
Assert.assertEquals(property13.name, "uuidProp");
Assert.assertEquals(property13.baseName, "uuidProp");
Assert.assertEquals(property13.datatype, "String");
Assert.assertEquals(property13.baseType, "String");
Assert.assertEquals(property13.example, "'793574b2-3a8e-4f6c-bfa5-c6929dc29f8a'");
Assert.assertNull(property13.defaultValue);
Assert.assertFalse(property13.hasMore);
Assert.assertTrue(property13.isPrimitiveType);
Assert.assertTrue(property13.isNotContainer);
}
@Test(description = "convert a simple apex model with default examples")
public void defaultExamplesTest() {
final Model model = new ModelImpl()
.property("boolProp", new BooleanProperty())
.property("dateProp", new DateProperty())
.property("dateTimeProp", new DateTimeProperty())
.property("decimalProp", new DecimalProperty())
.property("doubleProp", new DoubleProperty())
.property("emailProp", new EmailProperty())
.property("floatProp", new FloatProperty())
.property("intProp", new IntegerProperty())
.property("longProp", new LongProperty())
.property("stringProp", new StringProperty())
.property("baseIntProp", new BaseIntegerProperty())
.property("passwordProp", new PasswordProperty())
.property("uuidProp", new UUIDProperty())
.property("byteArrProp", new ByteArrayProperty())
.property("binaryProp", new BinaryProperty());
final ApexClientCodegen codegen = new ApexClientCodegen();
codegen.setClassPrefix("Prefix");
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "PrefixSample");
Assert.assertEquals(cm.vars.size(), 15);
final List<CodegenProperty> vars = cm.vars;
final CodegenProperty property1 = vars.get(0);
Assert.assertEquals(property1.name, "boolProp");
Assert.assertEquals(property1.baseName, "boolProp");
Assert.assertEquals(property1.datatype, "Boolean");
Assert.assertEquals(property1.baseType, "Boolean");
Assert.assertEquals(property1.example, "true");
Assert.assertNull(property1.defaultValue);
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.isPrimitiveType);
Assert.assertTrue(property1.isNotContainer);
Assert.assertTrue(property1.isBoolean);
final CodegenProperty property2 = vars.get(1);
Assert.assertEquals(property2.name, "dateProp");
Assert.assertEquals(property2.baseName, "dateProp");
Assert.assertEquals(property2.datatype, "Date");
Assert.assertEquals(property2.baseType, "Date");
Assert.assertEquals(property2.example, "Date.newInstance(2000, 1, 23)");
Assert.assertNull(property2.defaultValue);
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isNotContainer);
Assert.assertTrue(property2.isDate);
final CodegenProperty property3 = vars.get(2);
Assert.assertEquals(property3.name, "dateTimeProp");
Assert.assertEquals(property3.baseName, "dateTimeProp");
Assert.assertEquals(property3.datatype, "Datetime");
Assert.assertEquals(property3.baseType, "Datetime");
Assert.assertEquals(property3.example, "Datetime.newInstanceGmt(2000, 1, 23, 4, 56, 7)");
Assert.assertNull(property3.defaultValue);
Assert.assertTrue(property3.hasMore);
Assert.assertTrue(property3.isPrimitiveType);
Assert.assertTrue(property3.isNotContainer);
Assert.assertTrue(property3.isDateTime);
final CodegenProperty property4 = vars.get(3);
Assert.assertEquals(property4.name, "decimalProp");
Assert.assertEquals(property4.baseName, "decimalProp");
Assert.assertEquals(property4.datatype, "Double");
Assert.assertEquals(property4.baseType, "Double");
Assert.assertEquals(property4.example, "1.3579");
Assert.assertNull(property4.defaultValue);
Assert.assertTrue(property4.hasMore);
Assert.assertTrue(property4.isPrimitiveType);
Assert.assertTrue(property4.isNotContainer);
final CodegenProperty property5 = vars.get(4);
Assert.assertEquals(property5.name, "doubleProp");
Assert.assertEquals(property5.baseName, "doubleProp");
Assert.assertEquals(property5.datatype, "Double");
Assert.assertEquals(property5.baseType, "Double");
Assert.assertEquals(property5.example, "1.3579");
Assert.assertNull(property5.defaultValue);
Assert.assertTrue(property5.hasMore);
Assert.assertTrue(property5.isPrimitiveType);
Assert.assertTrue(property5.isNotContainer);
Assert.assertTrue(property5.isDouble);
final CodegenProperty property6 = vars.get(5);
Assert.assertEquals(property6.name, "emailProp");
Assert.assertEquals(property6.baseName, "emailProp");
Assert.assertEquals(property6.datatype, "String");
Assert.assertEquals(property6.baseType, "String");
Assert.assertEquals(property6.example, "'example@example.com'");
Assert.assertNull(property6.defaultValue);
Assert.assertTrue(property6.hasMore);
Assert.assertTrue(property6.isPrimitiveType);
Assert.assertTrue(property6.isNotContainer);
Assert.assertTrue(property6.isString);
final CodegenProperty property7 = vars.get(6);
Assert.assertEquals(property7.name, "floatProp");
Assert.assertEquals(property7.baseName, "floatProp");
Assert.assertEquals(property7.datatype, "Double");
Assert.assertEquals(property7.baseType, "Double");
Assert.assertEquals(property7.example, "1.3579");
Assert.assertNull(property7.defaultValue);
Assert.assertTrue(property7.hasMore);
Assert.assertTrue(property7.isPrimitiveType);
Assert.assertTrue(property7.isNotContainer);
Assert.assertTrue(property7.isFloat);
final CodegenProperty property8 = vars.get(7);
Assert.assertEquals(property8.name, "intProp");
Assert.assertEquals(property8.baseName, "intProp");
Assert.assertEquals(property8.datatype, "Integer");
Assert.assertEquals(property8.baseType, "Integer");
Assert.assertEquals(property8.example, "123");
Assert.assertNull(property8.defaultValue);
Assert.assertTrue(property8.hasMore);
Assert.assertTrue(property8.isPrimitiveType);
Assert.assertTrue(property8.isNotContainer);
Assert.assertTrue(property8.isInteger);
final CodegenProperty property9 = vars.get(8);
Assert.assertEquals(property9.name, "longProp");
Assert.assertEquals(property9.baseName, "longProp");
Assert.assertEquals(property9.datatype, "Long");
Assert.assertEquals(property9.baseType, "Long");
Assert.assertEquals(property9.example, "123456789L");
Assert.assertNull(property9.defaultValue);
Assert.assertTrue(property9.hasMore);
Assert.assertTrue(property9.isPrimitiveType);
Assert.assertTrue(property9.isNotContainer);
Assert.assertTrue(property9.isLong);
final CodegenProperty property10 = vars.get(9);
Assert.assertEquals(property10.name, "stringProp");
Assert.assertEquals(property10.baseName, "stringProp");
Assert.assertEquals(property10.datatype, "String");
Assert.assertEquals(property10.baseType, "String");
Assert.assertEquals(property10.example, "'aeiou'");
Assert.assertNull(property10.defaultValue);
Assert.assertTrue(property10.hasMore);
Assert.assertTrue(property10.isPrimitiveType);
Assert.assertTrue(property10.isNotContainer);
Assert.assertTrue(property10.isString);
final CodegenProperty property11 = vars.get(10);
Assert.assertEquals(property11.name, "baseIntProp");
Assert.assertEquals(property11.baseName, "baseIntProp");
Assert.assertEquals(property11.datatype, "Integer");
Assert.assertEquals(property11.baseType, "Integer");
Assert.assertEquals(property11.example, "123");
Assert.assertNull(property11.defaultValue);
Assert.assertTrue(property11.hasMore);
Assert.assertTrue(property11.isPrimitiveType);
Assert.assertTrue(property11.isNotContainer);
Assert.assertTrue(property11.isInteger);
final CodegenProperty property12 = vars.get(11);
Assert.assertEquals(property12.name, "passwordProp");
Assert.assertEquals(property12.baseName, "passwordProp");
Assert.assertEquals(property12.datatype, "String");
Assert.assertEquals(property12.baseType, "String");
Assert.assertEquals(property12.example, "'password123'");
Assert.assertNull(property12.defaultValue);
Assert.assertTrue(property12.hasMore);
Assert.assertTrue(property12.isPrimitiveType);
Assert.assertTrue(property12.isNotContainer);
final CodegenProperty property13 = vars.get(12);
Assert.assertEquals(property13.name, "uuidProp");
Assert.assertEquals(property13.baseName, "uuidProp");
Assert.assertEquals(property13.datatype, "String");
Assert.assertEquals(property13.baseType, "String");
Assert.assertEquals(property13.example, "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'");
Assert.assertNull(property13.defaultValue);
Assert.assertTrue(property13.hasMore);
Assert.assertTrue(property13.isPrimitiveType);
Assert.assertTrue(property13.isNotContainer);
final CodegenProperty property14 = vars.get(13);
Assert.assertEquals(property14.name, "byteArrProp");
Assert.assertEquals(property14.baseName, "byteArrProp");
Assert.assertEquals(property14.datatype, "Blob");
Assert.assertEquals(property14.baseType, "Blob");
Assert.assertEquals(property14.example, "EncodingUtil.base64Decode('VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')");
Assert.assertNull(property14.defaultValue);
Assert.assertTrue(property14.hasMore);
Assert.assertTrue(property14.isPrimitiveType);
Assert.assertTrue(property14.isNotContainer);
Assert.assertTrue(property14.isByteArray);
final CodegenProperty property15 = vars.get(14);
Assert.assertEquals(property15.name, "binaryProp");
Assert.assertEquals(property15.baseName, "binaryProp");
Assert.assertEquals(property15.datatype, "String");
Assert.assertEquals(property15.baseType, "String");
Assert.assertEquals(property15.example, "");
Assert.assertNull(property15.defaultValue);
Assert.assertFalse(property15.hasMore);
Assert.assertTrue(property15.isPrimitiveType);
Assert.assertTrue(property15.isNotContainer);
Assert.assertTrue(property15.isBinary);
}
//
// @Test(description = "convert a model with list property")
// public void listPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("id", new LongProperty())
// .property("urls", new ArrayProperty()
// .items(new StringProperty()))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 2);
//
// final CodegenProperty property = cm.vars.get(1);
// Assert.assertEquals(property.baseName, "urls");
// Assert.assertEquals(property.getter, "getUrls");
// Assert.assertEquals(property.setter, "setUrls");
// Assert.assertEquals(property.datatype, "List<String>");
// Assert.assertEquals(property.name, "urls");
// Assert.assertEquals(property.defaultValue, "new ArrayList<String>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a map property")
// public void mapPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("translations", new MapProperty()
// .additionalProperties(new StringProperty()))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "translations");
// Assert.assertEquals(property.getter, "getTranslations");
// Assert.assertEquals(property.setter, "setTranslations");
// Assert.assertEquals(property.datatype, "Map<String, String>");
// Assert.assertEquals(property.name, "translations");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, String>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a map with complex list property")
// public void mapWithListPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("translations",
// new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet"))))
// .required("id");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "translations");
// Assert.assertEquals(property.getter, "getTranslations");
// Assert.assertEquals(property.setter, "setTranslations");
// Assert.assertEquals(property.datatype, "Map<String, List<Pet>>");
// Assert.assertEquals(property.name, "translations");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, List<Pet>>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with a 2D list property")
// public void list2DPropertyTest() {
// final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items(
// new ArrayProperty().items(new RefProperty("Pet"))));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "list2D");
// Assert.assertEquals(property.getter, "getList2D");
// Assert.assertEquals(property.setter, "setList2D");
// Assert.assertEquals(property.datatype, "List<List<Pet>>");
// Assert.assertEquals(property.name, "list2D");
// Assert.assertEquals(property.defaultValue, "new ArrayList<List<Pet>>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with complex properties")
// public void complexPropertiesTest() {
// final Model model = new ModelImpl().description("a sample model")
// .property("children", new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "Children");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "Children");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model with complex list property")
// public void complexListPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children")));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.complexType, "Children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "List<Children>");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "new ArrayList<Children>()");
// Assert.assertEquals(property.baseType, "List");
// Assert.assertEquals(property.containerType, "array");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// }
//
// @Test(description = "convert a model with complex map property")
// public void complexMapPropertyTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children")));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "a sample model");
// Assert.assertEquals(cm.vars.size(), 1);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "children");
// Assert.assertEquals(property.complexType, "Children");
// Assert.assertEquals(property.getter, "getChildren");
// Assert.assertEquals(property.setter, "setChildren");
// Assert.assertEquals(property.datatype, "Map<String, Children>");
// Assert.assertEquals(property.name, "children");
// Assert.assertEquals(property.defaultValue, "new HashMap<String, Children>()");
// Assert.assertEquals(property.baseType, "Map");
// Assert.assertEquals(property.containerType, "map");
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isContainer);
// Assert.assertFalse(property.isNotContainer);
//
// }
//
// @Test(description = "convert an array model")
// public void arrayModelTest() {
// final Model model = new ArrayModel()
// .description("an array model")
// .items(new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "an array model");
// Assert.assertEquals(cm.vars.size(), 0);
// Assert.assertEquals(cm.parent, "ArrayList<Children>");
// Assert.assertEquals(cm.imports.size(), 4);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "List", "ArrayList", "Children")).size(), 4);
// }
//
// @Test(description = "convert an map model")
// public void mapModelTest() {
// final Model model = new ModelImpl()
// .description("an map model")
// .additionalProperties(new RefProperty("#/definitions/Children"));
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.description, "an map model");
// Assert.assertEquals(cm.vars.size(), 0);
// Assert.assertEquals(cm.parent, "HashMap<String, Children>");
// Assert.assertEquals(cm.imports.size(), 4);
// Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ApiModel", "Map", "HashMap", "Children")).size(), 4);
// }
//
// @Test(description = "convert a model with upper-case property names")
// public void upperCaseNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with upper-case property names")
// .property("NAME", new StringProperty())
// .required("NAME");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "NAME");
// Assert.assertEquals(property.getter, "getNAME");
// Assert.assertEquals(property.setter, "setNAME");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "NAME");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model with a 2nd char upper-case property names")
// public void secondCharUpperCaseNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with a 2nd char upper-case property names")
// .property("pId", new StringProperty())
// .required("pId");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "pId");
// Assert.assertEquals(property.getter, "getPId");
// Assert.assertEquals(property.setter, "setPId");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "pId");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a model starting with two upper-case letter property names")
// public void firstTwoUpperCaseLetterNamesTest() {
// final Model model = new ModelImpl()
// .description("a model with a property name starting with two upper-case letters")
// .property("ATTName", new StringProperty())
// .required("ATTName");
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "ATTName");
// Assert.assertEquals(property.getter, "getAtTName");
// Assert.assertEquals(property.setter, "setAtTName");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "atTName");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert hyphens per issue 503")
// public void hyphensTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("created-at", new DateTimeProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "created-at");
// Assert.assertEquals(property.getter, "getCreatedAt");
// Assert.assertEquals(property.setter, "setCreatedAt");
// Assert.assertEquals(property.name, "createdAt");
// }
//
// @Test(description = "convert query[password] to queryPassword")
// public void squareBracketsTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("query[password]", new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "query[password]");
// Assert.assertEquals(property.getter, "getQueryPassword");
// Assert.assertEquals(property.setter, "setQueryPassword");
// Assert.assertEquals(property.name, "queryPassword");
// }
//
// @Test(description = "properly escape names per 567")
// public void escapeNamesTest() {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property("created-at", new DateTimeProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("with.dots", model);
//
// Assert.assertEquals(cm.classname, "WithDots");
// }
//
// @Test(description = "convert a model with binary data")
// public void binaryDataTest() {
// final Model model = new ModelImpl()
// .description("model with binary")
// .property("inputBinaryData", new ByteArrayProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "inputBinaryData");
// Assert.assertEquals(property.getter, "getInputBinaryData");
// Assert.assertEquals(property.setter, "setInputBinaryData");
// Assert.assertEquals(property.datatype, "byte[]");
// Assert.assertEquals(property.name, "inputBinaryData");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "byte[]");
// Assert.assertFalse(property.hasMore);
// Assert.assertFalse(property.required);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "translate an invalid param name")
// public void invalidParamNameTest() {
// final Model model = new ModelImpl()
// .description("a model with a 2nd char upper-case property names")
// .property("_", new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// Assert.assertEquals(cm.name, "sample");
// Assert.assertEquals(cm.classname, "Sample");
// Assert.assertEquals(cm.vars.size(), 1);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, "_");
// Assert.assertEquals(property.getter, "getU");
// Assert.assertEquals(property.setter, "setU");
// Assert.assertEquals(property.datatype, "String");
// Assert.assertEquals(property.name, "u");
// Assert.assertEquals(property.defaultValue, "null");
// Assert.assertEquals(property.baseType, "String");
// Assert.assertFalse(property.hasMore);
// Assert.assertTrue(property.isNotContainer);
// }
//
// @Test(description = "convert a parameter")
// public void convertParameterTest() {
// final QueryParameter parameter = new QueryParameter()
// .property(new IntegerProperty())
// .name("limit")
// .required(true);
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenParameter cm = codegen.fromParameter(parameter, null);
//
// Assert.assertNull(cm.allowableValues);
// }
//
// @Test(description = "types used by inner properties should be imported")
// public void mapWithAnListOfBigDecimalTest() {
// final CodegenModel cm1 = new JavaClientCodegen().fromModel("sample", new ModelImpl()
// .description("model with Map<String, List<BigDecimal>>")
// .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))));
// Assert.assertEquals(cm1.vars.get(0).datatype, "Map<String, List<BigDecimal>>");
// Assert.assertTrue(cm1.imports.contains("BigDecimal"));
//
// final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl()
// .description("model with Map<String, Map<String, List<BigDecimal>>>")
// .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))));
// Assert.assertEquals(cm2.vars.get(0).datatype, "Map<String, Map<String, List<BigDecimal>>>");
// Assert.assertTrue(cm2.imports.contains("BigDecimal"));
// }
//
// @DataProvider(name = "modelNames")
// public static Object[][] primeNumbers() {
// return new Object[][] {
// {"sample", "Sample"},
// {"sample_name", "SampleName"},
// {"sample__name", "SampleName"},
// {"/sample", "Sample"},
// {"\\sample", "Sample"},
// {"sample.name", "SampleName"},
// {"_sample", "Sample"},
// {"Sample", "Sample"},
// };
// }
//
// @Test(dataProvider = "modelNames", description = "avoid inner class")
// public void modelNameTest(String name, String expectedName) {
// final Model model = new ModelImpl();
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel(name, model);
//
// Assert.assertEquals(cm.name, name);
// Assert.assertEquals(cm.classname, expectedName);
// }
//
// @DataProvider(name = "classProperties")
// public static Object[][] classProperties() {
// return new Object[][] {
// {"class", "getPropertyClass", "setPropertyClass", "propertyClass"},
// {"_class", "getPropertyClass", "setPropertyClass", "propertyClass"},
// {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"}
// };
// }
//
// @Test(dataProvider = "classProperties", description = "handle 'class' properties")
// public void classPropertyTest(String baseName, String getter, String setter, String name) {
// final Model model = new ModelImpl()
// .description("a sample model")
// .property(baseName, new StringProperty());
// final DefaultCodegen codegen = new JavaClientCodegen();
// final CodegenModel cm = codegen.fromModel("sample", model);
//
// final CodegenProperty property = cm.vars.get(0);
// Assert.assertEquals(property.baseName, baseName);
// Assert.assertEquals(property.getter, getter);
// Assert.assertEquals(property.setter, setter);
// Assert.assertEquals(property.name, name);
// }
}