remove scala-httpclient client generator (deprecated) (#15627)

This commit is contained in:
William Cheng
2023-05-24 16:39:35 +08:00
committed by GitHub
parent 2042fb222a
commit 3990b73ff3
98 changed files with 0 additions and 9658 deletions

View File

@@ -1,9 +0,0 @@
# This is for generating scala legacy client
generatorName: scala-httpclient-deprecated
outputDir: samples/client/petstore/scala-httpclient-deprecated
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/scala-httpclient
additionalProperties:
apiPackage: org.openapitools.example.api
invokerPackage: org.openapitools.example.invoker
artifactId: scala-legacy-petstore

View File

@@ -1,4 +0,0 @@
generatorName: scala-httpclient-deprecated
outputDir: samples/client/petstore/scala-httpclient
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/scala-httpclient

View File

@@ -58,7 +58,6 @@ The following generators are available:
* [rust](generators/rust.md)
* [scala-akka](generators/scala-akka.md)
* [scala-gatling](generators/scala-gatling.md)
* [scala-httpclient-deprecated (deprecated)](generators/scala-httpclient-deprecated.md)
* [scala-sttp (beta)](generators/scala-sttp.md)
* [scalaz](generators/scalaz.md)
* [swift5](generators/swift5.md)

View File

@@ -1,254 +0,0 @@
---
title: Documentation for the scala-httpclient-deprecated Generator
---
## METADATA
| Property | Value | Notes |
| -------- | ----- | ----- |
| generator name | scala-httpclient-deprecated | pass this to the generate command after -g |
| generator stability | DEPRECATED | |
| generator type | CLIENT | |
| generator language | Scala | |
| generator default templating engine | mustache | |
| helpTxt | Generates a Scala client library (beta). IMPORTANT: This generator is no longer actively maintained and will be deprecated. PLease use 'scala-akka' generator instead. | |
## CONFIG OPTIONS
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|apiPackage|package for generated api classes| |null|
|dateLibrary|Option. Date library to use|<dl><dt>**joda**</dt><dd>Joda (for legacy app)</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (preferred for JDK 1.8+)</dd></dl>|java8|
|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|<dl><dt>**false**</dt><dd>The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.</dd><dt>**true**</dt><dd>Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.</dd></dl>|true|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|<dl><dt>**false**</dt><dd>No changes to the enum's are made, this is the default option.</dd><dt>**true**</dt><dd>With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.</dd></dl>|false|
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|modelPackage|package for generated models| |null|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|sourceFolder|source folder for generated code| |null|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
|Array|java.util.List|
|ArrayList|java.util.ArrayList|
|Date|java.util.Date|
|DateTime|org.joda.time.*|
|File|java.io.File|
|HashMap|java.util.HashMap|
|ListBuffer|scala.collection.mutable.ListBuffer|
|ListSet|scala.collection.immutable.ListSet|
|LocalDate|org.joda.time.*|
|LocalDateTime|org.joda.time.*|
|LocalTime|org.joda.time.*|
|Seq|scala.collection.immutable.Seq|
|Timestamp|java.sql.Timestamp|
|URI|java.net.URI|
|UUID|java.util.UUID|
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|ListBuffer|
|map|HashMap|
|set|Set|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>Any</li>
<li>Array</li>
<li>Boolean</li>
<li>Byte</li>
<li>Double</li>
<li>Float</li>
<li>Int</li>
<li>List</li>
<li>Long</li>
<li>Map</li>
<li>Object</li>
<li>Seq</li>
<li>String</li>
<li>boolean</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abstract</li>
<li>apiinvoker</li>
<li>basepath</li>
<li>case</li>
<li>catch</li>
<li>class</li>
<li>contenttype</li>
<li>contenttypes</li>
<li>def</li>
<li>do</li>
<li>else</li>
<li>extends</li>
<li>false</li>
<li>final</li>
<li>finally</li>
<li>for</li>
<li>formparams</li>
<li>forsome</li>
<li>headerparams</li>
<li>if</li>
<li>implicit</li>
<li>import</li>
<li>lazy</li>
<li>match</li>
<li>mp</li>
<li>new</li>
<li>null</li>
<li>object</li>
<li>override</li>
<li>package</li>
<li>path</li>
<li>postbody</li>
<li>private</li>
<li>protected</li>
<li>queryparams</li>
<li>return</li>
<li>sealed</li>
<li>super</li>
<li>this</li>
<li>throw</li>
<li>trait</li>
<li>true</li>
<li>try</li>
<li>type</li>
<li>val</li>
<li>var</li>
<li>while</li>
<li>with</li>
<li>yield</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✓|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
|MockServer|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Uuid|✗|
|Array|✓|OAS2,OAS3
|Null|✗|OAS3
|AnyType|✗|OAS2,OAS3
|Object|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✓|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✗|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3
|allOf|✗|OAS2,OAS3
|anyOf|✗|OAS3
|oneOf|✗|OAS3
|not|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✗|OAS2,OAS3
|ApiKey|✗|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✗|OAS3
|OAuth2_Implicit|✗|OAS2,OAS3
|OAuth2_Password|✗|OAS2,OAS3
|OAuth2_ClientCredentials|✗|OAS2,OAS3
|OAuth2_AuthorizationCode|✗|OAS2,OAS3
|SignatureAuth|✗|OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✓|OAS2,OAS3

View File

@@ -1,212 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER;
import static org.openapitools.codegen.utils.StringUtils.camelize;
/*
* This generator has been deprecated. Please use scala-akka instead.
*/
public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements CodegenConfig {
private final Logger LOGGER = LoggerFactory.getLogger(ScalaHttpClientCodegen.class);
protected String authScheme = "";
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean authPreemptive;
protected boolean asyncHttpClient = !authScheme.isEmpty();
protected String groupId = "org.openapitools";
protected String artifactId = "openapi-scala-client";
protected String artifactVersion = "1.0.0";
protected String clientName = "AsyncClient";
public ScalaHttpClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.DEPRECATED)
.build();
modifyFeatureSet(features -> features
.includeDocumentationFeatures(DocumentationFeature.Readme)
.wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom))
.securityFeatures(EnumSet.noneOf(SecurityFeature.class))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
)
.includeClientModificationFeatures(
ClientModificationFeature.BasePath
)
);
outputFolder = "generated-code/scala-http-client";
modelTemplateFiles.put("model.mustache", ".scala");
apiTemplateFiles.put("api.mustache", ".scala");
embeddedTemplateDir = templateDir = "scala-httpclient";
apiPackage = "org.openapitools.client.api";
modelPackage = "org.openapitools.client.model";
setReservedWordsLowerCase(
Arrays.asList(
// local variable names used in API methods (endpoints)
"path", "contentTypes", "contentType", "queryParams", "headerParams",
"formParams", "postBody", "mp", "basePath", "apiInvoker",
// scala reserved words
"abstract", "case", "catch", "class", "def", "do", "else", "extends",
"false", "final", "finally", "for", "forSome", "if", "implicit",
"import", "lazy", "match", "new", "null", "object", "override", "package",
"private", "protected", "return", "sealed", "super", "this", "throw",
"trait", "try", "true", "type", "val", "var", "while", "with", "yield")
);
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("asyncHttpClient", asyncHttpClient);
additionalProperties.put("authScheme", authScheme);
additionalProperties.put("authPreemptive", authPreemptive);
additionalProperties.put("clientName", clientName);
importMapping.remove("List");
importMapping.remove("Set");
importMapping.remove("Map");
setDateLibrary("legacy",true);
importMapping.put("Date", "java.util.Date");
typeMapping = new HashMap<String, String>();
typeMapping.put("enum", "NSString");
typeMapping.put("array", "List");
typeMapping.put("set", "Set");
typeMapping.put("boolean", "Boolean");
typeMapping.put("string", "String");
typeMapping.put("int", "Int");
typeMapping.put("long", "Long");
typeMapping.put("float", "Float");
typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short");
typeMapping.put("char", "Char");
typeMapping.put("double", "Double");
typeMapping.put("object", "Any");
typeMapping.put("file", "File");
typeMapping.put("binary", "File");
typeMapping.put("ByteArray", "Array[Byte]");
typeMapping.put("ArrayByte", "Array[Byte]");
typeMapping.put("date-time", "Date");
typeMapping.put("DateTime", "Date");
instantiationTypes.put("array", "ListBuffer");
instantiationTypes.put("map", "HashMap");
}
@Override
public void processOpts() {
LOGGER.warn("IMPORTANT: This generator (scala-http-client-deprecated) is no longer actively maintained and will be deprecated. " +
"PLease use 'scala-akka' generator instead.");
super.processOpts();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
supportingFiles.add(new SupportingFile("client.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
// gradle settings
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
// gradleWrapper files
supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew"));
supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat"));
supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties"));
supportingFiles.add(new SupportingFile("gradle-wrapper.jar",
gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar"));
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public String getName() {
return "scala-httpclient-deprecated";
}
@Override
public String getHelp() {
return "Generates a Scala client library (beta). IMPORTANT: " +
"This generator is no longer actively maintained and will be deprecated. " +
"PLease use 'scala-akka' generator instead.";
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, LOWERCASE_FIRST_LETTER);
}
@Override
public String toEnumName(CodegenProperty property) {
return formatIdentifier(stripPackageName(property.baseName), true);
}
}

View File

@@ -116,7 +116,6 @@ org.openapitools.codegen.languages.ScalatraServerCodegen
org.openapitools.codegen.languages.ScalaAkkaClientCodegen
org.openapitools.codegen.languages.ScalaAkkaHttpServerCodegen
org.openapitools.codegen.languages.ScalaFinchServerCodegen
org.openapitools.codegen.languages.ScalaHttpClientCodegen
org.openapitools.codegen.languages.ScalaGatlingCodegen
org.openapitools.codegen.languages.ScalaLagomServerCodegen
org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen

View File

@@ -1,134 +0,0 @@
# NAME
{{appName}}
{{#appDescriptionWithNewLines}}
{{{.}}}
{{/appDescriptionWithNewLines}}
# VERSION
Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: {{appVersion}}
- Package version: {{moduleVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
# Requirements
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn deploy
```
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>{{{groupId}}}</groupId>
<artifactId>{{{artifactId}}}</artifactId>
<version>{{{artifactVersion}}}</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}"
```
### SBT users
```scala
libraryDependencies += "{{{groupId}}}" % "{{{artifactId}}}" % "{{{artifactVersion}}}"
```
## 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}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
<a id="documentation-for-authorization"></a>
## Documentation for Authorization
{{^authMethods}}Endpoints do not require authorization.{{/authMethods}}
{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}}
{{#authMethods}}
<a id="{{name}}"></a>
### {{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}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
# BUILDING YOUR LIBRARY
See the homepage `https://openapi-generator.tech` for full details.
But briefly, clone the git repository, build the codegen codebase, set up your build
config file, then run the API build script. You will need git, Java 7 or 8 and Apache
maven 3.0.3 or better already installed.
Your library files will be built under `WWW::MyProjectName`.
$ git clone https://github.com/openapitools/openapi-generator
$ cd openapi-generator
$ mvn package
$ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate \
-i [URL or file path to OpenAPI spec] \
-g akka-scala \
-c /path/to/config/file.json \
-o /path/to/output/folder
Bang, all done. Run the `autodoc` script in the `bin` directory to see the API
you just built.
## Author
{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
{{/-last}}{{/apis}}{{/apiInfo}}

View File

@@ -1,159 +0,0 @@
{{>licenseInfo}}
package {{package}}
import java.text.SimpleDateFormat
{{#imports}}import {{import}}
{{/imports}}
import {{invokerPackage}}.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
{{#operations}}
class {{classname}}(
val defBasePath: String = "{{{basePath}}}",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new {{classname}}AsyncHelper(client, config)
{{#operation}}
/**
* {{summary}}
* {{notes}}
*
{{#allParams}} * @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return {{{returnType}}}{{^returnType}}void{{/returnType}}
*/
def {{operationId}}({{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}Option[{{dataType}}] = None{{/required}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: Option[{{.}}]{{/returnType}} = {
val await = Try(Await.result({{operationId}}Async({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* {{summary}} asynchronously
* {{notes}}
*
{{#allParams}} * @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * @return Future({{{returnType}}}{{^returnType}}void{{/returnType}})
*/
def {{operationId}}Async({{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}Option[{{dataType}}] = None{{/required}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}: Future[{{.}}]{{/returnType}} = {
helper.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
}
{{/operation}}
}
class {{classname}}AsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
{{#operation}}
def {{operationId}}({{#allParams}}{{^required}}{{paramName}}: Option[{{dataType}}] = None{{^-last}},{{/-last}}
{{/required}}{{#required}}{{paramName}}: {{dataType}}{{^-last}},
{{/-last}}{{/required}}{{/allParams}})(implicit reader: ClientResponseReader[{{returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{^required}}Option[{{dataType}}]{{/required}}{{#required}}{{dataType}}{{/required}}]{{/bodyParams}}){{#returnType}}: Future[{{.}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = {
// create path and map variables
val path = (addFmt("{{path}}"){{#pathParams}}
replaceAll("\\{" + "{{baseName}}" + "\\}", {{paramName}}.toString){{/pathParams}})
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
{{#allParams}}
{{#required}}
{{^isPrimitiveType}}
if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
{{/isPrimitiveType}}
{{#isString}}
if ({{paramName}} == null) throw new Exception("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")
{{/isString}}
{{/required}}
{{/allParams}}
{{#queryParams}}
{{^required}}
{{paramName}} match {
case Some(param) => queryParams += "{{baseName}}" -> param.toString
case _ => queryParams
}
{{/required}}
{{#required}}
queryParams += "{{baseName}}" -> {{paramName}}.toString
{{/required}}
{{/queryParams}}
{{#headerParams}}
{{^required}}
{{paramName}} match {
case Some(param) => headerParams += "{{baseName}}" -> param.toString
case _ => headerParams
}
{{/required}}
{{#required}}
headerParams += "{{baseName}}" -> {{paramName}}.toString
{{/required}}
{{/headerParams}}
val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{paramName}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}})
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
{{/operation}}
}
{{/operations}}

View File

@@ -1,226 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import com.sun.jersey.core.util.MultivaluedMapImpl
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import java.io.File
import java.net.URLEncoder
import java.util.UUID
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders
def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def escape(values: List[String]): String = {
values.map(escape).mkString(",")
}
def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString
def escape(value: UUID): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case _ =>
json match {
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else {
null
}
}
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => {
if (!headerParams.contains(p._1) && p._2 != null) {
builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.foreach(p => formData.add(p._1, p._2))
}
val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse])
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if Range(200, 299).contains(code) =>
if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
""
}
case _ =>
val entity = if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
"no data"
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}
def getClient(host: String): Client = {
if (hostMap.contains(host)) {
hostMap(host)
} else {
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
def newClient(host: String): Client = if (asyncHttpClient) {
import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
} else {
Client.create()
}
}
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = {{asyncHttpClient}},
authScheme = "{{authScheme}}",
authPreemptive = {{authPreemptive}}
)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -1,131 +0,0 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
}
}
repositories {
mavenCentral()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
dependencies {
provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'scala'
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
publishing {
publications {
maven(MavenPublication) {
artifactId = '{{artifactId}}'
from components.java
}
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
scala_version = "2.10.4"
jakarta_annotation_version = "1.3.5"
joda_version = "1.2"
jodatime_version = "2.2"
jersey_version = "1.19"
swagger_core_version = "1.5.8"
jersey_async_version = "1.0.5"
jackson_version = "2.4.2"
junit_version = "4.8.1"
scala_test_version = "2.2.4"
swagger_async_httpclient_version = "0.3.5"
}
repositories {
mavenLocal()
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version"
compile "com.sun.jersey:jersey-client:$jersey_version"
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "org.jfarcand:jersey-ahc-client:$jersey_async_version"
compile "org.scala-lang:scala-library:$scala_version"
compile "io.swagger:swagger-core:$swagger_core_version"
testCompile "org.scalatest:scalatest_2.10:$scala_test_version"
testCompile "junit:junit:$junit_version"
compile "joda-time:joda-time:$jodatime_version"
compile "org.joda:joda-convert:$joda_version"
compile "com.wordnik.swagger:swagger-async-httpclient_2.10:$swagger_async_httpclient_version"
}

View File

@@ -1,31 +0,0 @@
version := "{{artifactVersion}}"
name := "{{artifactId}}"
organization := "{{groupId}}"
scalaVersion := "2.11.12"
libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9",
"com.sun.jersey" % "jersey-core" % "1.19.4",
"com.sun.jersey" % "jersey-client" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4",
"org.jfarcand" % "jersey-ahc-client" % "1.0.5",
"io.swagger" % "swagger-core" % "1.5.8",
"joda-time" % "joda-time" % "2.9.9",
"org.joda" % "joda-convert" % "1.9.2",
"org.scalatest" %% "scalatest" % "3.0.4" % "test",
"junit" % "junit" % "4.13" % "test",
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
)
resolvers ++= Seq(
Resolver.mavenLocal
)
scalacOptions := Seq(
"-unchecked",
"-deprecation",
"-feature"
)
publishArtifact in (Compile, packageDoc) := false

View File

@@ -1,22 +0,0 @@
package {{invokerPackage}}
{{#imports}}import {{import}}
{{/imports}}
import {{apiPackage}}._
import com.wordnik.swagger.client._
import java.io.Closeable
class {{clientName}}(config: SwaggerConfig) extends Closeable {
lazy val locator: ServiceLocator = config.locator
lazy val name: String = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
def close() {
client.close()
}
}

View File

@@ -1,57 +0,0 @@
#!/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 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="{{{gitHost}}}"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
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 credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -1,22 +0,0 @@
# scala specific
*.class
*.log
# sbt specific
.cache
.history
.lib/
dist/*
target/
lib_managed/
src_managed/
project/boot/
project/plugins/project/
# Scala-IDE specific
.scala_dependencies
.worksheet
# IntelliJ specific
.idea
*.iml

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,2 +0,0 @@
# Uncomment to build for Android
#target = android

View File

@@ -1,84 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -1,11 +0,0 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}}
* {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@@ -1,20 +0,0 @@
{{>licenseInfo}}
package {{package}}
{{#imports}}
import {{import}}
{{/imports}}
{{#models}}
{{#model}}
case class {{classname}} (
{{#vars}}
{{#description}}
// {{{.}}}
{{/description}}
{{{name}}}: {{^required}}Option[{{/required}}{{dataType}}{{^required}}] = None{{/required}}{{^-last}},{{/-last}}
{{/vars}}
)
{{/model}}
{{/models}}

View File

@@ -1,255 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<pluginRepositories>
<pluginRepository>
<id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name>
<!-- TODO: this URL does not exist. -->
<url>https://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M1</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>2.2.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</version>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms128m</jvmArg>
<jvmArg>-Xmx1500m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala-version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.jfarcand</groupId>
<artifactId>jersey-ahc-client</artifactId>
<version>${jersey-async-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.11</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time-version}</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>${joda-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik.swagger</groupId>
<artifactId>swagger-async-httpclient_2.11</artifactId>
<version>${async-httpclient-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.11.12</scala-version>
<joda-version>1.9.2</joda-version>
<joda-time-version>2.9.9</joda-time-version>
<jersey-version>1.19.4</jersey-version>
<swagger-core-version>1.5.18</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.9.9</jackson-version>
<junit-version>4.13</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>3.0.4</scala-test-version>
<async-httpclient-version>0.3.5</async-httpclient-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1 +0,0 @@
rootProject.name = "{{artifactId}}"

View File

@@ -1,327 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.scalahttpclient;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.ScalaHttpClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class ScalaHttpClientModelTest {
@Test(description = "convert a simple scala model")
public void simpleModelTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
.addProperties("name", new StringSchema())
.addProperties("createdAt", new DateTimeSchema())
.addRequiredItem("id")
.addRequiredItem("name");
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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(), 3);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.getter, "getId");
Assert.assertEquals(property1.setter, "setId");
Assert.assertEquals(property1.dataType, "Long");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "Long");
Assert.assertTrue(property1.required);
Assert.assertFalse(property1.isContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.getter, "getName");
Assert.assertEquals(property2.setter, "setName");
Assert.assertEquals(property2.dataType, "String");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "String");
Assert.assertTrue(property2.required);
Assert.assertFalse(property2.isContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.getter, "getCreatedAt");
Assert.assertEquals(property3.setter, "setCreatedAt");
Assert.assertEquals(property3.dataType, "Date");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "Date");
Assert.assertFalse(property3.required);
Assert.assertFalse(property3.isContainer);
}
@Test(description = "convert a model with list property")
public void listPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
.addProperties("urls", new ArraySchema()
.items(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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 property1 = cm.vars.get(1);
Assert.assertEquals(property1.baseName, "urls");
Assert.assertEquals(property1.getter, "getUrls");
Assert.assertEquals(property1.setter, "setUrls");
Assert.assertEquals(property1.dataType, "List[String]");
Assert.assertEquals(property1.name, "urls");
Assert.assertEquals(property1.defaultValue, "new ListBuffer[String]() ");
Assert.assertEquals(property1.baseType, "List");
Assert.assertEquals(property1.containerType, "array");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with set (unique array) property")
public void complexSetPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new ArraySchema()
.items(new Schema().$ref("#/definitions/Children"))
.uniqueItems(Boolean.TRUE));
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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 property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.getter, "getChildren");
Assert.assertEquals(property1.setter, "setChildren");
Assert.assertEquals(property1.dataType, "Set[Children]");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.defaultValue, "Set.empty[Children] ");
Assert.assertEquals(property1.baseType, "Set");
Assert.assertEquals(property1.containerType, "set");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("translations", new MapSchema()
.additionalProperties(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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 property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "translations");
Assert.assertEquals(property1.getter, "getTranslations");
Assert.assertEquals(property1.setter, "setTranslations");
Assert.assertEquals(property1.dataType, "Map[String, String]");
Assert.assertEquals(property1.name, "translations");
Assert.assertEquals(property1.defaultValue, "new HashMap[String, String]() ");
Assert.assertEquals(property1.baseType, "Map");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with complex properties")
public void complexPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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 property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.getter, "getChildren");
Assert.assertEquals(property1.setter, "setChildren");
Assert.assertEquals(property1.dataType, "Children");
Assert.assertEquals(property1.name, "children");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "Children");
Assert.assertFalse(property1.required);
Assert.assertFalse(property1.isContainer);
}
@Test(description = "convert a model with complex list property")
public void complexListPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new ArraySchema()
.items(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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 property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.getter, "getChildren");
Assert.assertEquals(property1.setter, "setChildren");
Assert.assertEquals(property1.dataType, "List[Children]");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.defaultValue, "new ListBuffer[Children]() ");
Assert.assertEquals(property1.baseType, "List");
Assert.assertEquals(property1.containerType, "array");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with complex map property")
public void complexMapPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new MapSchema()
.additionalProperties(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
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("Children")).size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.getter, "getChildren");
Assert.assertEquals(property1.setter, "setChildren");
Assert.assertEquals(property1.dataType, "Map[String, Children]");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.defaultValue, "new HashMap[String, Children]() ");
Assert.assertEquals(property1.baseType, "Map");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert an array model")
public void arrayModelTest() {
final Schema schema = new ArraySchema()
.items(new Schema().$ref("#/definitions/Children"))
.description("an array model");
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", schema);
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, "ListBuffer[Children]");
Assert.assertEquals(cm.imports.size(), 2);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ListBuffer", "Children")).size(), 2);
}
@Test(description = "convert an array model with unique items to set")
public void arrayAsSetModelTest() {
final Schema schema = new ArraySchema()
.items(new Schema().$ref("#/definitions/Children"))
.description("a set of Children models");
schema.setUniqueItems(true);
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", schema);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a set of Children models");
Assert.assertEquals(cm.vars.size(), 0);
Assert.assertEquals(cm.parent, "Set[Children]");
Assert.assertEquals(cm.arrayModelType, "Children");
Assert.assertEquals(cm.imports.size(), 2);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Set", "Children")).size(), 2);
}
@Test(description = "convert a map model")
public void mapModelTest() {
final Schema model = new Schema()
.description("a map model")
.additionalProperties(new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new ScalaHttpClientCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a map model");
Assert.assertEquals(cm.vars.size(), 0);
Assert.assertEquals(cm.parent, "HashMap[String, Children]");
Assert.assertEquals(cm.imports.size(), 2);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("HashMap", "Children")).size(), 2);
}
}

View File

@@ -1,53 +0,0 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.scalahttpclient;
import org.openapitools.codegen.AbstractOptionsTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.ScalaHttpClientCodegen;
import org.openapitools.codegen.options.ScalaHttpClientOptionsProvider;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class ScalaHttpClientOptionsTest extends AbstractOptionsTest {
private ScalaHttpClientCodegen clientCodegen = mock(ScalaHttpClientCodegen.class, mockSettings);
public ScalaHttpClientOptionsTest() {
super(new ScalaHttpClientOptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void verifyOptions() {
verify(clientCodegen).setModelPackage(ScalaHttpClientOptionsProvider.MODEL_PACKAGE_VALUE);
verify(clientCodegen).setApiPackage(ScalaHttpClientOptionsProvider.API_PACKAGE_VALUE);
verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(ScalaHttpClientOptionsProvider.SORT_PARAMS_VALUE));
verify(clientCodegen).setModelPropertyNaming(ScalaHttpClientOptionsProvider.MODEL_PROPERTY_NAMING);
verify(clientCodegen).setSourceFolder(ScalaHttpClientOptionsProvider.SOURCE_FOLDER_VALUE);
verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(ScalaHttpClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE));
verify(clientCodegen).setDateLibrary(ScalaHttpClientOptionsProvider.DATE_LIBRARY,false);
verify(clientCodegen).setEnumUnknownDefaultCase(Boolean.parseBoolean(ScalaHttpClientOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE));
}
}

View File

@@ -1,22 +0,0 @@
# scala specific
*.class
*.log
# sbt specific
.cache
.history
.lib/
dist/*
target/
lib_managed/
src_managed/
project/boot/
project/plugins/project/
# Scala-IDE specific
.scala_dependencies
.worksheet
# IntelliJ specific
.idea
*.iml

View File

@@ -1,23 +0,0 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -1,22 +0,0 @@
.gitignore
build.gradle
build.sbt
git_push.sh
gradle.properties
gradle/wrapper/gradle-wrapper.jar
gradle/wrapper/gradle-wrapper.properties
gradlew
gradlew.bat
pom.xml
settings.gradle
src/main/scala/org/openapitools/client/model/ApiResponse.scala
src/main/scala/org/openapitools/client/model/Category.scala
src/main/scala/org/openapitools/client/model/Order.scala
src/main/scala/org/openapitools/client/model/Pet.scala
src/main/scala/org/openapitools/client/model/Tag.scala
src/main/scala/org/openapitools/client/model/User.scala
src/main/scala/org/openapitools/example/api/PetApi.scala
src/main/scala/org/openapitools/example/api/StoreApi.scala
src/main/scala/org/openapitools/example/api/UserApi.scala
src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala
src/main/scala/org/openapitools/example/invoker/AsyncClient.scala

View File

@@ -1,131 +0,0 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = 'org.openapitools'
version = '1.0.0'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
}
}
repositories {
mavenCentral()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
dependencies {
provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'scala'
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
publishing {
publications {
maven(MavenPublication) {
artifactId = 'scala-legacy-petstore'
from components.java
}
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
scala_version = "2.10.4"
jakarta_annotation_version = "1.3.5"
joda_version = "1.2"
jodatime_version = "2.2"
jersey_version = "1.19"
swagger_core_version = "1.5.8"
jersey_async_version = "1.0.5"
jackson_version = "2.4.2"
junit_version = "4.8.1"
scala_test_version = "2.2.4"
swagger_async_httpclient_version = "0.3.5"
}
repositories {
mavenLocal()
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version"
compile "com.sun.jersey:jersey-client:$jersey_version"
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "org.jfarcand:jersey-ahc-client:$jersey_async_version"
compile "org.scala-lang:scala-library:$scala_version"
compile "io.swagger:swagger-core:$swagger_core_version"
testCompile "org.scalatest:scalatest_2.10:$scala_test_version"
testCompile "junit:junit:$junit_version"
compile "joda-time:joda-time:$jodatime_version"
compile "org.joda:joda-convert:$joda_version"
compile "com.wordnik.swagger:swagger-async-httpclient_2.10:$swagger_async_httpclient_version"
}

View File

@@ -1,31 +0,0 @@
version := "1.0.0"
name := "scala-legacy-petstore"
organization := "org.openapitools"
scalaVersion := "2.11.12"
libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9",
"com.sun.jersey" % "jersey-core" % "1.19.4",
"com.sun.jersey" % "jersey-client" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4",
"org.jfarcand" % "jersey-ahc-client" % "1.0.5",
"io.swagger" % "swagger-core" % "1.5.8",
"joda-time" % "joda-time" % "2.9.9",
"org.joda" % "joda-convert" % "1.9.2",
"org.scalatest" %% "scalatest" % "3.0.4" % "test",
"junit" % "junit" % "4.13" % "test",
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
)
resolvers ++= Seq(
Resolver.mavenLocal
)
scalacOptions := Seq(
"-unchecked",
"-deprecation",
"-feature"
)
publishArtifact in (Compile, packageDoc) := false

View File

@@ -1,57 +0,0 @@
#!/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 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
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 credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -1,2 +0,0 @@
# Uncomment to build for Android
#target = android

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -1,84 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,255 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>scala-legacy-petstore</artifactId>
<packaging>jar</packaging>
<name>scala-legacy-petstore</name>
<version>1.0.0</version>
<pluginRepositories>
<pluginRepository>
<id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name>
<!-- TODO: this URL does not exist. -->
<url>https://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M1</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>2.2.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</version>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms128m</jvmArg>
<jvmArg>-Xmx1500m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala-version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.jfarcand</groupId>
<artifactId>jersey-ahc-client</artifactId>
<version>${jersey-async-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.11</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time-version}</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>${joda-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik.swagger</groupId>
<artifactId>swagger-async-httpclient_2.11</artifactId>
<version>${async-httpclient-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.11.12</scala-version>
<joda-version>1.9.2</joda-version>
<joda-time-version>2.9.9</joda-time-version>
<jersey-version>1.19.4</jersey-version>
<swagger-core-version>1.5.18</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.9.9</jackson-version>
<junit-version>4.13</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>3.0.4</scala-test-version>
<async-httpclient-version>0.3.5</async-httpclient-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1 +0,0 @@
rootProject.name = "scala-legacy-petstore"

View File

@@ -1,237 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.example.invoker
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import com.sun.jersey.core.util.MultivaluedMapImpl
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import java.io.File
import java.net.URLEncoder
import java.util.UUID
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders
def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def escape(values: List[String]): String = {
values.map(escape).mkString(",")
}
def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString
def escape(value: UUID): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case _ =>
json match {
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else {
null
}
}
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => {
if (!headerParams.contains(p._1) && p._2 != null) {
builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.foreach(p => formData.add(p._1, p._2))
}
val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse])
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if Range(200, 299).contains(code) =>
if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
""
}
case _ =>
val entity = if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
"no data"
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}
def getClient(host: String): Client = {
if (hostMap.contains(host)) {
hostMap(host)
} else {
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
def newClient(host: String): Client = if (asyncHttpClient) {
import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
} else {
Client.create()
}
}
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = false,
authScheme = "",
authPreemptive = false
)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -1,20 +0,0 @@
package org.openapitools.example.invoker
import org.openapitools.example.api._
import com.wordnik.swagger.client._
import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable {
lazy val locator: ServiceLocator = config.locator
lazy val name: String = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
def close() {
client.close()
}
}

View File

@@ -1,21 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class ApiResponse (
code: Option[Integer] = None,
`type`: Option[String] = None,
message: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Category (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,22 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class InlineObject (
// Updated name of the pet
name: Option[String] = None,
// Updated status of the pet
status: Option[String] = None
)

View File

@@ -1,23 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import java.io.File
case class InlineObject1 (
// Additional data to pass to server
additionalMetadata: Option[String] = None,
// file to upload
file: Option[File] = None
)

View File

@@ -1,26 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import java.util.Date
case class Order (
id: Option[Long] = None,
petId: Option[Long] = None,
quantity: Option[Integer] = None,
shipDate: Option[Date] = None,
// Order Status
status: Option[String] = None,
complete: Option[Boolean] = None
)

View File

@@ -1,25 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Pet (
id: Option[Long] = None,
category: Option[Category] = None,
name: String,
photoUrls: List[String],
tags: Option[List[Tag]] = None,
// pet status in the store
status: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Tag (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,27 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class User (
id: Option[Long] = None,
username: Option[String] = None,
firstName: Option[String] = None,
lastName: Option[String] = None,
email: Option[String] = None,
password: Option[String] = None,
phone: Option[String] = None,
// User Status
userStatus: Option[Integer] = None
)

View File

@@ -1,476 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.example.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.ApiResponse
import java.io.File
import org.openapitools.client.model.Pet
import org.openapitools.example.invoker.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class PetApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new PetApiAsyncHelper(client, config)
/**
* Add a new pet to the store
*
*
* @param pet Pet object that needs to be added to the store
* @return Pet
*/
def addPet(pet: Pet): Option[Pet] = {
val await = Try(Await.result(addPetAsync(pet), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Add a new pet to the store asynchronously
*
*
* @param pet Pet object that needs to be added to the store
* @return Future(Pet)
*/
def addPetAsync(pet: Pet): Future[Pet] = {
helper.addPet(pet)
}
/**
* Deletes a pet
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
*/
def deletePet(petId: Long, apiKey: Option[String] = None) = {
val await = Try(Await.result(deletePetAsync(petId, apiKey), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Deletes a pet asynchronously
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return Future(void)
*/
def deletePetAsync(petId: Long, apiKey: Option[String] = None) = {
helper.deletePet(petId, apiKey)
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return List[Pet]
*/
def findPetsByStatus(status: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByStatusAsync(status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by status asynchronously
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return Future(List[Pet])
*/
def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = {
helper.findPetsByStatus(status)
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return List[Pet]
*/
def findPetsByTags(tags: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByTagsAsync(tags), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by tags asynchronously
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return Future(List[Pet])
*/
def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = {
helper.findPetsByTags(tags)
}
/**
* Find pet by ID
* Returns a single pet
*
* @param petId ID of pet to return
* @return Pet
*/
def getPetById(petId: Long): Option[Pet] = {
val await = Try(Await.result(getPetByIdAsync(petId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find pet by ID asynchronously
* Returns a single pet
*
* @param petId ID of pet to return
* @return Future(Pet)
*/
def getPetByIdAsync(petId: Long): Future[Pet] = {
helper.getPetById(petId)
}
/**
* Update an existing pet
*
*
* @param pet Pet object that needs to be added to the store
* @return Pet
*/
def updatePet(pet: Pet): Option[Pet] = {
val await = Try(Await.result(updatePetAsync(pet), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Update an existing pet asynchronously
*
*
* @param pet Pet object that needs to be added to the store
* @return Future(Pet)
*/
def updatePetAsync(pet: Pet): Future[Pet] = {
helper.updatePet(pet)
}
/**
* Updates a pet in the store with form data
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return void
*/
def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
val await = Try(Await.result(updatePetWithFormAsync(petId, name, status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updates a pet in the store with form data asynchronously
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return Future(void)
*/
def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
helper.updatePetWithForm(petId, name, status)
}
/**
* uploads an image
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ApiResponse
*/
def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = {
val await = Try(Await.result(uploadFileAsync(petId, additionalMetadata, file), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* uploads an image asynchronously
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return Future(ApiResponse)
*/
def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = {
helper.uploadFile(petId, additionalMetadata, file)
}
}
class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def addPet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->addPet")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(pet))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deletePet(petId: Long,
apiKey: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
apiKey match {
case Some(param) => headerParams += "api_key" -> param.toString
case _ => headerParams
}
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByStatus"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus")
queryParams += "status" -> status.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByTags"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags")
queryParams += "tags" -> tags.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->updatePet")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(pet))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePetWithForm(petId: Long,
name: Option[String] = None,
status: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def uploadFile(petId: Long,
additionalMetadata: Option[String] = None,
file: Option[File] = None
)(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = {
// create path and map variables
val path = (addFmt("/pet/{petId}/uploadImage")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,265 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.example.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.Order
import org.openapitools.example.invoker.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class StoreApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new StoreApiAsyncHelper(client, config)
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return void
*/
def deleteOrder(orderId: String) = {
val await = Try(Await.result(deleteOrderAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete purchase order by ID asynchronously
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return Future(void)
*/
def deleteOrderAsync(orderId: String) = {
helper.deleteOrder(orderId)
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*
* @return Map[String, Integer]
*/
def getInventory(): Option[Map[String, Integer]] = {
val await = Try(Await.result(getInventoryAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Returns pet inventories by status asynchronously
* Returns a map of status codes to quantities
*
* @return Future(Map[String, Integer])
*/
def getInventoryAsync(): Future[Map[String, Integer]] = {
helper.getInventory()
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
def getOrderById(orderId: Long): Option[Order] = {
val await = Try(Await.result(getOrderByIdAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find purchase order by ID asynchronously
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Future(Order)
*/
def getOrderByIdAsync(orderId: Long): Future[Order] = {
helper.getOrderById(orderId)
}
/**
* Place an order for a pet
*
*
* @param order order placed for purchasing the pet
* @return Order
*/
def placeOrder(order: Order): Option[Order] = {
val await = Try(Await.result(placeOrderAsync(order), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Place an order for a pet asynchronously
*
*
* @param order order placed for purchasing the pet
* @return Future(Order)
*/
def placeOrderAsync(order: Order): Future[Order] = {
helper.placeOrder(order)
}
}
class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = {
// create path and map variables
val path = (addFmt("/store/inventory"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def placeOrder(order: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (order == null) throw new Exception("Missing required parameter 'order' when calling StoreApi->placeOrder")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(order))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,466 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.example.api
import java.text.SimpleDateFormat
import java.util.Date
import org.openapitools.client.model.User
import org.openapitools.example.invoker.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class UserApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new UserApiAsyncHelper(client, config)
/**
* Create user
* This can only be done by the logged in user.
*
* @param user Created user object
* @return void
*/
def createUser(user: User) = {
val await = Try(Await.result(createUserAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Create user asynchronously
* This can only be done by the logged in user.
*
* @param user Created user object
* @return Future(void)
*/
def createUserAsync(user: User) = {
helper.createUser(user)
}
/**
* Creates list of users with given input array
*
*
* @param user List of user object
* @return void
*/
def createUsersWithArrayInput(user: List[User]) = {
val await = Try(Await.result(createUsersWithArrayInputAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param user List of user object
* @return Future(void)
*/
def createUsersWithArrayInputAsync(user: List[User]) = {
helper.createUsersWithArrayInput(user)
}
/**
* Creates list of users with given input array
*
*
* @param user List of user object
* @return void
*/
def createUsersWithListInput(user: List[User]) = {
val await = Try(Await.result(createUsersWithListInputAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param user List of user object
* @return Future(void)
*/
def createUsersWithListInputAsync(user: List[User]) = {
helper.createUsersWithListInput(user)
}
/**
* Delete user
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return void
*/
def deleteUser(username: String) = {
val await = Try(Await.result(deleteUserAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete user asynchronously
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return Future(void)
*/
def deleteUserAsync(username: String) = {
helper.deleteUser(username)
}
/**
* Get user by user name
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
def getUserByName(username: String): Option[User] = {
val await = Try(Await.result(getUserByNameAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Get user by user name asynchronously
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return Future(User)
*/
def getUserByNameAsync(username: String): Future[User] = {
helper.getUserByName(username)
}
/**
* Logs user into the system
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
def loginUser(username: String, password: String): Option[String] = {
val await = Try(Await.result(loginUserAsync(username, password), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs user into the system asynchronously
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return Future(String)
*/
def loginUserAsync(username: String, password: String): Future[String] = {
helper.loginUser(username, password)
}
/**
* Logs out current logged in user session
*
*
* @return void
*/
def logoutUser() = {
val await = Try(Await.result(logoutUserAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs out current logged in user session asynchronously
*
*
* @return Future(void)
*/
def logoutUserAsync() = {
helper.logoutUser()
}
/**
* Updated user
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param user Updated user object
* @return void
*/
def updateUser(username: String, user: User) = {
val await = Try(Await.result(updateUserAsync(username, user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updated user asynchronously
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param user Updated user object
* @return Future(void)
*/
def updateUserAsync(username: String, user: User) = {
helper.updateUser(username, user)
}
}
class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def createUser(user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUser")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithArrayInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithArray"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithArrayInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithListInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithList"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithListInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName")
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def loginUser(username: String,
password: String)(implicit reader: ClientResponseReader[String]): Future[String] = {
// create path and map variables
val path = (addFmt("/user/login"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser")
if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser")
queryParams += "username" -> username.toString
queryParams += "password" -> password.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/logout"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updateUser(username: String,
user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser")
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->updateUser")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,237 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.example.invoker
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import com.sun.jersey.core.util.MultivaluedMapImpl
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import java.io.File
import java.net.URLEncoder
import java.util.UUID
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders
def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def escape(values: List[String]): String = {
values.map(escape).mkString(",")
}
def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString
def escape(value: UUID): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case _ =>
json match {
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else {
null
}
}
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => {
if (!headerParams.contains(p._1) && p._2 != null) {
builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.foreach(p => formData.add(p._1, p._2))
}
val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse])
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if Range(200, 299).contains(code) =>
if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
""
}
case _ =>
val entity = if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
"no data"
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}
def getClient(host: String): Client = {
if (hostMap.contains(host)) {
hostMap(host)
} else {
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
def newClient(host: String): Client = if (asyncHttpClient) {
import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
} else {
Client.create()
}
}
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = false,
authScheme = "",
authPreemptive = false
)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -1,20 +0,0 @@
package org.openapitools.example.invoker
import org.openapitools.example.api._
import com.wordnik.swagger.client._
import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable {
lazy val locator: ServiceLocator = config.locator
lazy val name: String = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
def close() {
client.close()
}
}

View File

@@ -1,22 +0,0 @@
# scala specific
*.class
*.log
# sbt specific
.cache
.history
.lib/
dist/*
target/
lib_managed/
src_managed/
project/boot/
project/plugins/project/
# Scala-IDE specific
.scala_dependencies
.worksheet
# IntelliJ specific
.idea
*.iml

View File

@@ -1,23 +0,0 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -1,94 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
@RunWith(classOf[JUnitRunner])
class PetApiTest extends FlatSpec with Matchers {
behavior of "PetApi"
val api = new PetApi
it should "add and fetch a pet" in {
val pet = Pet(
Some(1000),
Some(Category(Some(1), Some("sold"))),
"dragon",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList,
Some((for (i <- (1 to 5)) yield org.openapitools.client.model.Tag(Some(i), Some("tag-" + i))).toList),
Some("lost")
)
api.addPet(pet)
api.getPetById(1000) match {
case Some(pet) => {
pet.id should be(Some(1000))
pet.tags.get.size should be(5)
pet.status should be(Some("lost"))
pet.category should not be (null)
pet.category.get.name should be(Some("sold"))
pet.name should be("dragon")
pet.photoUrls.size should be(10)
}
case None => fail("didn't find pet created")
}
}
it should "update a pet" in {
val pet = Pet(
Some(1000),
Some(Category(Some(1), Some("sold"))),
"programmer",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList,
Some((for (i <- (1 to 5)) yield org.openapitools.client.model.Tag(Some(i), Some("tag-" + i))).toList),
Some("confused")
)
api.addPet(pet)
api.getPetById(1000) match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be(Some("confused"))
}
case None => fail("didn't find pet created")
}
val updatedPet = pet.copy(status = Some("fulfilled"))
api.updatePet(updatedPet)
api.getPetById(1000) match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be(Some("fulfilled"))
}
case None => fail("didn't find pet updated")
}
}
it should "find pets by status" in {
api.findPetsByStatus(List("available")) match {
case Some(pets) => {
pets.foreach(pet => pet.status should be("available"))
}
case None => fail("didn't find pets by status")
}
}
it should "find pets by tag" in {
api.findPetsByTags(List("tag1", "tag2")) match {
case Some(pets) => {
pets.foreach(pet => {
val tags = (for (tag <- pet.tags.get) yield tag.name).toSet
if ((tags & Set(Some("tag1"), Some("tag2"))).size == 0)
fail("unexpected tags in " + tags)
})
}
case None => fail("didn't find pets by tag")
}
}
}

View File

@@ -1,71 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.joda.time.DateTime
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
import java.util.Date
@RunWith(classOf[JUnitRunner])
class StoreApiTest extends FlatSpec with Matchers {
behavior of "StoreApi"
val api = new StoreApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
it should "place and fetch an order" in {
val now = new Date()
val order = Order(
petId = Some(10),
id = Some(1000),
quantity = Some(101),
status = Some("pending"),
shipDate = Some(now),
complete = Some(true))
api.placeOrder(order)
api.getOrderById(1000) match {
case Some(order) => {
order.id.get should be(1000)
order.petId.get should be(10)
order.quantity.get should be(101)
order.shipDate.get.getTime().equals(now.getTime()) should be(true)
}
case None => fail("didn't find order created")
}
}
it should "delete an order" in {
val now = new Date()
val order = Order(
id = Some(1001),
petId = Some(10),
quantity = Some(101),
status = Some("pending"),
shipDate = Some(now),
complete = Some(true))
api.placeOrder(order)
api.getOrderById(1001) match {
case Some(order) => order.id should be(Some(1001))
case None => fail("didn't find order created")
}
api.deleteOrder("1001")
/* comment out the following as the client cannot handle
* 4xx response yet
api.getOrderById(1001) match {
case Some(order) => fail("order should have been deleted")
case None =>
}
*/
}
}

View File

@@ -1,150 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
@RunWith(classOf[JUnitRunner])
class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll {
behavior of "UserApi"
val api = new UserApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
// preparation before running a test
override def beforeAll() {
val user = User(
Some(11222),
Some("scala-test-username"),
Some("scala-test-first"),
Some("scala-test-last"),
Some("scala_test@fail.com"),
Some("SCALATEST"),
Some("408-867-5309"),
Some(1))
api.createUser(user)
}
// cleanup after running a test
override def afterAll() {
api.deleteUser("scala-test-username")
}
it should "fetch a user" in {
api.getUserByName("scala-test-username") match {
case Some(user) => {
user.id should be(Some(11222))
user.username should be(Some("scala-test-username"))
user.password should be(Some("SCALATEST"))
user.email should be(Some("scala_test@fail.com"))
user.firstName should be(Some("scala-test-first"))
user.lastName should be(Some("scala-test-last"))
user.phone should be(Some("408-867-5309"))
user.userStatus should be(Some(1))
}
case None =>
}
}
it should "authenticate a user" in {
api.loginUser("scala-test-username", "SCALATEST") match {
case Some(status) => status.contains("logged in user session") match {
case true => // success!
case _ => fail("didn't get expected message " + status)
}
case None => fail("not able to login")
}
}
it should "log out a user" in {
api.logoutUser
}
it should "create 2 users" in {
val userArray = (for (i <- (1 to 2)) yield {
User(
Some(2000 + i),
Some("johnny-" + i),
Some("Johnny"),
Some("Rocket-" + i),
Some("johnny-" + i + "@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
}).toList
api.createUsersWithArrayInput(userArray)
for (i <- (1 to 2)) {
api.getUserByName("johnny-" + i) match {
case Some(user) => {
user.id should be(Some(2000 + i))
user.email should be(Some("johnny-" + i + "@fail.com"))
}
case None => fail("didn't find user " + i)
}
}
}
it should "create 3 users" in {
val userList = (for (i <- (1 to 3)) yield {
User(
Some(3000 + i),
Some("fred-" + i),
Some("Johnny"),
Some("Rocket-" + i),
Some("fred-" + i + "@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
}).toList
api.createUsersWithListInput(userList)
for (i <- (1 to 3)) {
api.getUserByName("fred-" + i) match {
case Some(user) => {
user.id should be(Some(3000 + i))
user.email should be(Some("fred-" + i + "@fail.com"))
}
case None => fail("didn't find user " + i)
}
}
}
it should "update a user" in {
val user = User(
Some(4000),
Some("tony"),
Some("Tony"),
Some("Tiger"),
Some("tony@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
api.createUser(user)
api.getUserByName("tony") match {
case Some(user) => {
user.id should be(Some(4000))
user.username should be(Some("tony"))
}
case None =>
}
val updatedUser = user.copy(email = Some("tony@succeed.com"))
api.updateUser("tony", updatedUser)
api.getUserByName("tony") match {
case Some(user) => {
user.email should be(Some("tony@succeed.com"))
}
case None =>
}
}
}

View File

@@ -1,237 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import com.sun.jersey.core.util.MultivaluedMapImpl
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import java.io.File
import java.net.URLEncoder
import java.util.UUID
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders
def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def escape(values: List[String]): String = {
values.map(escape).mkString(",")
}
def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString
def escape(value: UUID): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case _ =>
json match {
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else {
null
}
}
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => {
if (!headerParams.contains(p._1) && p._2 != null) {
builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.foreach(p => formData.add(p._1, p._2))
}
val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse])
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if Range(200, 299).contains(code) =>
if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
""
}
case _ =>
val entity = if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
"no data"
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}
def getClient(host: String): Client = {
if (hostMap.contains(host)) {
hostMap(host)
} else {
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
def newClient(host: String): Client = if (asyncHttpClient) {
import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
} else {
Client.create()
}
}
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = false,
authScheme = "",
authPreemptive = false
)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -1,20 +0,0 @@
package org.openapitools.client
import org.openapitools.client.api._
import com.wordnik.swagger.client._
import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable {
lazy val locator: ServiceLocator = config.locator
lazy val name: String = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
def close() {
client.close()
}
}

View File

@@ -1,476 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.ApiResponse
import java.io.File
import org.openapitools.client.model.Pet
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class PetApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new PetApiAsyncHelper(client, config)
/**
* Add a new pet to the store
*
*
* @param body Pet object that needs to be added to the store
* @return void
*/
def addPet(body: Pet) = {
val await = Try(Await.result(addPetAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Add a new pet to the store asynchronously
*
*
* @param body Pet object that needs to be added to the store
* @return Future(void)
*/
def addPetAsync(body: Pet) = {
helper.addPet(body)
}
/**
* Deletes a pet
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
*/
def deletePet(petId: Long, apiKey: Option[String] = None) = {
val await = Try(Await.result(deletePetAsync(petId, apiKey), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Deletes a pet asynchronously
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return Future(void)
*/
def deletePetAsync(petId: Long, apiKey: Option[String] = None) = {
helper.deletePet(petId, apiKey)
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return List[Pet]
*/
def findPetsByStatus(status: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByStatusAsync(status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by status asynchronously
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return Future(List[Pet])
*/
def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = {
helper.findPetsByStatus(status)
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return List[Pet]
*/
def findPetsByTags(tags: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByTagsAsync(tags), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by tags asynchronously
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return Future(List[Pet])
*/
def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = {
helper.findPetsByTags(tags)
}
/**
* Find pet by ID
* Returns a single pet
*
* @param petId ID of pet to return
* @return Pet
*/
def getPetById(petId: Long): Option[Pet] = {
val await = Try(Await.result(getPetByIdAsync(petId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find pet by ID asynchronously
* Returns a single pet
*
* @param petId ID of pet to return
* @return Future(Pet)
*/
def getPetByIdAsync(petId: Long): Future[Pet] = {
helper.getPetById(petId)
}
/**
* Update an existing pet
*
*
* @param body Pet object that needs to be added to the store
* @return void
*/
def updatePet(body: Pet) = {
val await = Try(Await.result(updatePetAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Update an existing pet asynchronously
*
*
* @param body Pet object that needs to be added to the store
* @return Future(void)
*/
def updatePetAsync(body: Pet) = {
helper.updatePet(body)
}
/**
* Updates a pet in the store with form data
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return void
*/
def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
val await = Try(Await.result(updatePetWithFormAsync(petId, name, status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updates a pet in the store with form data asynchronously
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return Future(void)
*/
def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
helper.updatePetWithForm(petId, name, status)
}
/**
* uploads an image
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ApiResponse
*/
def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = {
val await = Try(Await.result(uploadFileAsync(petId, additionalMetadata, file), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* uploads an image asynchronously
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return Future(ApiResponse)
*/
def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = {
helper.uploadFile(petId, additionalMetadata, file)
}
}
class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def addPet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->addPet")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deletePet(petId: Long,
apiKey: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
apiKey match {
case Some(param) => headerParams += "api_key" -> param.toString
case _ => headerParams
}
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByStatus"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus")
queryParams += "status" -> status.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByTags"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags")
queryParams += "tags" -> tags.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling PetApi->updatePet")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePetWithForm(petId: Long,
name: Option[String] = None,
status: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def uploadFile(petId: Long,
additionalMetadata: Option[String] = None,
file: Option[File] = None
)(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = {
// create path and map variables
val path = (addFmt("/pet/{petId}/uploadImage")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,265 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.Order
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class StoreApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new StoreApiAsyncHelper(client, config)
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return void
*/
def deleteOrder(orderId: String) = {
val await = Try(Await.result(deleteOrderAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete purchase order by ID asynchronously
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return Future(void)
*/
def deleteOrderAsync(orderId: String) = {
helper.deleteOrder(orderId)
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*
* @return Map[String, Integer]
*/
def getInventory(): Option[Map[String, Integer]] = {
val await = Try(Await.result(getInventoryAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Returns pet inventories by status asynchronously
* Returns a map of status codes to quantities
*
* @return Future(Map[String, Integer])
*/
def getInventoryAsync(): Future[Map[String, Integer]] = {
helper.getInventory()
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
def getOrderById(orderId: Long): Option[Order] = {
val await = Try(Await.result(getOrderByIdAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find purchase order by ID asynchronously
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Future(Order)
*/
def getOrderByIdAsync(orderId: Long): Future[Order] = {
helper.getOrderById(orderId)
}
/**
* Place an order for a pet
*
*
* @param body order placed for purchasing the pet
* @return Order
*/
def placeOrder(body: Order): Option[Order] = {
val await = Try(Await.result(placeOrderAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Place an order for a pet asynchronously
*
*
* @param body order placed for purchasing the pet
* @return Future(Order)
*/
def placeOrderAsync(body: Order): Future[Order] = {
helper.placeOrder(body)
}
}
class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = {
// create path and map variables
val path = (addFmt("/store/inventory"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def placeOrder(body: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling StoreApi->placeOrder")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,465 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.User
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class UserApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new UserApiAsyncHelper(client, config)
/**
* Create user
* This can only be done by the logged in user.
*
* @param body Created user object
* @return void
*/
def createUser(body: User) = {
val await = Try(Await.result(createUserAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Create user asynchronously
* This can only be done by the logged in user.
*
* @param body Created user object
* @return Future(void)
*/
def createUserAsync(body: User) = {
helper.createUser(body)
}
/**
* Creates list of users with given input array
*
*
* @param body List of user object
* @return void
*/
def createUsersWithArrayInput(body: List[User]) = {
val await = Try(Await.result(createUsersWithArrayInputAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param body List of user object
* @return Future(void)
*/
def createUsersWithArrayInputAsync(body: List[User]) = {
helper.createUsersWithArrayInput(body)
}
/**
* Creates list of users with given input array
*
*
* @param body List of user object
* @return void
*/
def createUsersWithListInput(body: List[User]) = {
val await = Try(Await.result(createUsersWithListInputAsync(body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param body List of user object
* @return Future(void)
*/
def createUsersWithListInputAsync(body: List[User]) = {
helper.createUsersWithListInput(body)
}
/**
* Delete user
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return void
*/
def deleteUser(username: String) = {
val await = Try(Await.result(deleteUserAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete user asynchronously
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return Future(void)
*/
def deleteUserAsync(username: String) = {
helper.deleteUser(username)
}
/**
* Get user by user name
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
def getUserByName(username: String): Option[User] = {
val await = Try(Await.result(getUserByNameAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Get user by user name asynchronously
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return Future(User)
*/
def getUserByNameAsync(username: String): Future[User] = {
helper.getUserByName(username)
}
/**
* Logs user into the system
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
def loginUser(username: String, password: String): Option[String] = {
val await = Try(Await.result(loginUserAsync(username, password), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs user into the system asynchronously
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return Future(String)
*/
def loginUserAsync(username: String, password: String): Future[String] = {
helper.loginUser(username, password)
}
/**
* Logs out current logged in user session
*
*
* @return void
*/
def logoutUser() = {
val await = Try(Await.result(logoutUserAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs out current logged in user session asynchronously
*
*
* @return Future(void)
*/
def logoutUserAsync() = {
helper.logoutUser()
}
/**
* Updated user
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param body Updated user object
* @return void
*/
def updateUser(username: String, body: User) = {
val await = Try(Await.result(updateUserAsync(username, body), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updated user asynchronously
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param body Updated user object
* @return Future(void)
*/
def updateUserAsync(username: String, body: User) = {
helper.updateUser(username, body)
}
}
class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def createUser(body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUser")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithArrayInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithArray"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithArrayInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithListInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithList"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->createUsersWithListInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName")
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def loginUser(username: String,
password: String)(implicit reader: ClientResponseReader[String]): Future[String] = {
// create path and map variables
val path = (addFmt("/user/login"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser")
if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser")
queryParams += "username" -> username.toString
queryParams += "password" -> password.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/logout"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updateUser(username: String,
body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser")
if (body == null) throw new Exception("Missing required parameter 'body' when calling UserApi->updateUser")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,21 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class ApiResponse (
code: Option[Integer] = None,
`type`: Option[String] = None,
message: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Category (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,26 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import java.util.Date
case class Order (
id: Option[Long] = None,
petId: Option[Long] = None,
quantity: Option[Integer] = None,
shipDate: Option[Date] = None,
// Order Status
status: Option[String] = None,
complete: Option[Boolean] = None
)

View File

@@ -1,25 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Pet (
id: Option[Long] = None,
category: Option[Category] = None,
name: String,
photoUrls: List[String],
tags: Option[List[Tag]] = None,
// pet status in the store
status: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Tag (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,27 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class User (
id: Option[Long] = None,
username: Option[String] = None,
firstName: Option[String] = None,
lastName: Option[String] = None,
email: Option[String] = None,
password: Option[String] = None,
phone: Option[String] = None,
// User Status
userStatus: Option[Integer] = None
)

View File

@@ -1,130 +0,0 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = 'org.openapitools'
version = '1.0.0'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
}
}
repositories {
mavenCentral()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
dependencies {
provided 'javax.annotation:jsr250-api:1.0'
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'scala'
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
publishing {
publications {
maven(MavenPublication) {
artifactId = 'openapi-scala-client'
from components.java
}
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
scala_version = "2.10.4"
joda_version = "1.2"
jodatime_version = "2.2"
jersey_version = "1.19"
swagger_core_version = "1.5.8"
jersey_async_version = "1.0.5"
jackson_version = "2.4.2"
junit_version = "4.8.1"
scala_test_version = "2.2.4"
swagger_async_httpclient_version = "0.3.5"
}
repositories {
mavenLocal()
maven { url "https://repo1.maven.org/maven2" }
}
dependencies {
compileOnly "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version"
compileOnly "com.sun.jersey:jersey-client:$jersey_version"
compileOnly "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compileOnly "org.jfarcand:jersey-ahc-client:$jersey_async_version"
compileOnly "org.scala-lang:scala-library:$scala_version"
compileOnly "io.swagger:swagger-core:$swagger_core_version"
testCompileOnly "org.scalatest:scalatest_2.10:$scala_test_version"
testCompileOnly "junit:junit:$junit_version"
compileOnly "joda-time:joda-time:$jodatime_version"
compileOnly "org.joda:joda-convert:$joda_version"
compileOnly "com.wordnik.swagger:swagger-async-httpclient_2.10:$swagger_async_httpclient_version"
}

View File

@@ -1,32 +0,0 @@
version := "1.0.0"
name := "openapi-scala-client"
organization := "org.openapitools"
scalaVersion := "2.11.12"
libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.13.2",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.13.2",
"com.sun.jersey" % "jersey-core" % "1.19.4",
"com.sun.jersey" % "jersey-client" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4",
"org.jfarcand" % "jersey-ahc-client" % "1.0.5",
"io.swagger" % "swagger-core" % "1.5.8",
"joda-time" % "joda-time" % "2.9.9",
"org.joda" % "joda-convert" % "1.9.2",
"org.scalatest" %% "scalatest" % "3.2.11" % "test",
"junit" % "junit" % "4.13" % "test",
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
)
resolvers ++= Seq(
Resolver.mavenLocal
)
scalacOptions := Seq(
"-unchecked",
"-deprecation",
"-feature"
)
publishArtifact in (Compile, packageDoc) := false

View File

@@ -1,58 +0,0 @@
#!/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 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
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 credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -1,2 +0,0 @@
# Uncomment to build for Android
#target = android

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,234 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -1,89 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,277 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>openapi-scala-client</artifactId>
<packaging>jar</packaging>
<name>openapi-scala-client</name>
<version>1.0.0</version>
<pluginRepositories>
<pluginRepository>
<id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name>
<!-- TODO: this URL does not exist. -->
<url>https://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M1</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>2.2.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</version>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms128m</jvmArg>
<jvmArg>-Xmx1500m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.5.0</version>
<executions>
<execution>
<id>sbt-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>sbt</executable>
<arguments>
<argument>-ivy</argument>
<argument>${user.home}/.ivy2</argument>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala-version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-scala_2.11</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.jfarcand</groupId>
<artifactId>jersey-ahc-client</artifactId>
<version>${jersey-async-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.11</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time-version}</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>${joda-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik.swagger</groupId>
<artifactId>swagger-async-httpclient_2.11</artifactId>
<version>${async-httpclient-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.11.12</scala-version>
<joda-version>1.9.2</joda-version>
<joda-time-version>2.9.9</joda-time-version>
<jersey-version>1.19.4</jersey-version>
<swagger-core-version>1.5.18</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.9.9</jackson-version>
<junit-version>4.13</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>3.0.4</scala-test-version>
<async-httpclient-version>0.3.5</async-httpclient-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -1 +0,0 @@
rootProject.name = "openapi-scala-client"

View File

@@ -1,237 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import com.sun.jersey.core.util.MultivaluedMapImpl
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import java.io.File
import java.net.URLEncoder
import java.util.UUID
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(),
hostMap: mutable.HashMap[String, Client] = mutable.HashMap(),
asyncHttpClient: Boolean = false,
authScheme: String = "",
authPreemptive: Boolean = false
) {
var defaultHeaders: mutable.HashMap[String, String] = httpHeaders
def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def escape(values: List[String]): String = {
values.map(escape).mkString(",")
}
def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString
def escape(value: UUID): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String =>
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) {
s.substring(1, s.length - 1)
} else {
s
}
case _ => null
}
} else {
containerType.toLowerCase match {
case "array" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case "list" =>
val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
case _ =>
json match {
case e: String if "\"\"" == e => null
case _ => mapper.readValue(json, cls)
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else {
null
}
}
def invokeApi(
host: String,
path: String,
method: String,
queryParams: Map[String, String],
formParams: Map[String, String],
body: AnyRef,
headerParams: Map[String, String],
contentType: String
): String = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => {
if (!headerParams.contains(p._1) && p._2 != null) {
builder.header(p._1, p._2)
}
})
var formData: MultivaluedMapImpl = null
if (contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl()
formParams.foreach(p => formData.add(p._1, p._2))
}
val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse])
case "POST" =>
if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData)
} else if (body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File]
val form = new FormDataMultiPart()
form.field("filename", file.getName)
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form)
} else {
if (body == null) {
builder.post(classOf[ClientResponse], serialize(body))
} else {
builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
}
case "PUT" =>
if (formData != null) {
builder.post(classOf[ClientResponse], formData)
} else if (body == null) {
builder.put(classOf[ClientResponse], null)
} else {
builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => builder.delete(classOf[ClientResponse])
case "PATCH" =>
if(formData != null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData)
} else if(body == null) {
builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null)
} else {
builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body))
}
case _ => null
}
response.getStatusInfo.getStatusCode match {
case 204 => ""
case code: Int if Range(200, 299).contains(code) =>
if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
""
}
case _ =>
val entity = if (response.hasEntity) {
response.getEntity(classOf[String])
} else {
"no data"
}
throw new ApiException(response.getStatusInfo.getStatusCode, entity)
}
}
def getClient(host: String): Client = {
if (hostMap.contains(host)) {
hostMap(host)
} else {
val client = newClient(host)
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
def newClient(host: String): Client = if (asyncHttpClient) {
import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config
.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build)
}
AhcHttpClient.create(config)
} else {
Client.create()
}
}
object ApiInvoker extends ApiInvoker(
mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = mutable.HashMap(),
hostMap = mutable.HashMap(),
asyncHttpClient = false,
authScheme = "",
authPreemptive = false
)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -1,20 +0,0 @@
package org.openapitools.client
import org.openapitools.client.api._
import com.wordnik.swagger.client._
import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable {
lazy val locator: ServiceLocator = config.locator
lazy val name: String = config.name
private[this] val client = transportClient
protected def transportClient: TransportClient = new RestClient(config)
def close() {
client.close()
}
}

View File

@@ -1,476 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.ApiResponse
import java.io.File
import org.openapitools.client.model.Pet
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class PetApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new PetApiAsyncHelper(client, config)
/**
* Add a new pet to the store
*
*
* @param pet Pet object that needs to be added to the store
* @return Pet
*/
def addPet(pet: Pet): Option[Pet] = {
val await = Try(Await.result(addPetAsync(pet), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Add a new pet to the store asynchronously
*
*
* @param pet Pet object that needs to be added to the store
* @return Future(Pet)
*/
def addPetAsync(pet: Pet): Future[Pet] = {
helper.addPet(pet)
}
/**
* Deletes a pet
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return void
*/
def deletePet(petId: Long, apiKey: Option[String] = None) = {
val await = Try(Await.result(deletePetAsync(petId, apiKey), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Deletes a pet asynchronously
*
*
* @param petId Pet id to delete
* @param apiKey (optional)
* @return Future(void)
*/
def deletePetAsync(petId: Long, apiKey: Option[String] = None) = {
helper.deletePet(petId, apiKey)
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return List[Pet]
*/
def findPetsByStatus(status: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByStatusAsync(status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by status asynchronously
* Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter
* @return Future(List[Pet])
*/
def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = {
helper.findPetsByStatus(status)
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return List[Pet]
*/
def findPetsByTags(tags: List[String]): Option[List[Pet]] = {
val await = Try(Await.result(findPetsByTagsAsync(tags), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Finds Pets by tags asynchronously
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by
* @return Future(List[Pet])
*/
def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = {
helper.findPetsByTags(tags)
}
/**
* Find pet by ID
* Returns a single pet
*
* @param petId ID of pet to return
* @return Pet
*/
def getPetById(petId: Long): Option[Pet] = {
val await = Try(Await.result(getPetByIdAsync(petId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find pet by ID asynchronously
* Returns a single pet
*
* @param petId ID of pet to return
* @return Future(Pet)
*/
def getPetByIdAsync(petId: Long): Future[Pet] = {
helper.getPetById(petId)
}
/**
* Update an existing pet
*
*
* @param pet Pet object that needs to be added to the store
* @return Pet
*/
def updatePet(pet: Pet): Option[Pet] = {
val await = Try(Await.result(updatePetAsync(pet), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Update an existing pet asynchronously
*
*
* @param pet Pet object that needs to be added to the store
* @return Future(Pet)
*/
def updatePetAsync(pet: Pet): Future[Pet] = {
helper.updatePet(pet)
}
/**
* Updates a pet in the store with form data
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return void
*/
def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
val await = Try(Await.result(updatePetWithFormAsync(petId, name, status), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updates a pet in the store with form data asynchronously
*
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return Future(void)
*/
def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
helper.updatePetWithForm(petId, name, status)
}
/**
* uploads an image
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ApiResponse
*/
def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = {
val await = Try(Await.result(uploadFileAsync(petId, additionalMetadata, file), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* uploads an image asynchronously
*
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return Future(ApiResponse)
*/
def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = {
helper.uploadFile(petId, additionalMetadata, file)
}
}
class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def addPet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->addPet")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(pet))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deletePet(petId: Long,
apiKey: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
apiKey match {
case Some(param) => headerParams += "api_key" -> param.toString
case _ => headerParams
}
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByStatus"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus")
queryParams += "status" -> status.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = {
// create path and map variables
val path = (addFmt("/pet/findByTags"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags")
queryParams += "tags" -> tags.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = {
// create path and map variables
val path = (addFmt("/pet"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->updatePet")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(pet))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updatePetWithForm(petId: Long,
name: Option[String] = None,
status: Option[String] = None
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/pet/{petId}")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def uploadFile(petId: Long,
additionalMetadata: Option[String] = None,
file: Option[File] = None
)(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = {
// create path and map variables
val path = (addFmt("/pet/{petId}/uploadImage")
replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,265 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.Order
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class StoreApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new StoreApiAsyncHelper(client, config)
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return void
*/
def deleteOrder(orderId: String) = {
val await = Try(Await.result(deleteOrderAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete purchase order by ID asynchronously
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted
* @return Future(void)
*/
def deleteOrderAsync(orderId: String) = {
helper.deleteOrder(orderId)
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*
* @return Map[String, Integer]
*/
def getInventory(): Option[Map[String, Integer]] = {
val await = Try(Await.result(getInventoryAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Returns pet inventories by status asynchronously
* Returns a map of status codes to quantities
*
* @return Future(Map[String, Integer])
*/
def getInventoryAsync(): Future[Map[String, Integer]] = {
helper.getInventory()
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
def getOrderById(orderId: Long): Option[Order] = {
val await = Try(Await.result(getOrderByIdAsync(orderId), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Find purchase order by ID asynchronously
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
*
* @param orderId ID of pet that needs to be fetched
* @return Future(Order)
*/
def getOrderByIdAsync(orderId: Long): Future[Order] = {
helper.getOrderById(orderId)
}
/**
* Place an order for a pet
*
*
* @param order order placed for purchasing the pet
* @return Order
*/
def placeOrder(order: Order): Option[Order] = {
val await = Try(Await.result(placeOrderAsync(order), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Place an order for a pet asynchronously
*
*
* @param order order placed for purchasing the pet
* @return Future(Order)
*/
def placeOrderAsync(order: Order): Future[Order] = {
helper.placeOrder(order)
}
}
class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = {
// create path and map variables
val path = (addFmt("/store/inventory"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order/{orderId}")
replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def placeOrder(order: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = {
// create path and map variables
val path = (addFmt("/store/order"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (order == null) throw new Exception("Missing required parameter 'order' when calling StoreApi->placeOrder")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(order))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,465 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import java.text.SimpleDateFormat
import org.openapitools.client.model.User
import org.openapitools.client.{ApiInvoker, ApiException}
import collection.mutable
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import com.wordnik.swagger.client._
import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._
import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._
import javax.ws.rs.core.Response.Status.Family
import java.net.URI
import java.io.File
import java.util.Date
import java.util.TimeZone
import javax.ws.rs.core.{MediaType, Response}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scala.collection.mutable.HashMap
import scala.util.{Failure, Success, Try}
import org.json4s._
class UserApi(
val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker
) {
private lazy val dateTimeFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
private val dateFormatter = {
val formatter = new SimpleDateFormat("yyyy-MM-dd")
formatter.setTimeZone(TimeZone.getTimeZone("UTC"))
formatter
}
implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = dateTimeFormatter
}
implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker
def addHeader(key: String, value: String): mutable.HashMap[String, String] = {
apiInvoker.defaultHeaders += key -> value
}
val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config)
val helper = new UserApiAsyncHelper(client, config)
/**
* Create user
* This can only be done by the logged in user.
*
* @param user Created user object
* @return void
*/
def createUser(user: User) = {
val await = Try(Await.result(createUserAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Create user asynchronously
* This can only be done by the logged in user.
*
* @param user Created user object
* @return Future(void)
*/
def createUserAsync(user: User) = {
helper.createUser(user)
}
/**
* Creates list of users with given input array
*
*
* @param user List of user object
* @return void
*/
def createUsersWithArrayInput(user: List[User]) = {
val await = Try(Await.result(createUsersWithArrayInputAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param user List of user object
* @return Future(void)
*/
def createUsersWithArrayInputAsync(user: List[User]) = {
helper.createUsersWithArrayInput(user)
}
/**
* Creates list of users with given input array
*
*
* @param user List of user object
* @return void
*/
def createUsersWithListInput(user: List[User]) = {
val await = Try(Await.result(createUsersWithListInputAsync(user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Creates list of users with given input array asynchronously
*
*
* @param user List of user object
* @return Future(void)
*/
def createUsersWithListInputAsync(user: List[User]) = {
helper.createUsersWithListInput(user)
}
/**
* Delete user
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return void
*/
def deleteUser(username: String) = {
val await = Try(Await.result(deleteUserAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Delete user asynchronously
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return Future(void)
*/
def deleteUserAsync(username: String) = {
helper.deleteUser(username)
}
/**
* Get user by user name
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
def getUserByName(username: String): Option[User] = {
val await = Try(Await.result(getUserByNameAsync(username), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Get user by user name asynchronously
*
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return Future(User)
*/
def getUserByNameAsync(username: String): Future[User] = {
helper.getUserByName(username)
}
/**
* Logs user into the system
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
def loginUser(username: String, password: String): Option[String] = {
val await = Try(Await.result(loginUserAsync(username, password), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs user into the system asynchronously
*
*
* @param username The user name for login
* @param password The password for login in clear text
* @return Future(String)
*/
def loginUserAsync(username: String, password: String): Future[String] = {
helper.loginUser(username, password)
}
/**
* Logs out current logged in user session
*
*
* @return void
*/
def logoutUser() = {
val await = Try(Await.result(logoutUserAsync(), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Logs out current logged in user session asynchronously
*
*
* @return Future(void)
*/
def logoutUserAsync() = {
helper.logoutUser()
}
/**
* Updated user
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param user Updated user object
* @return void
*/
def updateUser(username: String, user: User) = {
val await = Try(Await.result(updateUserAsync(username, user), Duration.Inf))
await match {
case Success(i) => Some(await.get)
case Failure(t) => None
}
}
/**
* Updated user asynchronously
* This can only be done by the logged in user.
*
* @param username name that need to be deleted
* @param user Updated user object
* @return Future(void)
*/
def updateUserAsync(username: String, user: User) = {
helper.updateUser(username, user)
}
}
class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) {
def createUser(user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUser")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithArrayInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithArray"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithArrayInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def createUsersWithListInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/createWithList"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithListInput")
val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser")
val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName")
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def loginUser(username: String,
password: String)(implicit reader: ClientResponseReader[String]): Future[String] = {
// create path and map variables
val path = (addFmt("/user/login"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser")
if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser")
queryParams += "username" -> username.toString
queryParams += "password" -> password.toString
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/logout"))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "")
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
def updateUser(username: String,
user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables
val path = (addFmt("/user/{username}")
replaceAll("\\{" + "username" + "\\}", username.toString))
// query params
val queryParams = new mutable.HashMap[String, String]
val headerParams = new mutable.HashMap[String, String]
if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser")
if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->updateUser")
val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(user))
resFuture flatMap { resp =>
val status = Response.Status.fromStatusCode(resp.statusCode)
status.getFamily match {
case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp))
case _ => throw new ApiException(resp.statusCode, resp.statusText)
}
}
}
}

View File

@@ -1,21 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class ApiResponse (
code: Option[Integer] = None,
`type`: Option[String] = None,
message: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Category (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,22 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class InlineObject (
// Updated name of the pet
name: Option[String] = None,
// Updated status of the pet
status: Option[String] = None
)

View File

@@ -1,23 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import java.io.File
case class InlineObject1 (
// Additional data to pass to server
additionalMetadata: Option[String] = None,
// file to upload
file: Option[File] = None
)

View File

@@ -1,26 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
import java.util.Date
case class Order (
id: Option[Long] = None,
petId: Option[Long] = None,
quantity: Option[Integer] = None,
shipDate: Option[Date] = None,
// Order Status
status: Option[String] = None,
complete: Option[Boolean] = None
)

View File

@@ -1,25 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Pet (
id: Option[Long] = None,
category: Option[Category] = None,
name: String,
photoUrls: List[String],
tags: Option[List[Tag]] = None,
// pet status in the store
status: Option[String] = None
)

View File

@@ -1,20 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class Tag (
id: Option[Long] = None,
name: Option[String] = None
)

View File

@@ -1,27 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model
case class User (
id: Option[Long] = None,
username: Option[String] = None,
firstName: Option[String] = None,
lastName: Option[String] = None,
email: Option[String] = None,
password: Option[String] = None,
phone: Option[String] = None,
// User Status
userStatus: Option[Integer] = None
)

View File

@@ -1,94 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
@RunWith(classOf[JUnitRunner])
class PetApiTest extends FlatSpec with Matchers {
behavior of "PetApi"
val api = new PetApi
it should "add and fetch a pet" in {
val pet = Pet(
Some(1000),
Some(Category(Some(1), Some("sold"))),
"dragon",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList,
Some((for (i <- (1 to 5)) yield org.openapitools.client.model.Tag(Some(i), Some("tag-" + i))).toList),
Some("lost")
)
api.addPet(pet)
api.getPetById(1000) match {
case Some(pet) => {
pet.id should be(Some(1000))
pet.tags.get.size should be(5)
pet.status should be(Some("lost"))
pet.category should not be (null)
pet.category.get.name should be(Some("sold"))
pet.name should be("dragon")
pet.photoUrls.size should be(10)
}
case None => fail("didn't find pet created")
}
}
it should "update a pet" in {
val pet = Pet(
Some(1000),
Some(Category(Some(1), Some("sold"))),
"programmer",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList,
Some((for (i <- (1 to 5)) yield org.openapitools.client.model.Tag(Some(i), Some("tag-" + i))).toList),
Some("confused")
)
api.addPet(pet)
api.getPetById(1000) match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be(Some("confused"))
}
case None => fail("didn't find pet created")
}
val updatedPet = pet.copy(status = Some("fulfilled"))
api.updatePet(updatedPet)
api.getPetById(1000) match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be(Some("fulfilled"))
}
case None => fail("didn't find pet updated")
}
}
it should "find pets by status" in {
api.findPetsByStatus(List("available")) match {
case Some(pets) => {
pets.foreach(pet => pet.status should be("available"))
}
case None => fail("didn't find pets by status")
}
}
it should "find pets by tag" in {
api.findPetsByTags(List("tag1", "tag2")) match {
case Some(pets) => {
pets.foreach(pet => {
val tags = (for (tag <- pet.tags.get) yield tag.name).toSet
if ((tags & Set(Some("tag1"), Some("tag2"))).size == 0)
fail("unexpected tags in " + tags)
})
}
case None => fail("didn't find pets by tag")
}
}
}

View File

@@ -1,71 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.joda.time.DateTime
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
import java.util.Date
@RunWith(classOf[JUnitRunner])
class StoreApiTest extends FlatSpec with Matchers {
behavior of "StoreApi"
val api = new StoreApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
it should "place and fetch an order" in {
val now = new Date()
val order = Order(
petId = Some(10),
id = Some(1000),
quantity = Some(101),
status = Some("pending"),
shipDate = Some(now),
complete = Some(true))
api.placeOrder(order)
api.getOrderById(1000) match {
case Some(order) => {
order.id.get should be(1000)
order.petId.get should be(10)
order.quantity.get should be(101)
order.shipDate.get.getTime().equals(now.getTime()) should be(true)
}
case None => fail("didn't find order created")
}
}
it should "delete an order" in {
val now = new Date()
val order = Order(
id = Some(1001),
petId = Some(10),
quantity = Some(101),
status = Some("pending"),
shipDate = Some(now),
complete = Some(true))
api.placeOrder(order)
api.getOrderById(1001) match {
case Some(order) => order.id should be(Some(1001))
case None => fail("didn't find order created")
}
api.deleteOrder("1001")
/* comment out the following as the client cannot handle
* 4xx response yet
api.getOrderById(1001) match {
case Some(order) => fail("order should have been deleted")
case None =>
}
*/
}
}

View File

@@ -1,150 +0,0 @@
import org.openapitools.client._
import org.openapitools.client.api._
import org.openapitools.client.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest._
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.beans.BeanProperty
@RunWith(classOf[JUnitRunner])
class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll {
behavior of "UserApi"
val api = new UserApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
// preparation before running a test
override def beforeAll() {
val user = User(
Some(11222),
Some("scala-test-username"),
Some("scala-test-first"),
Some("scala-test-last"),
Some("scala_test@fail.com"),
Some("SCALATEST"),
Some("408-867-5309"),
Some(1))
api.createUser(user)
}
// cleanup after running a test
override def afterAll() {
api.deleteUser("scala-test-username")
}
it should "fetch a user" in {
api.getUserByName("scala-test-username") match {
case Some(user) => {
user.id should be(Some(11222))
user.username should be(Some("scala-test-username"))
user.password should be(Some("SCALATEST"))
user.email should be(Some("scala_test@fail.com"))
user.firstName should be(Some("scala-test-first"))
user.lastName should be(Some("scala-test-last"))
user.phone should be(Some("408-867-5309"))
user.userStatus should be(Some(1))
}
case None =>
}
}
it should "authenticate a user" in {
api.loginUser("scala-test-username", "SCALATEST") match {
case Some(status) => status.contains("logged in user session") match {
case true => // success!
case _ => fail("didn't get expected message " + status)
}
case None => fail("not able to login")
}
}
it should "log out a user" in {
api.logoutUser
}
it should "create 2 users" in {
val userArray = (for (i <- (1 to 2)) yield {
User(
Some(2000 + i),
Some("johnny-" + i),
Some("Johnny"),
Some("Rocket-" + i),
Some("johnny-" + i + "@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
}).toList
api.createUsersWithArrayInput(userArray)
for (i <- (1 to 2)) {
api.getUserByName("johnny-" + i) match {
case Some(user) => {
user.id should be(Some(2000 + i))
user.email should be(Some("johnny-" + i + "@fail.com"))
}
case None => fail("didn't find user " + i)
}
}
}
it should "create 3 users" in {
val userList = (for (i <- (1 to 3)) yield {
User(
Some(3000 + i),
Some("fred-" + i),
Some("Johnny"),
Some("Rocket-" + i),
Some("fred-" + i + "@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
}).toList
api.createUsersWithListInput(userList)
for (i <- (1 to 3)) {
api.getUserByName("fred-" + i) match {
case Some(user) => {
user.id should be(Some(3000 + i))
user.email should be(Some("fred-" + i + "@fail.com"))
}
case None => fail("didn't find user " + i)
}
}
}
it should "update a user" in {
val user = User(
Some(4000),
Some("tony"),
Some("Tony"),
Some("Tiger"),
Some("tony@fail.com"),
Some("XXXXXXXXXXX"),
Some("408-867-5309"),
Some(1))
api.createUser(user)
api.getUserByName("tony") match {
case Some(user) => {
user.id should be(Some(4000))
user.username should be(Some("tony"))
}
case None =>
}
val updatedUser = user.copy(email = Some("tony@succeed.com"))
api.updateUser("tony", updatedUser)
api.getUserByName("tony") match {
case Some(user) => {
user.email should be(Some("tony@succeed.com"))
}
case None =>
}
}
}