diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ApexClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ApexClientCodegen.java new file mode 100644 index 00000000000..b157b8cff68 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ApexClientCodegen.java @@ -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( + 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()", 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 allDefinitions) { + CodegenModel cm = super.fromModel(name, model, allDefinitions); + if (cm.interfaces == null) { + cm.interfaces = new ArrayList(); + } + + Boolean hasDefaultValues = false; + + // for (de)serializing properties renamed for Apex (e.g. reserved words) + List> propertyMappings = new ArrayList<>(); + for (CodegenProperty p : cm.allVars) { + hasDefaultValues |= p.defaultValue != null; + if (!p.baseName.equals(p.name)) { + Map 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 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 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 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."; + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index ed87bdf2998..e8c706ce79b 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -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 diff --git a/modules/swagger-codegen/src/main/resources/apex/README.mustache b/modules/swagger-codegen/src/main/resources/apex/README.mustache new file mode 100644 index 00000000000..53f2bf4fc1f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/README.mustache @@ -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 + +## 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 params = new Map{ + {{#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}} diff --git a/modules/swagger-codegen/src/main/resources/apex/Swagger.cls b/modules/swagger-codegen/src/main/resources/apex/Swagger.cls new file mode 100644 index 00000000000..0a7a1b106a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/Swagger.cls @@ -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 DELIMITERS = new Map { + '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 headers, List query); + } + + public interface MappedProperties { + Map 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 headers, List query) { + query.add(new Param(paramName, key)); + } + } + + public class ApiKeyHeaderAuth extends ApiKeyAuth { + public ApiKeyHeaderAuth(String paramName) { + this.paramName = paramName; + } + + public void apply(Map headers, List 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 headers, List 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 headers, List query) { + headers.put('Authorization', getHeaderValue()); + } + } + + public class ApiException extends Exception { + private final Integer code; + private final String status; + private final Map headers; + private final String body; + + public ApiException(Integer code, String status, Map 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 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 authentications = new Map(); + + 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 makeParams(String name, List values) { + List pairs = new List(); + for (Object value : new List(values)) { + pairs.add(new Param(name, String.valueOf(value))); + } + return pairs; + } + + public List makeParam(String name, List values, String format) { + List pairs = new List(); + if (values != null) { + String delimiter = DELIMITERS.get(format); + pairs.add(new Param(name, String.join(values, delimiter))); + } + return pairs; + } + + public List makeParam(String name, Object value) { + List pairs = new List(); + 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 query, List form, + Map pathParams, Map headers, List accepts, + List contentTypes, List 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 getHeaders(HttpResponse res) { + Map headers = new Map(); + List 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 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 query, List form, + Map pathParams, Map headers, List accepts, + List contentTypes, List 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 headers) { + for (String headerName : headers.keySet()) { + req.setHeader(headerName, String.valueOf(headers.get(headerName))); + } + } + + @TestVisible + protected virtual String toBody(String contentType, Object body, List 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 contentTypes, + Map 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 accepts, Map 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 names, Map headers, + List query) { + for (Authentication auth : getAuthMethods(names)) { + auth.apply(headers, query); + } + } + + @TestVisible + protected virtual List getAuthMethods(List names) { + List authMethods = new List(); + for (String name : names) { + authMethods.add(authentications.get(name)); + } + return authMethods; + } + + @TestVisible + protected virtual String toPath(String path, Map 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 params, + List queryParams) { + String query = '?' + paramsToString(queryParams); + return basePath + toPath(path, params) + query.removeEnd('?'); + } + + @TestVisible + protected virtual String paramsToString(List params) { + String s = ''; + for (Param p : params) { + s += '&' + p; + } + return s.removeStart('&'); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/SwaggerResponseMock.cls b/modules/swagger-codegen/src/main/resources/apex/SwaggerResponseMock.cls new file mode 100644 index 00000000000..7d3acb1a91f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/SwaggerResponseMock.cls @@ -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; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/SwaggerTest.cls b/modules/swagger-codegen/src/main/resources/apex/SwaggerTest.cls new file mode 100644 index 00000000000..dcbca6cdd94 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/SwaggerTest.cls @@ -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 headers = new Map(); + List query = new List(); + 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 headers = new Map(); + List query = new List(); + 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 headers = new Map(); + List query = new List(); + 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 headers = new Map(); + List query = new List(); + 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 headers = new Map(); + List query = new List(); + 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 values = new List{'bar', 4, false, 12.4, ''}; + Swagger.ApiClient client = new Swagger.ApiClient(); + List 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 params = client.makeParams('foo', null); + + System.assert(params.isEmpty()); + } + + @isTest + private static void ApiClient_valuesListToSingleCsvKeyValuePair() { + List values = new List{'bar', 4, false, 12.4, ''}; + Swagger.ApiClient client = new Swagger.ApiClient(); + List 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 values = new List{'bar', 4, false, 12.4, ''}; + Swagger.ApiClient client = new Swagger.ApiClient(); + List 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 values = new List{'bar', 4, false, 12.4, ''}; + Swagger.ApiClient client = new Swagger.ApiClient(); + List 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 values = new List{'bar', 4, false, 12.4, ''}; + Swagger.ApiClient client = new Swagger.ApiClient(); + List 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 params = client.makeParam('foo', null, 'csv'); + + System.assert(params.isEmpty()); + } + + @isTest + private static void ApiClient_paramsFromAnyPrimitiveTypeDiscardNull() { + Swagger.ApiClient client = new Swagger.ApiClient(); + List params = new List(); + 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 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 result1 = (Map) client + .toReturnValue(jsonBody, Map.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 headers = new Map{ + '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 body1 = new Map{ + 'hello' => 'world', + 'foo' => 15, + 'bar' => Datetime.newInstanceGmt(2017, 1, 1, 15, 0, 0), + 'bat' => false + }; + Set expected1 = new Set{ + '"hello":"world"', + '"foo":15', + '"bar":"2017-01-01T15:00:00.000Z"', + '"bat":false' + }; + Set actual1 = new Set(client + .toBody('application/json', body1, new List()) + .removeStart('{') + .removeEnd('}') + .split(',') + ); + System.assertEquals(expected1, actual1); + + String body2 = 'Hello, World!'; + String actual2 = client.toBody('text/plain', body2, new List()); + System.assertEquals(body2, actual2); + + List form = new List{ + 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 headers1 = new Map(); + List types1 = new List{'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 headers2 = new Map(); + List types2 = new List{'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 headers3 = new Map(); + String result3 = client.setContentTypeHeader(new List(), 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 headers1 = new Map(); + List types1 = new List{'application/xml', 'application/json', 'text/plain'}; + client.setAcceptHeader(types1, headers1); + System.assertEquals(1, headers1.size()); + System.assertEquals('application/json', headers1.get('Accept')); + + Map headers2 = new Map(); + List types2 = new List{'application/xml', 'text/plain'}; + client.setAcceptHeader(types2, headers2); + System.assertEquals(1, headers2.size()); + System.assertEquals('application/xml,text/plain', headers2.get('Accept')); + + Map headers3 = new Map(); + client.setAcceptHeader(new List(), headers3); + System.assert(headers3.isEmpty()); + } + + @isTest + private static void ApiClient_applyOnlyGivenAuthMethodsToParams() { + MockApiClient client = new MockApiClient(); + Map headers = new Map(); + 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{'auth2'}, headers, new List()); + + 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 params = new Map{'department' => 'finance'}; + List queryParams = new List{ + 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 { + 'title' => 'Chapter 4 quiz', + 'timed' => true, + 'time' => 60, + 'points' => 20.5, + 'due' => Datetime.newInstanceGmt(2016, 5, 10, 23, 59, 59), + 'description' => '' + }, + new List(), + new List(), + new Map{ + 'course' => 'acc321', + 'assignmentId' => 5 + }, + new Map{ + 'X-Session' => 'foo-bar-444' + }, + new List{'application/json', 'application/xml'}, + new List{'application/json', 'application/xml'}, + new List{'oauth_method'} + ); + + HttpRequest req = mock.getRequest(); + String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5'; + Set body = new Set(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(), + new List{ + 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{ + 'course' => 'acc321', + 'assignmentId' => 5 + }, + new Map{ + 'X-Session' => 'foo-bar-444' + }, + new List{'text/html', 'application/xml'}, + new List{'application/x-www-form-urlencoded'}, + new List{'oauth_method'} + ); + + HttpRequest req = mock.getRequest(); + String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments/5'; + Set body = new Set(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{ + new Swagger.Param('title', '#chapter1:section2'), + new Swagger.Param('due', '2016-05-10 18:59:59') + }, + new List(), + new Map{ + 'course' => 'acc321' + }, + new Map(), + new List{'application/xml'}, + new List{'text/plain'}, + new List{'oauth_method'} + ); + + HttpRequest req = mock.getRequest(); + List splitUrl = req.getEndpoint().split('\\?'); + String expectedUrl = 'https://www.mccombs.utexas.edu/courses/acc321/assignments'; + Set query = new Set(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(), + new List(), + new Map{ + 'course' => 'acc321' + }, + new Map(), + new List{'application/json'}, + new List{'text/plain'}, + new List{'oauth_method'}, + null + ); + } catch (Swagger.ApiException e) { + Map 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(), + new List(), + new Map(), + new Map(), + new List{'application/json'}, + new List{'text/plain'}, + new List(), + 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(), + new List(), + new Map(), + new Map(), + new List{'application/json'}, + new List{'text/plain'}, + new List(), + null + ); + + System.assertEquals(null, o); + } + + private class MockApiClient extends Swagger.ApiClient { + public MockApiClient() { + basePath = 'https://www.mccombs.utexas.edu'; + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/api.mustache b/modules/swagger-codegen/src/main/resources/apex/api.mustache new file mode 100644 index 00000000000..700c66eb15c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/api.mustache @@ -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 params{{/hasParams}}) { + {{#allParams}} + {{#required}} + client.assertNotNull(params.get('{{paramName}}'), '{{paramName}}'); + {{/required}} + {{/allParams}} + List query = new List(); + {{#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 form = new List(); + {{#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{{#hasPathParams}}{ + {{#pathParams}} + '{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}} + {{/pathParams}} + }{{/hasPathParams}}{{^hasPathParams}}(){{/hasPathParams}}, + new Map{{#hasHeaderParams}}{ + {{#headerParams}} + '{{baseName}}' => ({{{dataType}}}) params.get('{{paramName}}'){{#hasMore}},{{/hasMore}} + {{/headerParams}} + }{{/hasHeaderParams}}{{^hasHeaderParams}}(){{/hasHeaderParams}}, + {{#hasProduces}} + new List{ {{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}} }, + {{/hasProduces}} + {{^hasProduces}} + new List(), + {{/hasProduces}} + {{#hasConsumes}} + new List{ {{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}} }, + {{/hasConsumes}} + {{^hasConsumes}} + new List(), + {{/hasConsumes}} + {{#hasAuthMethods}} + new List { {{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}} }, + {{/hasAuthMethods}} + {{^hasAuthMethods}} + new List(), + {{/hasAuthMethods}} + {{#returnType}} + {{{returnType}}}.class + {{/returnType}} + {{^returnType}} + null + {{/returnType}} + ); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/apex/api_doc.mustache b/modules/swagger-codegen/src/main/resources/apex/api_doc.mustache new file mode 100644 index 00000000000..5a639d29506 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/api_doc.mustache @@ -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}} + +# **{{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 params = new Map{ + {{#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}} diff --git a/modules/swagger-codegen/src/main/resources/apex/api_test.mustache b/modules/swagger-codegen/src/main/resources/apex/api_test.mustache new file mode 100644 index 00000000000..7ddb1afd210 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/api_test.mustache @@ -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 params = new Map{ + {{#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}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/build.mustache b/modules/swagger-codegen/src/main/resources/apex/build.mustache new file mode 100644 index 00000000000..beb0fd0b326 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/build.mustache @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {{#apiInfo}} + {{#apis}} + {{classname}}Test + {{/apis}} + {{/apiInfo}} + {{#models}} + {{#model}} + {{classname}}Test + {{/model}} + {{/models}} + SwaggerTest + + + + + + + + + + + + + {{#apiInfo}} + {{#apis}} + {{classname}}Test + {{/apis}} + {{/apiInfo}} + {{#models}} + {{#model}} + {{classname}}Test + {{/model}} + {{/models}} + SwaggerTest + + + diff --git a/modules/swagger-codegen/src/main/resources/apex/build.properties b/modules/swagger-codegen/src/main/resources/apex/build.properties new file mode 100644 index 00000000000..93b38a78f55 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/build.properties @@ -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 isn’t 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 isn’t 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 aren’t 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 diff --git a/modules/swagger-codegen/src/main/resources/apex/client.mustache b/modules/swagger-codegen/src/main/resources/apex/client.mustache new file mode 100644 index 00000000000..13fd8363dba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/client.mustache @@ -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}} +} diff --git a/modules/swagger-codegen/src/main/resources/apex/cls-meta.mustache b/modules/swagger-codegen/src/main/resources/apex/cls-meta.mustache new file mode 100644 index 00000000000..c8b56e71f20 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/cls-meta.mustache @@ -0,0 +1,5 @@ + + + {{apiVersion}} + Active + diff --git a/modules/swagger-codegen/src/main/resources/apex/enum_outer_doc.mustache b/modules/swagger-codegen/src/main/resources/apex/enum_outer_doc.mustache new file mode 100644 index 00000000000..20c512aaeae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/enum_outer_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache new file mode 100644 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/git_push.sh.mustache @@ -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' + diff --git a/modules/swagger-codegen/src/main/resources/apex/gitignore.mustache b/modules/swagger-codegen/src/main/resources/apex/gitignore.mustache new file mode 100644 index 00000000000..c206f2e86e8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/gitignore.mustache @@ -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 diff --git a/modules/swagger-codegen/src/main/resources/apex/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/apex/licenseInfo.mustache new file mode 100644 index 00000000000..94c36dda3af --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/licenseInfo.mustache @@ -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. + */ diff --git a/modules/swagger-codegen/src/main/resources/apex/model.mustache b/modules/swagger-codegen/src/main/resources/apex/model.mustache new file mode 100644 index 00000000000..2c00f8eaa25 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/model.mustache @@ -0,0 +1,6 @@ +{{>licenseInfo}} +{{#models}} +{{#model}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/apex/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/apex/modelEnum.mustache new file mode 100644 index 00000000000..0de022ce854 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/modelEnum.mustache @@ -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}} +} diff --git a/modules/swagger-codegen/src/main/resources/apex/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/apex/modelInnerEnum.mustache new file mode 100644 index 00000000000..8086630e375 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/modelInnerEnum.mustache @@ -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}} + } diff --git a/modules/swagger-codegen/src/main/resources/apex/model_doc.mustache b/modules/swagger-codegen/src/main/resources/apex/model_doc.mustache new file mode 100644 index 00000000000..658df8d5322 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/model_doc.mustache @@ -0,0 +1,3 @@ +{{#models}}{{#model}} +{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/apex/model_test.mustache b/modules/swagger-codegen/src/main/resources/apex/model_test.mustache new file mode 100644 index 00000000000..7b22a41e557 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/model_test.mustache @@ -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 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}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/package.mustache b/modules/swagger-codegen/src/main/resources/apex/package.mustache new file mode 100644 index 00000000000..0d2438aac08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/package.mustache @@ -0,0 +1,31 @@ + + + {{appName}} API Client + Client library for calling the {{appName}} API.{{#appDescription}} +{{{appDescription}}}{{/appDescription}} +Generated with Swagger Codegen (github.com/swagger-api/swagger-codegen) + + {{#apiInfo}} + {{#apis}} + {{classname}} + {{classname}}Test + {{/apis}} + {{/apiInfo}} + {{#models}} + {{#model}} + {{classname}} + {{classname}}Test + {{/model}} + {{/models}} + {{classPrefix}}Client + Swagger + SwaggerTest + SwaggerResponseMock + ApexClass + + + {{sanitizedName}} + RemoteSiteSetting + + {{apiVersion}} + diff --git a/modules/swagger-codegen/src/main/resources/apex/pojo.mustache b/modules/swagger-codegen/src/main/resources/apex/pojo.mustache new file mode 100644 index 00000000000..78ad8584e59 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/pojo.mustache @@ -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 propertyMappings = new Map{ + {{#propertyMappings}} + '{{externalName}}' => '{{internalName}}'{{^-last}},{{/-last}} + {{/propertyMappings}} + }; + + public Map 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; + } +} diff --git a/modules/swagger-codegen/src/main/resources/apex/pojo_doc.mustache b/modules/swagger-codegen/src/main/resources/apex/pojo_doc.mustache new file mode 100644 index 00000000000..0e4c0749866 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/pojo_doc.mustache @@ -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}} + + +## Enum: {{datatypeWithEnum}} +Name | Value +---- | -----{{#allowableValues}}{{#enumVars}} +{{name}} | {{value}}{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/apex/remoteSite.mustache b/modules/swagger-codegen/src/main/resources/apex/remoteSite.mustache new file mode 100644 index 00000000000..eb3e7985462 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/remoteSite.mustache @@ -0,0 +1,7 @@ + +{{#shortDescription}} + {{{shortDescription}}}{{/shortDescription}} + false + true + {{basePath}} + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/apex/remove.package.mustache b/modules/swagger-codegen/src/main/resources/apex/remove.package.mustache new file mode 100644 index 00000000000..07d116e488d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/apex/remove.package.mustache @@ -0,0 +1,5 @@ + + + {{classPrefix}} API Client + {{apiVersion}} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/apex/ApexModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/apex/ApexModelTest.java new file mode 100644 index 00000000000..48d9ca79aed --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/apex/ApexModelTest.java @@ -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 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 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"); +// Assert.assertEquals(property.name, "urls"); +// Assert.assertEquals(property.defaultValue, "new ArrayList()"); +// 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"); +// Assert.assertEquals(property.name, "translations"); +// Assert.assertEquals(property.defaultValue, "new HashMap()"); +// 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>"); +// Assert.assertEquals(property.name, "translations"); +// Assert.assertEquals(property.defaultValue, "new HashMap>()"); +// 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>"); +// Assert.assertEquals(property.name, "list2D"); +// Assert.assertEquals(property.defaultValue, "new ArrayList>()"); +// 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"); +// Assert.assertEquals(property.name, "children"); +// Assert.assertEquals(property.defaultValue, "new ArrayList()"); +// 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"); +// Assert.assertEquals(property.name, "children"); +// Assert.assertEquals(property.defaultValue, "new HashMap()"); +// 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"); +// 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"); +// 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>") +// .property("map", new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty())))); +// Assert.assertEquals(cm1.vars.get(0).datatype, "Map>"); +// Assert.assertTrue(cm1.imports.contains("BigDecimal")); +// +// final CodegenModel cm2 = new JavaClientCodegen().fromModel("sample", new ModelImpl() +// .description("model with Map>>") +// .property("map", new MapProperty().additionalProperties(new MapProperty().additionalProperties(new ArrayProperty(new DecimalProperty()))))); +// Assert.assertEquals(cm2.vars.get(0).datatype, "Map>>"); +// 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); +// } + +}