updated versions

This commit is contained in:
fehguy
2015-06-09 00:25:09 -07:00
parent 33c2b1b623
commit 3d2f09a693
180 changed files with 22318 additions and 26364 deletions

View File

@@ -3,7 +3,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.1</version> <version>2.1.2</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.1</version> <version>2.1.2</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@@ -4,7 +4,7 @@
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<version>2.1.1</version> <version>2.1.2</version>
<relativePath>../..</relativePath> <relativePath>../..</relativePath>
</parent> </parent>
<artifactId>swagger-generator</artifactId> <artifactId>swagger-generator</artifactId>

View File

@@ -10,7 +10,7 @@
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>swagger-codegen-project</name> <name>swagger-codegen-project</name>
<version>2.1.1</version> <version>2.1.2</version>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-codegen.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-codegen.git</connection>

View File

@@ -1,85 +1,87 @@
group = 'io.swagger' group = 'io.swagger'
project.version = '1.0.0' project.version = '1.0.0'
buildscript { buildscript {
repositories { repositories {
jcenter() jcenter()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:1.2.2' classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
} classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
} }
allprojects { allprojects {
repositories { repositories {
jcenter() jcenter()
} }
} }
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'com.github.dcendents.android-maven'
android { android {
compileSdkVersion 22 compileSdkVersion 22
buildToolsVersion '22.0.0' buildToolsVersion '22.0.0'
defaultConfig { defaultConfig {
minSdkVersion 14 minSdkVersion 14
targetSdkVersion 22 targetSdkVersion 22
} }
// Rename the aar correctly // Rename the aar correctly
libraryVariants.all { variant -> libraryVariants.all { variant ->
variant.outputs.each { output -> variant.outputs.each { output ->
def outputFile = output.outputFile def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) { if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar" def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName) output.outputFile = new File(outputFile.parent, fileName)
} }
} }
} }
} }
ext { ext {
swagger_annotations_version = "1.5.0" swagger_annotations_version = "1.5.0"
gson_version = "2.3.1" gson_version = "2.3.1"
httpclient_version = "4.3.3" httpclient_version = "4.3.3"
junit_version = "4.8.1" junit_version = "4.8.1"
} }
dependencies { dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version" compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.gson:gson:$gson_version" compile "com.google.code.gson:gson:$gson_version"
compile "org.apache.httpcomponents:httpcore:$httpclient_version" compile "org.apache.httpcomponents:httpcore:$httpclient_version"
compile "org.apache.httpcomponents:httpclient:$httpclient_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version"
compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { compile ("org.apache.httpcomponents:httpcore:$httpclient_version") {
exclude(group: 'org.apache.httpcomponents', module: 'httpclient') exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
} }
compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { compile ("org.apache.httpcomponents:httpmime:$httpclient_version") {
exclude(group: 'org.apache.httpcomponents', module: 'httpclient') exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
} }
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
} }
afterEvaluate { afterEvaluate {
android.libraryVariants.all { variant -> android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}" task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar") task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task); artifacts.add('archives', task);
} }
} }
task sourcesJar(type: Jar) { task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs from android.sourceSets.main.java.srcDirs
classifier = 'sources' classifier = 'sources'
} }
artifacts { artifacts {
archives sourcesJar archives sourcesJar
} }

View File

@@ -1,158 +1,155 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-android-client</artifactId> <artifactId>swagger-android-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-android-client</name> <name>swagger-android-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection> <developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
</scm> </scm>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version> <version>2.12</version>
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>loggerPath</name> <name>loggerPath</name>
<value>conf/log4j.properties</value> <value>conf/log4j.properties</value>
</property> </property>
</systemProperties> </systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine> <argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel> <parallel>methods</parallel>
<forkMode>pertest</forkMode> <forkMode>pertest</forkMode>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/main/java</source>
src/main/java</source> </sources>
</sources> </configuration>
</configuration> </execution>
</execution> <execution>
<execution> <id>add_test_sources</id>
<id>add_test_sources</id> <phase>generate-test-sources</phase>
<phase>generate-test-sources</phase> <goals>
<goals> <goal>add-test-source</goal>
<goal>add-test-source</goal> </goals>
</goals> <configuration>
<configuration> <sources>
<sources> <source>src/test/java</source>
<source> </sources>
src/test/java</source> </configuration>
</sources> </execution>
</configuration> </executions>
</execution> </plugin>
</executions> <plugin>
</plugin> <groupId>org.apache.maven.plugins</groupId>
<plugin> <artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>2.3.2</version>
<artifactId>maven-compiler-plugin</artifactId> <configuration>
<version>2.3.2</version> <source>1.6</source>
<configuration> <target>1.6</target>
<source> </configuration>
1.6</source> </plugin>
<target>1.6</target> </plugins>
</configuration> </build>
</plugin> <dependencies>
</plugins> <dependency>
</build> <groupId>io.swagger</groupId>
<dependencies> <artifactId>swagger-annotations</artifactId>
<dependency> <version>${swagger-annotations-version}</version>
<groupId>io.swagger</groupId> </dependency>
<artifactId>swagger-annotations</artifactId> <dependency>
<version>${swagger-annotations-version}</version> <groupId>com.google.code.gson</groupId>
</dependency> <artifactId>gson</artifactId>
<dependency> <version>${gson-version}</version>
<groupId>com.google.code.gson</groupId> </dependency>
<artifactId>gson</artifactId> <dependency>
<version>${gson-version}</version> <groupId>org.apache.httpcomponents</groupId>
</dependency> <artifactId>httpclient</artifactId>
<dependency> <version>${httpclient-version}</version>
<groupId>org.apache.httpcomponents</groupId> <scope>compile</scope>
<artifactId>httpclient</artifactId> </dependency>
<version>${httpclient-version}</version> <dependency>
<scope>compile</scope> <groupId>org.apache.httpcomponents</groupId>
</dependency> <artifactId>httpmime</artifactId>
<dependency> <version>${httpclient-version}</version>
<groupId>org.apache.httpcomponents</groupId> <scope>compile</scope>
<artifactId>httpmime</artifactId> </dependency>
<version>${httpclient-version}</version>
<scope>compile</scope>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>sonatype-snapshots</id> <id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url> <url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository> </repository>
</repositories> </repositories>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-annotations-version>1.5.0</swagger-annotations-version>
<gson-version>2.3.1</gson-version> <gson-version>2.3.1</gson-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<httpclient-version>4.3.6</httpclient-version> <httpclient-version>4.3.6</httpclient-version>
</properties> </properties>
</project> </project>

View File

@@ -1,3 +1,3 @@
<manifest package="io.swagger.client"> <manifest package="io.swagger.client">
<application/> <application />
</manifest> </manifest>

View File

@@ -1,29 +1,29 @@
package io.swagger.client; package io.swagger.client;
public class ApiException extends Exception { public class ApiException extends Exception {
int code = 0; int code = 0;
String message = null; String message = null;
public ApiException() {} public ApiException() {}
public ApiException(int code, String message) { public ApiException(int code, String message) {
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
public int getCode() { public int getCode() {
return code; return code;
} }
public void setCode(int code) { public void setCode(int code) {
this.code = code; this.code = code;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
} }

View File

@@ -52,345 +52,338 @@ import javax.net.ssl.X509TrustManager;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
public class ApiInvoker { public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker(); private static ApiInvoker INSTANCE = new ApiInvoker();
private Map private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private HttpClient client = null; private HttpClient client = null;
private boolean ignoreSSLCertificates = false; private boolean ignoreSSLCertificates = false;
private ClientConnectionManager ignoreSSLConnectionManager; private ClientConnectionManager ignoreSSLConnectionManager;
/** Content type "text/plain" with UTF-8 encoding. */ /** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/** /**
* ISO 8601 date time format. * ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601 * @see https://en.wikipedia.org/wiki/ISO_8601
*/ */
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
/** /**
* ISO 8601 date format. * ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601 * @see https://en.wikipedia.org/wiki/ISO_8601
*/ */
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static { static {
// Use UTC as the default time zone. // Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Android-Java-Swagger"); setUserAgent("Android-Java-Swagger");
} }
public static void setUserAgent(String userAgent) { public static void setUserAgent(String userAgent) {
INSTANCE.addDefaultHeader("User-Agent", userAgent); INSTANCE.addDefaultHeader("User-Agent", userAgent);
} }
public static Date parseDateTime(String str) { public static Date parseDateTime(String str) {
try { try {
return DATE_TIME_FORMAT.parse(str); return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Date parseDate(String str) { public static Date parseDate(String str) {
try { try {
return DATE_FORMAT.parse(str); return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static String formatDateTime(Date datetime) { public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime); return DATE_TIME_FORMAT.format(datetime);
} }
public static String formatDate(Date date) { public static String formatDate(Date date) {
return DATE_FORMAT.format(date); return DATE_FORMAT.format(date);
} }
public static String parameterToString(Object param) { public static String parameterToString(Object param) {
if (param == null) { if (param == null) {
return ""; return "";
} else if (param instanceof Date) { } else if (param instanceof Date) {
return formatDateTime((Date) param); return formatDateTime((Date) param);
} else if (param instanceof Collection) { } else if (param instanceof Collection) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) { for(Object o : (Collection)param) {
if(b.length() > 0) { if(b.length() > 0) {
b.append(","); b.append(",");
} }
b.append(String.valueOf(o)); b.append(String.valueOf(o));
} }
return b.toString(); return b.toString();
} else { } else {
return String.valueOf(param); return String.valueOf(param);
} }
} }
public ApiInvoker() { public ApiInvoker() {
initConnectionManager(); initConnectionManager();
} }
public static ApiInvoker getInstance() { public static ApiInvoker getInstance() {
return INSTANCE; return INSTANCE;
} }
public void ignoreSSLCertificates(boolean ignoreSSLCertificates) { public void ignoreSSLCertificates(boolean ignoreSSLCertificates) {
this.ignoreSSLCertificates = ignoreSSLCertificates; this.ignoreSSLCertificates = ignoreSSLCertificates;
} }
public void addDefaultHeader(String key, String value) { public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value); defaultHeaderMap.put(key, value);
} }
public String escapeString(String str) { public String escapeString(String str) {
return str; return str;
} }
public static Object deserialize(String json, String containerType, Class cls) throws ApiException { public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{ try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) { if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls); return JsonUtil.deserializeToList(json, cls);
} }
else if(String.class.equals(cls)) { else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2); return json.substring(1, json.length() - 2);
else else
return json; return json;
} }
else { else {
return JsonUtil.deserializeToObject(json, cls); return JsonUtil.deserializeToObject(json, cls);
} }
} }
catch (JsonParseException e) { catch (JsonParseException e) {
throw new ApiException(500, e.getMessage()); throw new ApiException(500, e.getMessage());
} }
} }
public static String serialize(Object obj) throws ApiException { public static String serialize(Object obj) throws ApiException {
try { try {
if (obj != null) if (obj != null)
return JsonUtil.serialize(obj); return JsonUtil.serialize(obj);
else else
return null; return null;
} }
catch (Exception e) { catch (Exception e) {
throw new ApiException(500, e.getMessage()); throw new ApiException(500, e.getMessage());
} }
} }
public String invokeAPI(String host, String path, String method, Map public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
<String, String> queryParams, Object body, Map HttpClient client = getClient(host);
<String, String> headerParams, Map
<String, String> formParams, String contentType) throws ApiException {
HttpClient client = getClient(host);
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) { for(String key : queryParams.keySet()) {
String value = queryParams.get(key); String value = queryParams.get(key);
if (value != null){ if (value != null){
if(b.toString().length() == 0) if(b.toString().length() == 0)
b.append("?"); b.append("?");
else else
b.append("&"); b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value)); b.append(escapeString(key)).append("=").append(escapeString(value));
} }
} }
String url = host + path + b.toString(); String url = host + path + b.toString();
HashMap HashMap<String, String> headers = new HashMap<String, String>();
<String, String> headers = new HashMap
<String, String>();
for(String key : headerParams.keySet()) { for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key)); headers.put(key, headerParams.get(key));
} }
for(String key : defaultHeaderMap.keySet()) { for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) { if(!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key)); headers.put(key, defaultHeaderMap.get(key));
} }
} }
headers.put("Accept", "application/json"); headers.put("Accept", "application/json");
// URL encoded string from form parameters // URL encoded string from form parameters
String formParamStr = null; String formParamStr = null;
// for form data // for form data
if ("application/x-www-form-urlencoded".equals(contentType)) { if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder(); StringBuilder formParamBuilder = new StringBuilder();
// encode the form params // encode the form params
for (String key : formParams.keySet()) { for (String key : formParams.keySet()) {
String value = formParams.get(key); String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) { if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) { if (formParamBuilder.length() > 0) {
formParamBuilder.append("&"); formParamBuilder.append("&");
} }
try { try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
} }
catch (Exception e) { catch (Exception e) {
// move on to next // move on to next
} }
} }
} }
formParamStr = formParamBuilder.toString(); formParamStr = formParamBuilder.toString();
} }
HttpResponse response = null; HttpResponse response = null;
try { try {
if ("GET".equals(method)) { if ("GET".equals(method)) {
HttpGet get = new HttpGet(url); HttpGet get = new HttpGet(url);
get.addHeader("Accept", "application/json"); get.addHeader("Accept", "application/json");
for(String key : headers.keySet()) { for(String key : headers.keySet()) {
get.setHeader(key, headers.get(key)); get.setHeader(key, headers.get(key));
} }
response = client.execute(get); response = client.execute(get);
} }
else if ("POST".equals(method)) { else if ("POST".equals(method)) {
HttpPost post = new HttpPost(url); HttpPost post = new HttpPost(url);
if (formParamStr != null) { if (formParamStr != null) {
post.setHeader("Content-Type", contentType); post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(formParamStr, "UTF-8")); post.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) { } else if (body != null) {
if (body instanceof HttpEntity) { if (body instanceof HttpEntity) {
// this is for file uploading // this is for file uploading
post.setEntity((HttpEntity) body); post.setEntity((HttpEntity) body);
} else { } else {
post.setHeader("Content-Type", contentType); post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(serialize(body), "UTF-8")); post.setEntity(new StringEntity(serialize(body), "UTF-8"));
} }
} }
for(String key : headers.keySet()) { for(String key : headers.keySet()) {
post.setHeader(key, headers.get(key)); post.setHeader(key, headers.get(key));
} }
response = client.execute(post); response = client.execute(post);
} }
else if ("PUT".equals(method)) { else if ("PUT".equals(method)) {
HttpPut put = new HttpPut(url); HttpPut put = new HttpPut(url);
if (formParamStr != null) { if (formParamStr != null) {
put.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(formParamStr, "UTF-8")); put.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) { } else if (body != null) {
put.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(serialize(body), "UTF-8")); put.setEntity(new StringEntity(serialize(body), "UTF-8"));
} }
for(String key : headers.keySet()) { for(String key : headers.keySet()) {
put.setHeader(key, headers.get(key)); put.setHeader(key, headers.get(key));
} }
response = client.execute(put); response = client.execute(put);
} }
else if ("DELETE".equals(method)) { else if ("DELETE".equals(method)) {
HttpDelete delete = new HttpDelete(url); HttpDelete delete = new HttpDelete(url);
for(String key : headers.keySet()) { for(String key : headers.keySet()) {
delete.setHeader(key, headers.get(key)); delete.setHeader(key, headers.get(key));
} }
response = client.execute(delete); response = client.execute(delete);
} }
else if ("PATCH".equals(method)) { else if ("PATCH".equals(method)) {
HttpPatch patch = new HttpPatch(url); HttpPatch patch = new HttpPatch(url);
if (formParamStr != null) { if (formParamStr != null) {
patch.setHeader("Content-Type", contentType); patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(formParamStr, "UTF-8")); patch.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) { } else if (body != null) {
patch.setHeader("Content-Type", contentType); patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(serialize(body), "UTF-8")); patch.setEntity(new StringEntity(serialize(body), "UTF-8"));
} }
for(String key : headers.keySet()) { for(String key : headers.keySet()) {
patch.setHeader(key, headers.get(key)); patch.setHeader(key, headers.get(key));
} }
response = client.execute(patch); response = client.execute(patch);
} }
int code = response.getStatusLine().getStatusCode(); int code = response.getStatusLine().getStatusCode();
String responseString = null; String responseString = null;
if(code == 204) if(code == 204)
responseString = ""; responseString = "";
else if(code >= 200 && code < 300) { else if(code >= 200 && code < 300) {
if(response.getEntity() != null) { if(response.getEntity() != null) {
HttpEntity resEntity = response.getEntity(); HttpEntity resEntity = response.getEntity();
responseString = EntityUtils.toString(resEntity); responseString = EntityUtils.toString(resEntity);
} }
return responseString; return responseString;
} }
else { else {
if(response.getEntity() != null) { if(response.getEntity() != null) {
HttpEntity resEntity = response.getEntity(); HttpEntity resEntity = response.getEntity();
responseString = EntityUtils.toString(resEntity); responseString = EntityUtils.toString(resEntity);
} }
else else
responseString = "no data"; responseString = "no data";
} }
throw new ApiException(code, responseString); throw new ApiException(code, responseString);
} }
catch(IOException e) { catch(IOException e) {
throw new ApiException(500, e.getMessage()); throw new ApiException(500, e.getMessage());
} }
} }
private HttpClient getClient(String host) { private HttpClient getClient(String host) {
if (client == null) { if (client == null) {
if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) { if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) {
// Trust self signed certificates // Trust self signed certificates
client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams()); client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams());
} else { } else {
client = new DefaultHttpClient(); client = new DefaultHttpClient();
} }
} }
return client; return client;
} }
private void initConnectionManager() { private void initConnectionManager() {
try { try {
final SSLContext sslContext = SSLContext.getInstance("SSL"); final SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything // set up a TrustManager that trusts everything
TrustManager[] trustManagers = new TrustManager[] { TrustManager[] trustManagers = new TrustManager[] {
new X509TrustManager() { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return null; return null;
} }
public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}}; }};
sslContext.init(null, trustManagers, new SecureRandom()); sslContext.init(null, trustManagers, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) { SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) {
private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory(); private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory();
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException { throws IOException, UnknownHostException {
return sslFactory.createSocket(socket, host, port, autoClose); return sslFactory.createSocket(socket, host, port, autoClose);
} }
public Socket createSocket() throws IOException { public Socket createSocket() throws IOException {
return sslFactory.createSocket(); return sslFactory.createSocket();
} }
}; };
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme httpsScheme = new Scheme("https", sf, 443); Scheme httpsScheme = new Scheme("https", sf, 443);
SchemeRegistry schemeRegistry = new SchemeRegistry(); SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme); schemeRegistry.register(httpsScheme);
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry); ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
// This will only be thrown if SSL isn't available for some reason. // This will only be thrown if SSL isn't available for some reason.
} catch (KeyManagementException e) { } catch (KeyManagementException e) {
// This might be thrown when passing a key into init(), but no key is being passed. // This might be thrown when passing a key into init(), but no key is being passed.
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
// This catches anything else that might go wrong. // This catches anything else that might go wrong.
// If anything goes wrong we default to the standard connection manager. // If anything goes wrong we default to the standard connection manager.
} }
} }
} }

View File

@@ -3,14 +3,14 @@ package io.swagger.client;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
public class HttpPatch extends HttpPost { public class HttpPatch extends HttpPost {
public static final String METHOD_PATCH = "PATCH"; public static final String METHOD_PATCH = "PATCH";
public HttpPatch(final String url) { public HttpPatch(final String url) {
super(url); super(url);
} }
@Override @Override
public String getMethod() { public String getMethod() {
return METHOD_PATCH; return METHOD_PATCH;
} }
} }

View File

@@ -8,95 +8,80 @@ import java.util.List;
import io.swagger.client.model.*; import io.swagger.client.model.*;
public class JsonUtil { public class JsonUtil {
public static GsonBuilder gsonBuilder; public static GsonBuilder gsonBuilder;
static { static {
gsonBuilder = new GsonBuilder(); gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls(); gsonBuilder.serializeNulls();
gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
} }
public static Gson getGson() { public static Gson getGson() {
return gsonBuilder.create(); return gsonBuilder.create();
} }
public static String serialize(Object obj){ public static String serialize(Object obj){
return getGson().toJson(obj); return getGson().toJson(obj);
} }
public static public static <T> T deserializeToList(String jsonString, Class cls){
<T> T deserializeToList(String jsonString, Class cls){
return getGson().fromJson(jsonString, getListTypeForDeserialization(cls)); return getGson().fromJson(jsonString, getListTypeForDeserialization(cls));
}
public static <T> T deserializeToObject(String jsonString, Class cls){
return getGson().fromJson(jsonString, getTypeForDeserialization(cls));
}
public static Type getListTypeForDeserialization(Class cls) {
String className = cls.getSimpleName();
if ("User".equalsIgnoreCase(className)) {
return new TypeToken<List<User>>(){}.getType();
} }
public static if ("Category".equalsIgnoreCase(className)) {
<T> T deserializeToObject(String jsonString, Class cls){ return new TypeToken<List<Category>>(){}.getType();
return getGson().fromJson(jsonString, getTypeForDeserialization(cls)); }
}
public static Type getListTypeForDeserialization(Class cls) { if ("Pet".equalsIgnoreCase(className)) {
String className = cls.getSimpleName(); return new TypeToken<List<Pet>>(){}.getType();
}
if ("User".equalsIgnoreCase(className)) { if ("Tag".equalsIgnoreCase(className)) {
return new TypeToken return new TypeToken<List<Tag>>(){}.getType();
<List }
<User>>(){}.getType();
}
if ("Category".equalsIgnoreCase(className)) { if ("Order".equalsIgnoreCase(className)) {
return new TypeToken return new TypeToken<List<Order>>(){}.getType();
<List }
<Category>>(){}.getType();
}
if ("Pet".equalsIgnoreCase(className)) { return new TypeToken<List<Object>>(){}.getType();
return new TypeToken }
<List
<Pet>>(){}.getType();
}
if ("Tag".equalsIgnoreCase(className)) { public static Type getTypeForDeserialization(Class cls) {
return new TypeToken String className = cls.getSimpleName();
<List
<Tag>>(){}.getType();
}
if ("Order".equalsIgnoreCase(className)) { if ("User".equalsIgnoreCase(className)) {
return new TypeToken return new TypeToken<User>(){}.getType();
<List }
<Order>>(){}.getType();
}
return new TypeToken if ("Category".equalsIgnoreCase(className)) {
<List return new TypeToken<Category>(){}.getType();
<Object>>(){}.getType(); }
}
public static Type getTypeForDeserialization(Class cls) { if ("Pet".equalsIgnoreCase(className)) {
String className = cls.getSimpleName(); return new TypeToken<Pet>(){}.getType();
}
if ("User".equalsIgnoreCase(className)) { if ("Tag".equalsIgnoreCase(className)) {
return new TypeToken<User>(){}.getType(); return new TypeToken<Tag>(){}.getType();
} }
if ("Category".equalsIgnoreCase(className)) { if ("Order".equalsIgnoreCase(className)) {
return new TypeToken<Category>(){}.getType(); return new TypeToken<Order>(){}.getType();
} }
if ("Pet".equalsIgnoreCase(className)) { return new TypeToken<Object>(){}.getType();
return new TypeToken<Pet>(){}.getType(); }
}
if ("Tag".equalsIgnoreCase(className)) { };
return new TypeToken<Tag>(){}.getType();
}
if ("Order".equalsIgnoreCase(className)) {
return new TypeToken<Order>(){}.getType();
}
return new TypeToken
<Object>(){}.getType();
}
};

View File

@@ -17,274 +17,250 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import java.io.File; import java.io.File;
public class StoreApi { public class StoreApi {
String basePath = "http://petstore.swagger.io/v2"; String basePath = "http://petstore.swagger.io/v2";
ApiInvoker apiInvoker = ApiInvoker.getInstance(); ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) { public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value); getInvoker().addDefaultHeader(key, value);
} }
public ApiInvoker getInvoker() { public ApiInvoker getInvoker() {
return apiInvoker; return apiInvoker;
} }
public void setBasePath(String basePath) { public void setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
} }
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
} }
try {
/** String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
* Returns pet inventories by status if(response != null){
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (Map<String, Integer>) ApiInvoker.deserialize(response, "map", Map.class); return (Map<String, Integer>) ApiInvoker.deserialize(response, "map", Map.class);
} }
else { else {
return null; return null;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Place an order for a pet * Place an order for a pet
* *
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Order * @return Order
*/ */
public Order placeOrder (Order body) throws ApiException { public Order placeOrder (Order body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/store/order".replaceAll("\\{format\\}","json"); String path = "/store/order".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap // header params
<String, String>(); Map<String, String> headerParams = new HashMap<String, String>();
// header params // form params
Map Map<String, String> formParams = new HashMap<String, String>();
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = { String[] contentTypes = {
}; };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) { if (contentType.startsWith("multipart/form-data")) {
// file uploading // file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build(); HttpEntity httpEntity = builder.build();
postBody = httpEntity; postBody = httpEntity;
} else { } else {
// normal form params // normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void deleteOrder (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
} }
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void deleteOrder (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
}

View File

@@ -17,525 +17,477 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import java.io.File; import java.io.File;
public class UserApi { public class UserApi {
String basePath = "http://petstore.swagger.io/v2"; String basePath = "http://petstore.swagger.io/v2";
ApiInvoker apiInvoker = ApiInvoker.getInstance(); ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) { public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value); getInvoker().addDefaultHeader(key, value);
} }
public ApiInvoker getInvoker() { public ApiInvoker getInvoker() {
return apiInvoker; return apiInvoker;
} }
public void setBasePath(String basePath) { public void setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
} }
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
*/
public void createUser (User body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/user".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
} }
try {
/** String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
* Create user if(response != null){
* This can only be done by the logged in user.
* @param body Created user object
* @return void
*/
public void createUser (User body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/user".replaceAll("\\{format\\}","json");
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ; return ;
} }
else { else {
return ; return ;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
* @param body List of user object * @param body List of user object
* @return void * @return void
*/ */
public void createUsersWithArrayInput (List<User> body) throws ApiException { public void createUsersWithArrayInput (List<User> body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); String path = "/user/createWithArray".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap // header params
<String, String>(); Map<String, String> headerParams = new HashMap<String, String>();
// header params // form params
Map Map<String, String> formParams = new HashMap<String, String>();
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = { String[] contentTypes = {
}; };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) { if (contentType.startsWith("multipart/form-data")) {
// file uploading // file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build(); HttpEntity httpEntity = builder.build();
postBody = httpEntity; postBody = httpEntity;
} else { } else {
// normal form params // normal form params
} }
try { try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){ if(response != null){
return ; return ;
} }
else { else {
return ; return ;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
* @param body List of user object * @param body List of user object
* @return void * @return void
*/ */
public void createUsersWithListInput (List<User> body) throws ApiException { public void createUsersWithListInput (List<User> body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/user/createWithList".replaceAll("\\{format\\}","json"); String path = "/user/createWithList".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap // header params
<String, String>(); Map<String, String> headerParams = new HashMap<String, String>();
// header params // form params
Map Map<String, String> formParams = new HashMap<String, String>();
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = { String[] contentTypes = {
}; };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) { if (contentType.startsWith("multipart/form-data")) {
// file uploading // file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build(); HttpEntity httpEntity = builder.build();
postBody = httpEntity; postBody = httpEntity;
} else { } else {
// normal form params // normal form params
} }
try { try {
String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){ if(response != null){
return ; return ;
} }
else { else {
return ; return ;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Logs user into the system * Logs user into the system
* *
* @param username The user name for login * @param username The user name for login
* @param password The password for login in clear text * @param password The password for login in clear text
* @return String * @return String
*/ */
public String loginUser (String username, String password) throws ApiException { public String loginUser (String username, String password) throws ApiException {
Object postBody = null; Object postBody = null;
// create path and map variables // create path and map variables
String path = "/user/login".replaceAll("\\{format\\}","json"); String path = "/user/login".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap // header params
<String, String>(); Map<String, String> headerParams = new HashMap<String, String>();
// header params // form params
Map Map<String, String> formParams = new HashMap<String, String>();
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
if (username != null) if (username != null)
queryParams.put("username", ApiInvoker.parameterToString(username)); queryParams.put("username", ApiInvoker.parameterToString(username));
if (password != null) if (password != null)
queryParams.put("password", ApiInvoker.parameterToString(password)); queryParams.put("password", ApiInvoker.parameterToString(password));
String[] contentTypes = { String[] contentTypes = {
}; };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) { if (contentType.startsWith("multipart/form-data")) {
// file uploading // file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build(); HttpEntity httpEntity = builder.build();
postBody = httpEntity; postBody = httpEntity;
} else { } else {
// normal form params // normal form params
} }
try { try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){ if(response != null){
return (String) ApiInvoker.deserialize(response, "", String.class); return (String) ApiInvoker.deserialize(response, "", String.class);
} }
else { else {
return null; return null;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Logs out current logged in user session * Logs out current logged in user session
* *
* @return void * @return void
*/ */
public void logoutUser () throws ApiException { public void logoutUser () throws ApiException {
Object postBody = null; Object postBody = null;
// create path and map variables // create path and map variables
String path = "/user/logout".replaceAll("\\{format\\}","json"); String path = "/user/logout".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap // header params
<String, String>(); Map<String, String> headerParams = new HashMap<String, String>();
// header params // form params
Map Map<String, String> formParams = new HashMap<String, String>();
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = { String[] contentTypes = {
}; };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) { if (contentType.startsWith("multipart/form-data")) {
// file uploading // file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build(); HttpEntity httpEntity = builder.build();
postBody = httpEntity; postBody = httpEntity;
} else { } else {
// normal form params // normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (User) ApiInvoker.deserialize(response, "", User.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void updateUser (String username, User body) throws ApiException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map
<String, String> formParams = new HashMap
<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
} }
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (User) ApiInvoker.deserialize(response, "", User.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void updateUser (String username, User body) throws ApiException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
}

View File

@@ -5,40 +5,40 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Category { public class Category {
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Category {\n"); sb.append("class Category {\n");
@@ -46,6 +46,5 @@ import com.google.gson.annotations.SerializedName;
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -6,96 +6,96 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Order { public class Order {
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
@SerializedName("petId") @SerializedName("petId")
private Long petId = null; private Long petId = null;
@SerializedName("quantity") @SerializedName("quantity")
private Integer quantity = null; private Integer quantity = null;
@SerializedName("shipDate") @SerializedName("shipDate")
private Date shipDate = null; private Date shipDate = null;
public enum StatusEnum { public enum StatusEnum {
placed, approved, delivered, placed, approved, delivered,
}; };
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
@SerializedName("complete") @SerializedName("complete")
private Boolean complete = null; private Boolean complete = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getPetId() { public Long getPetId() {
return petId; return petId;
} }
public void setPetId(Long petId) { public void setPetId(Long petId) {
this.petId = petId; this.petId = petId;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Integer getQuantity() { public Integer getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(Integer quantity) { public void setQuantity(Integer quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Date getShipDate() { public Date getShipDate() {
return shipDate; return shipDate;
} }
public void setShipDate(Date shipDate) { public void setShipDate(Date shipDate) {
this.shipDate = shipDate; this.shipDate = shipDate;
} }
/** /**
* Order Status * Order Status
**/ **/
@ApiModelProperty(value = "Order Status") @ApiModelProperty(value = "Order Status")
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Boolean getComplete() { public Boolean getComplete() {
return complete; return complete;
} }
public void setComplete(Boolean complete) { public void setComplete(Boolean complete) {
this.complete = complete; this.complete = complete;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Order {\n"); sb.append("class Order {\n");
@@ -107,6 +107,5 @@ import com.google.gson.annotations.SerializedName;
sb.append(" complete: ").append(complete).append("\n"); sb.append(" complete: ").append(complete).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,103 +1,103 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.client.model.Category; import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*; import java.util.*;
import io.swagger.client.model.Tag;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Pet { public class Pet {
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
@SerializedName("category") @SerializedName("category")
private Category category = null; private Category category = null;
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
@SerializedName("photoUrls") @SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>() ; private List<String> photoUrls = new ArrayList<String>() ;
@SerializedName("tags") @SerializedName("tags")
private List<Tag> tags = new ArrayList<Tag>() ; private List<Tag> tags = new ArrayList<Tag>() ;
public enum StatusEnum { public enum StatusEnum {
available, pending, sold, available, pending, sold,
}; };
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Category getCategory() { public Category getCategory() {
return category; return category;
} }
public void setCategory(Category category) { public void setCategory(Category category) {
this.category = category; this.category = category;
} }
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
public List<String> getPhotoUrls() { public List<String> getPhotoUrls() {
return photoUrls; return photoUrls;
} }
public void setPhotoUrls(List<String> photoUrls) { public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls; this.photoUrls = photoUrls;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public List<Tag> getTags() { public List<Tag> getTags() {
return tags; return tags;
} }
public void setTags(List<Tag> tags) { public void setTags(List<Tag> tags) {
this.tags = tags; this.tags = tags;
} }
/** /**
* pet status in the store * pet status in the store
**/ **/
@ApiModelProperty(value = "pet status in the store") @ApiModelProperty(value = "pet status in the store")
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n"); sb.append("class Pet {\n");
@@ -109,6 +109,5 @@ import com.google.gson.annotations.SerializedName;
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,40 +5,40 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Tag { public class Tag {
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n"); sb.append("class Tag {\n");
@@ -46,6 +46,5 @@ import com.google.gson.annotations.SerializedName;
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,119 +5,119 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class User { public class User {
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
@SerializedName("username") @SerializedName("username")
private String username = null; private String username = null;
@SerializedName("firstName") @SerializedName("firstName")
private String firstName = null; private String firstName = null;
@SerializedName("lastName") @SerializedName("lastName")
private String lastName = null; private String lastName = null;
@SerializedName("email") @SerializedName("email")
private String email = null; private String email = null;
@SerializedName("password") @SerializedName("password")
private String password = null; private String password = null;
@SerializedName("phone") @SerializedName("phone")
private String phone = null; private String phone = null;
@SerializedName("userStatus") @SerializedName("userStatus")
private Integer userStatus = null; private Integer userStatus = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
/** /**
* User Status * User Status
**/ **/
@ApiModelProperty(value = "User Status") @ApiModelProperty(value = "User Status")
public Integer getUserStatus() { public Integer getUserStatus() {
return userStatus; return userStatus;
} }
public void setUserStatus(Integer userStatus) { public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus; this.userStatus = userStatus;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class User {\n"); sb.append("class User {\n");
@@ -131,6 +131,5 @@ import com.google.gson.annotations.SerializedName;
sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append(" userStatus: ").append(userStatus).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -500,7 +500,7 @@ namespace IO.Swagger.Api {
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { "api_key", "petstore_auth" }; String[] authSettings = new String[] { "petstore_auth", "api_key" };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
@@ -540,7 +540,7 @@ namespace IO.Swagger.Api {
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { "api_key", "petstore_auth" }; String[] authSettings = new String[] { "petstore_auth", "api_key" };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

View File

@@ -1,170 +1,167 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-java-client</artifactId> <artifactId>swagger-java-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-java-client</name> <name>swagger-java-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection> <developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
</scm> </scm>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version> <version>2.12</version>
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>loggerPath</name> <name>loggerPath</name>
<value>conf/log4j.properties</value> <value>conf/log4j.properties</value>
</property> </property>
</systemProperties> </systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine> <argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel> <parallel>methods</parallel>
<forkMode>pertest</forkMode> <forkMode>pertest</forkMode>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/main/java</source>
src/main/java</source> </sources>
</sources> </configuration>
</configuration> </execution>
</execution> <execution>
<execution> <id>add_test_sources</id>
<id>add_test_sources</id> <phase>generate-test-sources</phase>
<phase>generate-test-sources</phase> <goals>
<goals> <goal>add-test-source</goal>
<goal>add-test-source</goal> </goals>
</goals> <configuration>
<configuration> <sources>
<sources> <source>src/test/java</source>
<source> </sources>
src/test/java</source> </configuration>
</sources> </execution>
</configuration> </executions>
</execution> </plugin>
</executions> <plugin>
</plugin> <groupId>org.apache.maven.plugins</groupId>
<plugin> <artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>2.3.2</version>
<artifactId>maven-compiler-plugin</artifactId> <configuration>
<version>2.3.2</version> <source>1.6</source>
<configuration> <target>1.6</target>
<source> </configuration>
1.6</source> </plugin>
<target>1.6</target> </plugins>
</configuration> </build>
</plugin> <dependencies>
</plugins> <dependency>
</build> <groupId>io.swagger</groupId>
<dependencies> <artifactId>swagger-annotations</artifactId>
<dependency> <version>${swagger-annotations-version}</version>
<groupId>io.swagger</groupId> </dependency>
<artifactId>swagger-annotations</artifactId> <dependency>
<version>${swagger-annotations-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-client</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-client</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey.contribs</groupId>
</dependency> <artifactId>jersey-multipart</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey.contribs</groupId> </dependency>
<artifactId>jersey-multipart</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.fasterxml.jackson.core</groupId>
</dependency> <artifactId>jackson-core</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.core</groupId> </dependency>
<artifactId>jackson-core</artifactId> <dependency>
<version>${jackson-version}</version> <groupId>com.fasterxml.jackson.core</groupId>
</dependency> <artifactId>jackson-annotations</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.core</groupId> </dependency>
<artifactId>jackson-annotations</artifactId> <dependency>
<version>${jackson-version}</version> <groupId>com.fasterxml.jackson.core</groupId>
</dependency> <artifactId>jackson-databind</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.core</groupId> </dependency>
<artifactId>jackson-databind</artifactId> <dependency>
<version>${jackson-version}</version> <groupId>com.fasterxml.jackson.datatype</groupId>
</dependency> <artifactId>jackson-datatype-joda</artifactId>
<dependency> <version>2.1.5</version>
<groupId>com.fasterxml.jackson.datatype</groupId> </dependency>
<artifactId>jackson-datatype-joda</artifactId> <dependency>
<version>2.1.5</version> <groupId>joda-time</groupId>
</dependency> <artifactId>joda-time</artifactId>
<dependency> <version>${jodatime-version}</version>
<groupId>joda-time</groupId> </dependency>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-annotations-version>1.5.0</swagger-annotations-version>
<jersey-version>1.18</jersey-version> <jersey-version>1.18</jersey-version>
<jackson-version>2.4.2</jackson-version> <jackson-version>2.4.2</jackson-version>
<jodatime-version>2.3</jodatime-version> <jodatime-version>2.3</jodatime-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
</properties> </properties>
</project> </project>

View File

@@ -40,481 +40,467 @@ import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth; import io.swagger.client.auth.OAuth;
public class ApiClient { public class ApiClient {
private Map private Map<String, Client> hostMap = new HashMap<String, Client>();
<String, Client> hostMap = new HashMap private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
<String, Client>(); private boolean debugging = false;
private Map private String basePath = "http://petstore.swagger.io/v2";
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private boolean debugging = false;
private String basePath = "http://petstore.swagger.io/v2";
private Map private Map<String, Authentication> authentications;
<String, Authentication> authentications;
private DateFormat dateFormat; private DateFormat dateFormat;
public ApiClient() { public ApiClient() {
// Use ISO 8601 format for date and datetime. // Use ISO 8601 format for date and datetime.
// See https://en.wikipedia.org/wiki/ISO_8601 // See https://en.wikipedia.org/wiki/ISO_8601
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone. // Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap authentications = new HashMap<String, Authentication>();
<String, Authentication>();
authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth()); authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified. // Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications); authentications = Collections.unmodifiableMap(authentications);
} }
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
} }
public ApiClient setBasePath(String basePath) { public ApiClient setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
return this; return this;
} }
/** /**
* Get authentications (key: authentication name, value: authentication). * Get authentications (key: authentication name, value: authentication).
*/ */
public Map public Map<String, Authentication> getAuthentications() {
<String, Authentication> getAuthentications() { return authentications;
return authentications; }
}
/** /**
* Get authentication for the given name. * Get authentication for the given name.
* *
* @param authName The authentication name * @param authName The authentication name
* @return The authentication, null if not found * @return The authentication, null if not found
*/ */
public Authentication getAuthentication(String authName) { public Authentication getAuthentication(String authName) {
return authentications.get(authName); return authentications.get(authName);
} }
/** /**
* Helper method to set username for the first HTTP basic authentication. * Helper method to set username for the first HTTP basic authentication.
*/ */
public void setUsername(String username) { public void setUsername(String username) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) { if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username); ((HttpBasicAuth) auth).setUsername(username);
return; return;
} }
} }
throw new RuntimeException("No HTTP basic authentication configured!"); throw new RuntimeException("No HTTP basic authentication configured!");
} }
/** /**
* Helper method to set password for the first HTTP basic authentication. * Helper method to set password for the first HTTP basic authentication.
*/ */
public void setPassword(String password) { public void setPassword(String password) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) { if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password); ((HttpBasicAuth) auth).setPassword(password);
return; return;
} }
} }
throw new RuntimeException("No HTTP basic authentication configured!"); throw new RuntimeException("No HTTP basic authentication configured!");
} }
/** /**
* Helper method to set API key value for the first API key authentication. * Helper method to set API key value for the first API key authentication.
*/ */
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) { if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey); ((ApiKeyAuth) auth).setApiKey(apiKey);
return; return;
} }
} }
throw new RuntimeException("No API key authentication configured!"); throw new RuntimeException("No API key authentication configured!");
} }
/** /**
* Helper method to set API key prefix for the first API key authentication. * Helper method to set API key prefix for the first API key authentication.
*/ */
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) { if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return; return;
} }
} }
throw new RuntimeException("No API key authentication configured!"); throw new RuntimeException("No API key authentication configured!");
} }
/** /**
* Set the User-Agent header's value (by adding to the default header map). * Set the User-Agent header's value (by adding to the default header map).
*/ */
public ApiClient setUserAgent(String userAgent) { public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent); addDefaultHeader("User-Agent", userAgent);
return this; return this;
} }
/** /**
* Add a default header. * Add a default header.
* *
* @param key The header's key * @param key The header's key
* @param value The header's value * @param value The header's value
*/ */
public ApiClient addDefaultHeader(String key, String value) { public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value); defaultHeaderMap.put(key, value);
return this; return this;
} }
/** /**
* Check that whether debugging is enabled for this API client. * Check that whether debugging is enabled for this API client.
*/ */
public boolean isDebugging() { public boolean isDebugging() {
return debugging; return debugging;
} }
/** /**
* Enable/disable debugging for this API client. * Enable/disable debugging for this API client.
* *
* @param debugging To enable (true) or disable (false) debugging * @param debugging To enable (true) or disable (false) debugging
*/ */
public ApiClient setDebugging(boolean debugging) { public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging; this.debugging = debugging;
return this; return this;
} }
/** /**
* Get the date format used to parse/format date parameters. * Get the date format used to parse/format date parameters.
*/ */
public DateFormat getDateFormat() { public DateFormat getDateFormat() {
return dateFormat; return dateFormat;
} }
/** /**
* Set the date format used to parse/format date parameters. * Set the date format used to parse/format date parameters.
*/ */
public ApiClient getDateFormat(DateFormat dateFormat) { public ApiClient getDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat; this.dateFormat = dateFormat;
return this; return this;
} }
/** /**
* Parse the given string into Date object. * Parse the given string into Date object.
*/ */
public Date parseDate(String str) { public Date parseDate(String str) {
try { try {
return dateFormat.parse(str); return dateFormat.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Format the given Date object into string. * Format the given Date object into string.
*/ */
public String formatDate(Date date) { public String formatDate(Date date) {
return dateFormat.format(date); return dateFormat.format(date);
} }
/** /**
* Format the given parameter object into string. * Format the given parameter object into string.
*/ */
public String parameterToString(Object param) { public String parameterToString(Object param) {
if (param == null) { if (param == null) {
return ""; return "";
} else if (param instanceof Date) { } else if (param instanceof Date) {
return formatDate((Date) param); return formatDate((Date) param);
} else if (param instanceof Collection) { } else if (param instanceof Collection) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) { for(Object o : (Collection)param) {
if(b.length() > 0) { if(b.length() > 0) {
b.append(","); b.append(",");
} }
b.append(String.valueOf(o)); b.append(String.valueOf(o));
} }
return b.toString(); return b.toString();
} else { } else {
return String.valueOf(param); return String.valueOf(param);
} }
} }
/** /**
* Select the Accept header's value from the given accepts array: * Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it; * if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string) * otherwise use all of them (joining into a string)
* *
* @param accepts The accepts array to select from * @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty, * @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly). * null will be returned (not to set the Accept header explicitly).
*/ */
public String selectHeaderAccept(String[] accepts) { public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) return null; if (accepts.length == 0) return null;
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
return StringUtil.join(accepts, ","); return StringUtil.join(accepts, ",");
} }
/** /**
* Select the Content-Type header's value from the given array: * Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it; * if JSON exists in the given array, use it;
* otherwise use the first one of the array. * otherwise use the first one of the array.
* *
* @param contentTypes The Content-Type array to select from * @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty, * @return The Content-Type header to use. If the given array is empty,
* JSON will be used. * JSON will be used.
*/ */
public String selectHeaderContentType(String[] contentTypes) { public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) return "application/json"; if (contentTypes.length == 0) return "application/json";
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
return contentTypes[0]; return contentTypes[0];
} }
/** /**
* Escape the given string to be used as URL query value. * Escape the given string to be used as URL query value.
*/ */
public String escapeString(String str) { public String escapeString(String str) {
try { try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
return str; return str;
} }
} }
/** /**
* Deserialize the given JSON string to Java object. * Deserialize the given JSON string to Java object.
* *
* @param json The JSON string * @param json The JSON string
* @param containerType The container type, one of "list", "array" or "" * @param containerType The container type, one of "list", "array" or ""
* @param cls The type of the Java object * @param cls The type of the Java object
* @return The deserialized Java object * @return The deserialized Java object
*/ */
public Object deserialize(String json, String containerType, Class cls) throws ApiException { public Object deserialize(String json, String containerType, Class cls) throws ApiException {
if(null != containerType) { if(null != containerType) {
containerType = containerType.toLowerCase(); containerType = containerType.toLowerCase();
} }
try{ try{
if("list".equals(containerType) || "array".equals(containerType)) { if("list".equals(containerType) || "array".equals(containerType)) {
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo); List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
return response; return response;
} }
else if(String.class.equals(cls)) { else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2); return json.substring(1, json.length() - 2);
else else
return json; return json;
} }
else { else {
return JsonUtil.getJsonMapper().readValue(json, cls); return JsonUtil.getJsonMapper().readValue(json, cls);
} }
} }
catch (IOException e) { catch (IOException e) {
throw new ApiException(500, e.getMessage(), null, json); throw new ApiException(500, e.getMessage(), null, json);
} }
} }
/** /**
* Serialize the given Java object into JSON string. * Serialize the given Java object into JSON string.
*/ */
public String serialize(Object obj) throws ApiException { public String serialize(Object obj) throws ApiException {
try { try {
if (obj != null) if (obj != null)
return JsonUtil.getJsonMapper().writeValueAsString(obj); return JsonUtil.getJsonMapper().writeValueAsString(obj);
else else
return null; return null;
} }
catch (Exception e) { catch (Exception e) {
throw new ApiException(500, e.getMessage()); throw new ApiException(500, e.getMessage());
} }
} }
/** /**
* Invoke API by sending HTTP request with the given options. * Invoke API by sending HTTP request with the given options.
* *
* @param path The sub-path of the HTTP URL * @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters * @param queryParams The query parameters
* @param body The request body object * @param body The request body object
* @param headerParams The header parameters * @param headerParams The header parameters
* @param formParams The form parameters * @param formParams The form parameters
* @param accept The request's Accept header * @param accept The request's Accept header
* @param contentType The request's Content-Type header * @param contentType The request's Content-Type header
* @param authNames The authentications to apply * @param authNames The authentications to apply
* @return The response body in type of string * @return The response body in type of string
*/ */
public String invokeAPI(String path, String method, Map public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
<String, String> queryParams, Object body, Map updateParamsForAuth(authNames, queryParams, headerParams);
<String, String> headerParams, Map
<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
Client client = getClient(); Client client = getClient();
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) { for(String key : queryParams.keySet()) {
String value = queryParams.get(key); String value = queryParams.get(key);
if (value != null){ if (value != null){
if(b.toString().length() == 0) if(b.toString().length() == 0)
b.append("?"); b.append("?");
else else
b.append("&"); b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value)); b.append(escapeString(key)).append("=").append(escapeString(value));
} }
} }
String querystring = b.toString(); String querystring = b.toString();
Builder builder; Builder builder;
if (accept == null) if (accept == null)
builder = client.resource(basePath + path + querystring).getRequestBuilder(); builder = client.resource(basePath + path + querystring).getRequestBuilder();
else else
builder = client.resource(basePath + path + querystring).accept(accept); builder = client.resource(basePath + path + querystring).accept(accept);
for(String key : headerParams.keySet()) { for(String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));
} }
for(String key : defaultHeaderMap.keySet()) { for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) { if(!headerParams.containsKey(key)) {
builder = builder.header(key, defaultHeaderMap.get(key)); builder = builder.header(key, defaultHeaderMap.get(key));
} }
} }
ClientResponse response = null; ClientResponse response = null;
if("GET".equals(method)) { if("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class); response = (ClientResponse) builder.get(ClientResponse.class);
} }
else if ("POST".equals(method)) { else if ("POST".equals(method)) {
if (contentType.startsWith("application/x-www-form-urlencoded")) { if (contentType.startsWith("application/x-www-form-urlencoded")) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).post(ClientResponse.class, response = builder.type(contentType).post(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if (body == null) { } else if (body == null) {
response = builder.post(ClientResponse.class, null); response = builder.post(ClientResponse.class, null);
} else if(body instanceof FormDataMultiPart) { } else if(body instanceof FormDataMultiPart) {
response = builder.type(contentType).post(ClientResponse.class, body); response = builder.type(contentType).post(ClientResponse.class, body);
} }
else else
response = builder.type(contentType).post(ClientResponse.class, serialize(body)); response = builder.type(contentType).post(ClientResponse.class, serialize(body));
} }
else if ("PUT".equals(method)) { else if ("PUT".equals(method)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { if ("application/x-www-form-urlencoded".equals(contentType)) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).put(ClientResponse.class, response = builder.type(contentType).put(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if(body == null) { } else if(body == null) {
response = builder.put(ClientResponse.class, serialize(body)); response = builder.put(ClientResponse.class, serialize(body));
} else { } else {
response = builder.type(contentType).put(ClientResponse.class, serialize(body)); response = builder.type(contentType).put(ClientResponse.class, serialize(body));
} }
} }
else if ("DELETE".equals(method)) { else if ("DELETE".equals(method)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { if ("application/x-www-form-urlencoded".equals(contentType)) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).delete(ClientResponse.class, response = builder.type(contentType).delete(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if(body == null) { } else if(body == null) {
response = builder.delete(ClientResponse.class); response = builder.delete(ClientResponse.class);
} else { } else {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
} }
} }
else { else {
throw new ApiException(500, "unknown method type " + method); throw new ApiException(500, "unknown method type " + method);
} }
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
return null; return null;
} }
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) { if(response.hasEntity()) {
return (String) response.getEntity(String.class); return (String) response.getEntity(String.class);
} }
else { else {
return ""; return "";
} }
} }
else { else {
String message = "error"; String message = "error";
String respBody = null; String respBody = null;
if(response.hasEntity()) { if(response.hasEntity()) {
try{ try{
respBody = String.valueOf(response.getEntity(String.class)); respBody = String.valueOf(response.getEntity(String.class));
message = respBody; message = respBody;
} }
catch (RuntimeException e) { catch (RuntimeException e) {
// e.printStackTrace(); // e.printStackTrace();
} }
} }
throw new ApiException( throw new ApiException(
response.getClientResponseStatus().getStatusCode(), response.getClientResponseStatus().getStatusCode(),
message, message,
response.getHeaders(), response.getHeaders(),
respBody); respBody);
} }
} }
/** /**
* Update query and header parameters based on authentication settings. * Update query and header parameters based on authentication settings.
* *
* @param authNames The authentications to apply * @param authNames The authentications to apply
*/ */
private void updateParamsForAuth(String[] authNames, Map private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map for (String authName : authNames) {
<String, String> headerParams) { Authentication auth = authentications.get(authName);
for (String authName : authNames) { if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
Authentication auth = authentications.get(authName); auth.applyToParams(queryParams, headerParams);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); }
auth.applyToParams(queryParams, headerParams); }
}
}
/** /**
* Encode the given form parameters as request body. * Encode the given form parameters as request body.
*/ */
private String getXWWWFormUrlencodedParams(Map private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
<String, String> formParams) { StringBuilder formParamBuilder = new StringBuilder();
StringBuilder formParamBuilder = new StringBuilder();
for (Entry for (Entry<String, String> param : formParams.entrySet()) {
<String, String> param : formParams.entrySet()) { String keyStr = parameterToString(param.getKey());
String keyStr = parameterToString(param.getKey()); String valueStr = parameterToString(param.getValue());
String valueStr = parameterToString(param.getValue());
try { try {
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
.append("=") .append("=")
.append(URLEncoder.encode(valueStr, "utf8")); .append(URLEncoder.encode(valueStr, "utf8"));
formParamBuilder.append("&"); formParamBuilder.append("&");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// move on to next // move on to next
} }
} }
String encodedFormParams = formParamBuilder.toString(); String encodedFormParams = formParamBuilder.toString();
if (encodedFormParams.endsWith("&")) { if (encodedFormParams.endsWith("&")) {
encodedFormParams = encodedFormParams.substring(0, encodedFormParams = encodedFormParams.substring(0,
encodedFormParams.length() - 1); encodedFormParams.length() - 1);
} }
return encodedFormParams; return encodedFormParams;
} }
/** /**
* Get an existing client or create a new client to handle HTTP request. * Get an existing client or create a new client to handle HTTP request.
*/ */
private Client getClient() { private Client getClient() {
if(!hostMap.containsKey(basePath)) { if(!hostMap.containsKey(basePath)) {
Client client = Client.create(); Client client = Client.create();
if (debugging) if (debugging)
client.addFilter(new LoggingFilter()); client.addFilter(new LoggingFilter());
hostMap.put(basePath, client); hostMap.put(basePath, client);
} }
return hostMap.get(basePath); return hostMap.get(basePath);
} }
} }

View File

@@ -4,52 +4,44 @@ import java.util.Map;
import java.util.List; import java.util.List;
public class ApiException extends Exception { public class ApiException extends Exception {
private int code = 0; private int code = 0;
private String message = null; private String message = null;
private Map private Map<String, List<String>> responseHeaders = null;
<String, List private String responseBody = null;
<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {} public ApiException() {}
public ApiException(int code, String message) { public ApiException(int code, String message) {
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
public ApiException(int code, String message, Map public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
<String this.code = code;
, List this.message = message;
<String>> responseHeaders, String responseBody) { this.responseHeaders = responseHeaders;
this.code = code; this.responseBody = responseBody;
this.message = message; }
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
}
public int getCode() { public int getCode() {
return code; return code;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
/** /**
* Get the HTTP response headers. * Get the HTTP response headers.
*/ */
public Map public Map<String, List<String>> getResponseHeaders() {
<String return responseHeaders;
, List }
<String>> getResponseHeaders() {
return responseHeaders;
}
/** /**
* Get the HTTP response body. * Get the HTTP response body.
*/ */
public String getResponseBody() { public String getResponseBody() {
return responseBody; return responseBody;
} }
} }

View File

@@ -1,21 +1,21 @@
package io.swagger.client; package io.swagger.client;
public class Configuration { public class Configuration {
private static ApiClient defaultApiClient = new ApiClient(); private static ApiClient defaultApiClient = new ApiClient();
/** /**
* Get the default API client, which would be used when creating API * Get the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static ApiClient getDefaultApiClient() { public static ApiClient getDefaultApiClient() {
return defaultApiClient; return defaultApiClient;
} }
/** /**
* Set the default API client, which would be used when creating API * Set the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static void setDefaultApiClient(ApiClient apiClient) { public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient; defaultApiClient = apiClient;
} }
} }

View File

@@ -8,16 +8,16 @@ import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.datatype.joda.*; import com.fasterxml.jackson.datatype.joda.*;
public class JsonUtil { public class JsonUtil {
public static ObjectMapper mapper; public static ObjectMapper mapper;
static { static {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JodaModule()); mapper.registerModule(new JodaModule());
} }
public static ObjectMapper getJsonMapper() { public static ObjectMapper getJsonMapper() {
return mapper; return mapper;
} }
} }

View File

@@ -1,41 +1,41 @@
package io.swagger.client; package io.swagger.client;
public class StringUtil { public class StringUtil {
/** /**
* Check if the given array contains the given value (with case-insensitive comparison). * Check if the given array contains the given value (with case-insensitive comparison).
* *
* @param array The array * @param array The array
* @param value The value to search * @param value The value to search
* @return true if the array contains the value * @return true if the array contains the value
*/ */
public static boolean containsIgnoreCase(String[] array, String value) { public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) { for (String str : array) {
if (value == null && str == null) return true; if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true; if (value != null && value.equalsIgnoreCase(str)) return true;
} }
return false; return false;
} }
/** /**
* Join an array of strings with the given separator. * Join an array of strings with the given separator.
* <p> * <p>
* Note: This might be replaced by utility method from commons-lang or guava someday * Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency. * if one of those libraries is added as dependency.
* </p> * </p>
* *
* @param array The array of strings * @param array The array of strings
* @param separator The separator * @param separator The separator
* @return the resulting string * @return the resulting string
*/ */
public static String join(String[] array, String separator) { public static String join(String[] array, String separator) {
int len = array.length; int len = array.length;
if (len == 0) return ""; if (len == 0) return "";
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
out.append(array[0]); out.append(array[0]);
for (int i = 1; i < len; i++) { for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]); out.append(separator).append(array[i]);
} }
return out.toString(); return out.toString();
} }
} }

View File

@@ -20,287 +20,263 @@ import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
public class StoreApi { public class StoreApi {
private ApiClient apiClient; private ApiClient apiClient;
public StoreApi() { public StoreApi() {
this(Configuration.getDefaultApiClient()); this(Configuration.getDefaultApiClient());
} }
public StoreApi(ApiClient apiClient) { public StoreApi(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
} }
public ApiClient getApiClient() { public ApiClient getApiClient() {
return apiClient; return apiClient;
} }
public void setApiClient(ApiClient apiClient) { public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
} }
try {
/** String[] authNames = new String[] { "api_key" };
* Returns pet inventories by status String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
* Returns a map of status codes to quantities if(response != null){
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { "api_key" };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (Map<String, Integer>) apiClient.deserialize(response, "map", Map.class); return (Map<String, Integer>) apiClient.deserialize(response, "map", Map.class);
} }
else { else {
return null; return null;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Place an order for a pet * Place an order for a pet
* *
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Order * @return Order
*/ */
public Order placeOrder (Order body) throws ApiException { public Order placeOrder (Order body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/store/order".replaceAll("\\{format\\}","json"); String path = "/store/order".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = { final String[] accepts = {
"application/json", "application/xml" "application/json", "application/xml"
}; };
final String accept = apiClient.selectHeaderAccept(accepts); final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { final String[] contentTypes = {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void deleteOrder (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
} }
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (Order) apiClient.deserialize(response, "", Order.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void deleteOrder (String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder");
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
}

View File

@@ -20,551 +20,503 @@ import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
public class UserApi { public class UserApi {
private ApiClient apiClient; private ApiClient apiClient;
public UserApi() { public UserApi() {
this(Configuration.getDefaultApiClient()); this(Configuration.getDefaultApiClient());
} }
public UserApi(ApiClient apiClient) { public UserApi(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
} }
public ApiClient getApiClient() { public ApiClient getApiClient() {
return apiClient; return apiClient;
} }
public void setApiClient(ApiClient apiClient) { public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient; this.apiClient = apiClient;
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
*/
public void createUser (User body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/user".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
} }
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/** /**
* Create user * Creates list of users with given input array
* This can only be done by the logged in user. *
* @param body Created user object * @param body List of user object
* @return void * @return void
*/ */
public void createUser (User body) throws ApiException { public void createUsersWithArrayInput (List<User> body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/user".replaceAll("\\{format\\}","json"); String path = "/user/createWithArray".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = { final String[] accepts = {
"application/json", "application/xml" "application/json", "application/xml"
}; };
final String accept = apiClient.selectHeaderAccept(accepts); final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { final String[] contentTypes = {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
} }
try { try {
String[] authNames = new String[] { }; String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){ if(response != null){
return ; return ;
} }
else { else {
return ; return ;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
* @param body List of user object * @param body List of user object
* @return void * @return void
*/ */
public void createUsersWithArrayInput (List<User> body) throws ApiException { public void createUsersWithListInput (List<User> body) throws ApiException {
Object postBody = body; Object postBody = body;
// create path and map variables // create path and map variables
String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); String path = "/user/createWithList".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = { final String[] accepts = {
"application/json", "application/xml" "application/json", "application/xml"
}; };
final String accept = apiClient.selectHeaderAccept(accepts); final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { final String[] contentTypes = {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
} }
try { try {
String[] authNames = new String[] { }; String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){ if(response != null){
return ; return ;
} }
else { else {
return ; return ;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Creates list of users with given input array * Logs user into the system
* *
* @param body List of user object * @param username The user name for login
* @return void * @param password The password for login in clear text
*/ * @return String
public void createUsersWithListInput (List<User> body) throws ApiException { */
Object postBody = body; public String loginUser (String username, String password) throws ApiException {
Object postBody = null;
// create path and map variables // create path and map variables
String path = "/user/createWithList".replaceAll("\\{format\\}","json"); String path = "/user/login".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap if (username != null)
<String, String>(); queryParams.put("username", apiClient.parameterToString(username));
Map if (password != null)
<String, String> formParams = new HashMap queryParams.put("password", apiClient.parameterToString(password));
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] accepts = { final String[] contentTypes = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final String contentType = apiClient.selectHeaderContentType(contentTypes);
}; if(contentType.startsWith("multipart/form-data")) {
final String contentType = apiClient.selectHeaderContentType(contentTypes); boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(contentType.startsWith("multipart/form-data")) { if(hasFields)
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
} }
try { try {
String[] authNames = new String[] { }; String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){ if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
public String loginUser (String username, String password) throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/user/login".replaceAll("\\{format\\}","json");
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
if (username != null)
queryParams.put("username", apiClient.parameterToString(username));
if (password != null)
queryParams.put("password", apiClient.parameterToString(password));
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (String) apiClient.deserialize(response, "", String.class); return (String) apiClient.deserialize(response, "", String.class);
} }
else { else {
return null; return null;
} }
} catch (ApiException ex) { } catch (ApiException ex) {
throw ex; throw ex;
} }
} }
/** /**
* Logs out current logged in user session * Logs out current logged in user session
* *
* @return void * @return void
*/ */
public void logoutUser () throws ApiException { public void logoutUser () throws ApiException {
Object postBody = null; Object postBody = null;
// create path and map variables // create path and map variables
String path = "/user/logout".replaceAll("\\{format\\}","json"); String path = "/user/logout".replaceAll("\\{format\\}","json");
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = { final String[] accepts = {
"application/json", "application/xml" "application/json", "application/xml"
}; };
final String accept = apiClient.selectHeaderAccept(accepts); final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { final String[] contentTypes = {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (User) apiClient.deserialize(response, "", User.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void updateUser (String username, User body) throws ApiException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
} }
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return (User) apiClient.deserialize(response, "", User.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* 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
*/
public void updateUser (String username, User body) throws ApiException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser");
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String[] authNames = new String[] { };
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
throw ex;
}
}
}

View File

@@ -3,55 +3,53 @@ package io.swagger.client.auth;
import java.util.Map; import java.util.Map;
public class ApiKeyAuth implements Authentication { public class ApiKeyAuth implements Authentication {
private final String location; private final String location;
private final String paramName; private final String paramName;
private String apiKey; private String apiKey;
private String apiKeyPrefix; private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) { public ApiKeyAuth(String location, String paramName) {
this.location = location; this.location = location;
this.paramName = paramName; this.paramName = paramName;
} }
public String getLocation() { public String getLocation() {
return location; return location;
} }
public String getParamName() { public String getParamName() {
return paramName; return paramName;
} }
public String getApiKey() { public String getApiKey() {
return apiKey; return apiKey;
} }
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
this.apiKey = apiKey; this.apiKey = apiKey;
} }
public String getApiKeyPrefix() { public String getApiKeyPrefix() {
return apiKeyPrefix; return apiKeyPrefix;
} }
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix; this.apiKeyPrefix = apiKeyPrefix;
} }
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map String value;
<String, String> headerParams) { if (apiKeyPrefix != null) {
String value; value = apiKeyPrefix + " " + apiKey;
if (apiKeyPrefix != null) { } else {
value = apiKeyPrefix + " " + apiKey; value = apiKey;
} else { }
value = apiKey; if (location == "query") {
} queryParams.put(paramName, value);
if (location == "query") { } else if (location == "header") {
queryParams.put(paramName, value); headerParams.put(paramName, value);
} else if (location == "header") { }
headerParams.put(paramName, value); }
}
}
} }

View File

@@ -3,8 +3,6 @@ package io.swagger.client.auth;
import java.util.Map; import java.util.Map;
public interface Authentication { public interface Authentication {
/** Apply authentication settings to header and query params. */ /** Apply authentication settings to header and query params. */
void applyToParams(Map void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams);
<String, String> queryParams, Map
<String, String> headerParams);
} }

View File

@@ -6,34 +6,32 @@ import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
public class HttpBasicAuth implements Authentication { public class HttpBasicAuth implements Authentication {
private String username; private String username;
private String password; private String password;
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
<String, String> headerParams) { try {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
try { } catch (UnsupportedEncodingException e) {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) { }
throw new RuntimeException(e); }
}
}
} }

View File

@@ -3,10 +3,8 @@ package io.swagger.client.auth;
import java.util.Map; import java.util.Map;
public class OAuth implements Authentication { public class OAuth implements Authentication {
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map // TODO: support oauth
<String, String> headerParams) { }
// TODO: support oauth
}
} }

View File

@@ -5,40 +5,40 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
public class Category { public class Category {
private Long id = null; private Long id = null;
private String name = null; private String name = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("id") @JsonProperty("id")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("name") @JsonProperty("name")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Category {\n"); sb.append("class Category {\n");
@@ -46,6 +46,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -6,96 +6,96 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
public class Order { public class Order {
private Long id = null; private Long id = null;
private Long petId = null; private Long petId = null;
private Integer quantity = null; private Integer quantity = null;
private Date shipDate = null; private Date shipDate = null;
public enum StatusEnum { public enum StatusEnum {
placed, approved, delivered, placed, approved, delivered,
}; };
private StatusEnum status = null; private StatusEnum status = null;
private Boolean complete = null; private Boolean complete = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("id") @JsonProperty("id")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("petId") @JsonProperty("petId")
public Long getPetId() { public Long getPetId() {
return petId; return petId;
} }
public void setPetId(Long petId) { public void setPetId(Long petId) {
this.petId = petId; this.petId = petId;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("quantity") @JsonProperty("quantity")
public Integer getQuantity() { public Integer getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(Integer quantity) { public void setQuantity(Integer quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("shipDate") @JsonProperty("shipDate")
public Date getShipDate() { public Date getShipDate() {
return shipDate; return shipDate;
} }
public void setShipDate(Date shipDate) { public void setShipDate(Date shipDate) {
this.shipDate = shipDate; this.shipDate = shipDate;
} }
/** /**
* Order Status * Order Status
**/ **/
@ApiModelProperty(value = "Order Status") @ApiModelProperty(value = "Order Status")
@JsonProperty("status") @JsonProperty("status")
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("complete") @JsonProperty("complete")
public Boolean getComplete() { public Boolean getComplete() {
return complete; return complete;
} }
public void setComplete(Boolean complete) { public void setComplete(Boolean complete) {
this.complete = complete; this.complete = complete;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Order {\n"); sb.append("class Order {\n");
@@ -107,6 +107,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
sb.append(" complete: ").append(complete).append("\n"); sb.append(" complete: ").append(complete).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,103 +1,103 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.client.model.Category; import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*; import java.util.*;
import io.swagger.client.model.Tag;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
public class Pet { public class Pet {
private Long id = null; private Long id = null;
private Category category = null; private Category category = null;
private String name = null; private String name = null;
private List<String> photoUrls = new ArrayList<String>() ; private List<String> photoUrls = new ArrayList<String>() ;
private List<Tag> tags = new ArrayList<Tag>() ; private List<Tag> tags = new ArrayList<Tag>() ;
public enum StatusEnum { public enum StatusEnum {
available, pending, sold, available, pending, sold,
}; };
private StatusEnum status = null; private StatusEnum status = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("id") @JsonProperty("id")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("category") @JsonProperty("category")
public Category getCategory() { public Category getCategory() {
return category; return category;
} }
public void setCategory(Category category) { public void setCategory(Category category) {
this.category = category; this.category = category;
} }
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@JsonProperty("name") @JsonProperty("name")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@JsonProperty("photoUrls") @JsonProperty("photoUrls")
public List<String> getPhotoUrls() { public List<String> getPhotoUrls() {
return photoUrls; return photoUrls;
} }
public void setPhotoUrls(List<String> photoUrls) { public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls; this.photoUrls = photoUrls;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("tags") @JsonProperty("tags")
public List<Tag> getTags() { public List<Tag> getTags() {
return tags; return tags;
} }
public void setTags(List<Tag> tags) { public void setTags(List<Tag> tags) {
this.tags = tags; this.tags = tags;
} }
/** /**
* pet status in the store * pet status in the store
**/ **/
@ApiModelProperty(value = "pet status in the store") @ApiModelProperty(value = "pet status in the store")
@JsonProperty("status") @JsonProperty("status")
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n"); sb.append("class Pet {\n");
@@ -109,6 +109,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,40 +5,40 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
public class Tag { public class Tag {
private Long id = null; private Long id = null;
private String name = null; private String name = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("id") @JsonProperty("id")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("name") @JsonProperty("name")
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n"); sb.append("class Tag {\n");
@@ -46,6 +46,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,119 +5,119 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
public class User { public class User {
private Long id = null; private Long id = null;
private String username = null; private String username = null;
private String firstName = null; private String firstName = null;
private String lastName = null; private String lastName = null;
private String email = null; private String email = null;
private String password = null; private String password = null;
private String phone = null; private String phone = null;
private Integer userStatus = null; private Integer userStatus = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("id") @JsonProperty("id")
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("username") @JsonProperty("username")
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("firstName") @JsonProperty("firstName")
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("lastName") @JsonProperty("lastName")
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("email") @JsonProperty("email")
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("password") @JsonProperty("password")
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@JsonProperty("phone") @JsonProperty("phone")
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
/** /**
* User Status * User Status
**/ **/
@ApiModelProperty(value = "User Status") @ApiModelProperty(value = "User Status")
@JsonProperty("userStatus") @JsonProperty("userStatus")
public Integer getUserStatus() { public Integer getUserStatus() {
return userStatus; return userStatus;
} }
public void setUserStatus(Integer userStatus) { public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus; this.userStatus = userStatus;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class User {\n"); sb.append("class User {\n");
@@ -131,6 +131,5 @@ import com.fasterxml.jackson.annotation.JsonProperty;
sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append(" userStatus: ").append(userStatus).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,5 +1,5 @@
platform :ios, '6.0' platform :ios, '6.0'
xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' xcodeproj 'swaggerClient/swaggerClient.xcodeproj'
pod 'AFNetworking', '~> 2.1' pod 'AFNetworking', '~> 2.1'
pod 'JSONModel', '~> 1.0' pod 'JSONModel', '~> 1.0'
pod 'ISO8601' pod 'ISO8601'

View File

@@ -1,21 +1,15 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGCategory
@end
@protocol SWGCategory @interface SWGCategory : SWGObject
@end
@interface SWGCategory : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id; @property(nonatomic) NSString* name;
@property(nonatomic) NSString* name;
@end
@end

View File

@@ -1,24 +1,22 @@
#import "SWGCategory.h"
#import "SWGCategory.h" @implementation SWGCategory
@implementation SWGCategory + (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
+ (JSONKeyMapper *)keyMapper + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; NSArray *optionalProperties = @[@"_id", @"name"];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName if ([optionalProperties containsObject:propertyName]) {
{ return YES;
NSArray *optionalProperties = @[@"_id", @"name"]; }
else {
return NO;
}
}
if ([optionalProperties containsObject:propertyName]) { @end
return YES;
}
else {
return NO;
}
}
@end

View File

@@ -1,57 +1,56 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
@interface SWGConfiguration : NSObject @interface SWGConfiguration : NSObject
/** /**
* Api key values for Api Key type Authentication * Api key values for Api Key type Authentication
* *
* To add or remove api key, use `setValue:forApiKeyField:`. * To add or remove api key, use `setValue:forApiKeyField:`.
*/ */
@property (readonly, nonatomic, strong) NSDictionary *apiKey; @property (readonly, nonatomic, strong) NSDictionary *apiKey;
/** /**
* Api key prefix values to be prepend to the respective api key * Api key prefix values to be prepend to the respective api key
* *
* To add or remove prefix, use `setValue:forApiKeyPrefixField:`. * To add or remove prefix, use `setValue:forApiKeyPrefixField:`.
*/ */
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
/** /**
* Usename and Password for Basic type Authentication * Usename and Password for Basic type Authentication
*/ */
@property (nonatomic) NSString *username; @property (nonatomic) NSString *username;
@property (nonatomic) NSString *password; @property (nonatomic) NSString *password;
/** /**
* Get configuration singleton instance * Get configuration singleton instance
*/ */
+ (instancetype) sharedConfig; + (instancetype) sharedConfig;
/** /**
* Sets field in `apiKey` * Sets field in `apiKey`
*/ */
- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; - (void) setValue:(NSString *)value forApiKeyField:(NSString*)field;
/** /**
* Sets field in `apiKeyPrefix` * Sets field in `apiKeyPrefix`
*/ */
- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field;
/** /**
* Get API key (with prefix if set) * Get API key (with prefix if set)
*/ */
- (NSString *) getApiKeyWithPrefix:(NSString *) key; - (NSString *) getApiKeyWithPrefix:(NSString *) key;
/** /**
* Get Basic Auth token * Get Basic Auth token
*/ */
- (NSString *) getBasicAuthToken; - (NSString *) getBasicAuthToken;
/** /**
* Get Authentication Setings * Get Authentication Setings
*/ */
- (NSDictionary *) authSettings; - (NSDictionary *) authSettings;
@end @end

View File

@@ -12,81 +12,81 @@
#pragma mark - Singletion Methods #pragma mark - Singletion Methods
+ (instancetype) sharedConfig { + (instancetype) sharedConfig {
static SWGConfiguration *shardConfig = nil; static SWGConfiguration *shardConfig = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
shardConfig = [[self alloc] init]; shardConfig = [[self alloc] init];
}); });
return shardConfig; return shardConfig;
} }
#pragma mark - Initialize Methods #pragma mark - Initialize Methods
- (instancetype) init { - (instancetype) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.username = @""; self.username = @"";
self.password = @""; self.password = @"";
self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - Instance Methods #pragma mark - Instance Methods
- (NSString *) getApiKeyWithPrefix:(NSString *)key { - (NSString *) getApiKeyWithPrefix:(NSString *)key {
if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) {
return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]];
} }
else if ([self.apiKey objectForKey:key]) { else if ([self.apiKey objectForKey:key]) {
return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]];
} }
else { else {
return @""; return @"";
} }
} }
- (NSString *) getBasicAuthToken { - (NSString *) getBasicAuthToken {
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials; return basicAuthCredentials;
} }
#pragma mark - Setter Methods #pragma mark - Setter Methods
- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - (void) setValue:(NSString *)value forApiKeyField:(NSString *)field {
[self.mutableApiKey setValue:value forKey:field]; [self.mutableApiKey setValue:value forKey:field];
} }
- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field {
[self.mutableApiKeyPrefix setValue:value forKey:field]; [self.mutableApiKeyPrefix setValue:value forKey:field];
} }
#pragma mark - Getter Methods #pragma mark - Getter Methods
- (NSDictionary *) apiKey { - (NSDictionary *) apiKey {
return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; return [NSDictionary dictionaryWithDictionary:self.mutableApiKey];
} }
- (NSDictionary *) apiKeyPrefix { - (NSDictionary *) apiKeyPrefix {
return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix];
} }
#pragma mark - #pragma mark -
- (NSDictionary *) authSettings { - (NSDictionary *) authSettings {
return @{ return @{
@"api_key": @{ @"api_key": @{
@"type": @"api_key", @"type": @"api_key",
@"in": @"header", @"in": @"header",
@"key": @"api_key", @"key": @"api_key",
@"value": [self getApiKeyWithPrefix:@"api_key"] @"value": [self getApiKeyWithPrefix:@"api_key"]
}, },
}; };
} }
@end @end

View File

@@ -1,34 +1,24 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGOrder
@end
@protocol SWGOrder @interface SWGOrder : SWGObject
@end
@interface SWGOrder : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id; @property(nonatomic) NSNumber* petId;
@property(nonatomic) NSNumber* quantity;
@property(nonatomic) NSNumber* petId; @property(nonatomic) NSDate* shipDate;
/* Order Status [optional]
*/
@property(nonatomic) NSString* status;
@property(nonatomic) BOOL complete;
@property(nonatomic) NSNumber* quantity; @end
@property(nonatomic) NSDate* shipDate;
/* Order Status [optional]
*/
@property(nonatomic) NSString* status;
@property(nonatomic) BOOL complete;
@end

View File

@@ -1,24 +1,22 @@
#import "SWGOrder.h"
#import "SWGOrder.h" @implementation SWGOrder
@implementation SWGOrder + (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }];
}
+ (JSONKeyMapper *)keyMapper + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName if ([optionalProperties containsObject:propertyName]) {
{ return YES;
NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; }
else {
return NO;
}
}
if ([optionalProperties containsObject:propertyName]) { @end
return YES;
}
else {
return NO;
}
}
@end

View File

@@ -1,36 +1,26 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGTag.h"
#import "SWGCategory.h" #import "SWGCategory.h"
#import "SWGTag.h"
@protocol SWGPet
@end
@protocol SWGPet @interface SWGPet : SWGObject
@end
@interface SWGPet : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id; @property(nonatomic) SWGCategory* category;
@property(nonatomic) NSString* name;
@property(nonatomic) SWGCategory* category; @property(nonatomic) NSArray* photoUrls;
@property(nonatomic) NSArray<SWGTag>* tags;
/* pet status in the store [optional]
*/
@property(nonatomic) NSString* status;
@property(nonatomic) NSString* name; @end
@property(nonatomic) NSArray* photoUrls;
@property(nonatomic) NSArray<SWGTag>* tags;
/* pet status in the store [optional]
*/
@property(nonatomic) NSString* status;
@end

View File

@@ -1,24 +1,22 @@
#import "SWGPet.h"
#import "SWGPet.h" @implementation SWGPet
@implementation SWGPet + (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }];
}
+ (JSONKeyMapper *)keyMapper + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName if ([optionalProperties containsObject:propertyName]) {
{ return YES;
NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; }
else {
return NO;
}
}
if ([optionalProperties containsObject:propertyName]) { @end
return YES;
}
else {
return NO;
}
}
@end

View File

@@ -1,166 +1,156 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGPet.h" #import "SWGPet.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGPetApi: NSObject @interface SWGPetApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/** Update an existing pet
Update an existing pet
@param body Pet object that needs to be added to the store
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
return type:
*/
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Add a new pet to the store
/**
Add a new pet to the store @param body Pet object that needs to be added to the store
@param body Pet object that needs to be added to the store return type:
*/
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
return type: completionHandler: (void (^)(NSError* error))completionBlock;
*/
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock; /**
Finds Pets by status
Multiple status values can be provided with comma seperated strings
@param status Status values that need to be considered for filter
/**
Finds Pets by status return type: NSArray<SWGPet>*
Multiple status values can be provided with comma seperated strings */
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
@param status Status values that need to be considered for filter completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
return type: NSArray<SWGPet>*
*/
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; /**
Finds Pets by tags
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
@param tags Tags to filter by
/** return type: NSArray<SWGPet>*
*/
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
Finds Pets by tags completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
@param tags Tags to filter by
return type: NSArray<SWGPet>* /**
*/
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
@param petId ID of pet that needs to be fetched
return type: SWGPet*
*/
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
/** completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
@param petId ID of pet that needs to be fetched
/**
return type: SWGPet* Updates a pet in the store with form data
*/
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
@param petId ID of pet that needs to be updated
@param name Updated name of the pet
@param status Updated status of the pet
return type:
*/
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name
status:(NSString*) status
/**
Updates a pet in the store with form data completionHandler: (void (^)(NSError* error))completionBlock;
@param petId ID of pet that needs to be updated /**
@param name Updated name of the pet
@param status Updated status of the pet
Deletes a pet
return type:
*/
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name
status:(NSString*) status
@param apiKey
@param petId Pet id to delete
completionHandler: (void (^)(NSError* error))completionBlock;
return type:
*/
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey
petId:(NSNumber*) petId
/** completionHandler: (void (^)(NSError* error))completionBlock;
Deletes a pet
/**
@param apiKey uploads an image
@param petId Pet id to delete
return type: @param petId ID of pet to update
*/ @param additionalMetadata Additional data to pass to server
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey @param file file to upload
petId:(NSNumber*) petId
completionHandler: (void (^)(NSError* error))completionBlock; return type:
*/
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock;
/**
uploads an image
@param petId ID of pet to update
@param additionalMetadata Additional data to pass to server
@param file file to upload
return type:
*/
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock;

File diff suppressed because it is too large Load Diff

View File

@@ -1,85 +1,79 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGOrder.h" #import "SWGOrder.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGStoreApi: NSObject @interface SWGStoreApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/** Returns pet inventories by status
Returns a map of status codes to quantities
Returns pet inventories by status
Returns a map of status codes to quantities
return type: NSDictionary* return type: NSDictionary*
*/ */
-(NSNumber*) getInventoryWithCompletionBlock : -(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock; (void (^)(NSDictionary* output, NSError* error))completionBlock;
/**
/** Place an order for a pet
Place an order for a pet
@param body order placed for purchasing the pet @param body order placed for purchasing the pet
return type: SWGOrder* return type: SWGOrder*
*/ */
-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body -(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
/** Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
Find purchase order by ID @param orderId ID of pet that needs to be fetched
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
@param orderId ID of pet that needs to be fetched
return type: SWGOrder* return type: SWGOrder*
*/ */
-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId -(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
/** Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
Delete purchase order by ID @param orderId ID of the order that needs to be deleted
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
@param orderId ID of the order that needs to be deleted
return type: return type:
*/ */
-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId -(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;

View File

@@ -1,343 +1,343 @@
#import "SWGStoreApi.h" #import "SWGStoreApi.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGQueryParamCollection.h" #import "SWGQueryParamCollection.h"
#import "SWGOrder.h" #import "SWGOrder.h"
@interface SWGStoreApi ()
@interface SWGStoreApi ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end @end
@implementation SWGStoreApi @implementation SWGStoreApi
static NSString * basePath = @"http://petstore.swagger.io/v2"; static NSString * basePath = @"http://petstore.swagger.io/v2";
#pragma mark - Initialize methods #pragma mark - Initialize methods
- (id) init { - (id) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
- (id) initWithApiClient:(SWGApiClient *)apiClient { - (id) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init]; self = [super init];
if (self) { if (self) {
if (apiClient) { if (apiClient) {
self.apiClient = apiClient; self.apiClient = apiClient;
} }
else { else {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
} }
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - #pragma mark -
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGStoreApi* singletonAPI = nil; static SWGStoreApi* singletonAPI = nil;
if (singletonAPI == nil) { if (singletonAPI == nil) {
singletonAPI = [[SWGStoreApi alloc] init]; singletonAPI = [[SWGStoreApi alloc] init];
[singletonAPI addHeader:headerValue forKey:key]; [singletonAPI addHeader:headerValue forKey:key];
} }
return singletonAPI; return singletonAPI;
} }
+(void) setBasePath:(NSString*)path { +(void) setBasePath:(NSString*)path {
basePath = path; basePath = path;
} }
+(NSString*) getBasePath { +(NSString*) getBasePath {
return basePath; return basePath;
} }
-(void) addHeader:(NSString*)value forKey:(NSString*)key { -(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(void) setHeaderValue:(NSString*) value -(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key { forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(unsigned long) requestQueueSize { -(unsigned long) requestQueueSize {
return [SWGApiClient requestQueueSize]; return [SWGApiClient requestQueueSize];
} }
/*!
/*! * Returns pet inventories by status
* Returns pet inventories by status * Returns a map of status codes to quantities
* Returns a map of status codes to quantities * \returns NSDictionary*
* \returns NSDictionary* */
*/ -(NSNumber*) getInventoryWithCompletionBlock:
-(NSNumber*) getInventoryWithCompletionBlock:
(void (^)(NSDictionary* output, NSError* error))completionBlock (void (^)(NSDictionary* output, NSError* error))completionBlock
{ {
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
}
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
responseContentType = @"";
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"api_key"];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
// response is in a container
// map container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
} }
completionBlock(data, nil);
}]; // response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
responseContentType = @"";
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"api_key"];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
}
// response is in a container
// map container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
}];
/*!
* Place an order for a pet
*
* \param body order placed for purchasing the pet
* \returns SWGOrder* }
*/
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body /*!
* Place an order for a pet
*
* \param body order placed for purchasing the pet
* \returns SWGOrder*
*/
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[]; NSArray *authSettings = @[];
id bodyDictionary = nil; id bodyDictionary = nil;
id __body = body; id __body = body;
if(__body != nil && [__body isKindOfClass:[NSArray class]]){ if(__body != nil && [__body isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] init]; NSMutableArray * objs = [[NSMutableArray alloc] init];
for (id dict in (NSArray*)__body) { for (id dict in (NSArray*)__body) {
if([dict respondsToSelector:@selector(toDictionary)]) { if([dict respondsToSelector:@selector(toDictionary)]) {
[objs addObject:[(SWGObject*)dict toDictionary]]; [objs addObject:[(SWGObject*)dict toDictionary]];
} }
else{ else{
[objs addObject:dict]; [objs addObject:dict];
} }
}
bodyDictionary = objs;
}
else if([__body respondsToSelector:@selector(toDictionary)]) {
bodyDictionary = [(SWGObject*)__body toDictionary];
}
else if([__body isKindOfClass:[NSString class]]) {
// convert it to a dictionary
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
} }
bodyDictionary = objs;
}
else if([__body respondsToSelector:@selector(toDictionary)]) {
bodyDictionary = [(SWGObject*)__body toDictionary];
}
else if([__body isKindOfClass:[NSString class]]) {
// convert it to a dictionary
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
/*!
* Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* \param orderId ID of pet that needs to be fetched
* \returns SWGOrder*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId // non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
}
/*!
* Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* \param orderId ID of pet that needs to be fetched
* \returns SWGOrder*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
// verify the required parameter 'orderId' is set // verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById"); NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById");
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[]; NSArray *authSettings = @[];
id bodyDictionary = nil; id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
@@ -347,98 +347,99 @@ return;
// non container response // non container response
// complex response // complex response
// comples response type
// comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) { completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return; return;
} }
SWGOrder* result = nil; SWGOrder* result = nil;
if (data) { if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil]; result = [[SWGOrder alloc] initWithDictionary:data error:nil];
} }
completionBlock(result , nil); completionBlock(result , nil);
}]; }];
}
}
/*! /*!
* Delete purchase order by ID * Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* \param orderId ID of the order that needs to be deleted * \param orderId ID of the order that needs to be deleted
* \returns void * \returns void
*/ */
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
// verify the required parameter 'orderId' is set // verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder"); NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder");
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[]; NSArray *authSettings = @[];
id bodyDictionary = nil; id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
@@ -450,26 +451,25 @@ return;
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE" method: @"DELETE"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
}

View File

@@ -1,21 +1,15 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGTag
@end
@protocol SWGTag @interface SWGTag : SWGObject
@end
@interface SWGTag : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id; @property(nonatomic) NSString* name;
@property(nonatomic) NSString* name;
@end
@end

View File

@@ -1,24 +1,22 @@
#import "SWGTag.h"
#import "SWGTag.h" @implementation SWGTag
@implementation SWGTag + (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
+ (JSONKeyMapper *)keyMapper + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; NSArray *optionalProperties = @[@"_id", @"name"];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName if ([optionalProperties containsObject:propertyName]) {
{ return YES;
NSArray *optionalProperties = @[@"_id", @"name"]; }
else {
return NO;
}
}
if ([optionalProperties containsObject:propertyName]) { @end
return YES;
}
else {
return NO;
}
}
@end

View File

@@ -1,40 +1,28 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGUser
@end
@protocol SWGUser @interface SWGUser : SWGObject
@end
@interface SWGUser : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id; @property(nonatomic) NSString* username;
@property(nonatomic) NSString* firstName;
@property(nonatomic) NSString* username; @property(nonatomic) NSString* lastName;
@property(nonatomic) NSString* email;
@property(nonatomic) NSString* firstName; @property(nonatomic) NSString* password;
@property(nonatomic) NSString* phone;
/* User Status [optional]
*/
@property(nonatomic) NSNumber* userStatus;
@property(nonatomic) NSString* lastName; @end
@property(nonatomic) NSString* email;
@property(nonatomic) NSString* password;
@property(nonatomic) NSString* phone;
/* User Status [optional]
*/
@property(nonatomic) NSNumber* userStatus;
@end

View File

@@ -1,24 +1,22 @@
#import "SWGUser.h"
#import "SWGUser.h" @implementation SWGUser
@implementation SWGUser + (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }];
}
+ (JSONKeyMapper *)keyMapper + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName if ([optionalProperties containsObject:propertyName]) {
{ return YES;
NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; }
else {
return NO;
}
}
if ([optionalProperties containsObject:propertyName]) { @end
return YES;
}
else {
return NO;
}
}
@end

View File

@@ -1,157 +1,147 @@
#import #import <Foundation/Foundation.h>
<Foundation/Foundation.h>
#import "SWGUser.h" #import "SWGUser.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGUserApi: NSObject @interface SWGUserApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/** Create user
This can only be done by the logged in user.
Create user @param body Created user object
This can only be done by the logged in user.
@param body Created user object
return type:
*/
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
return type:
*/
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Creates list of users with given input array
/**
Creates list of users with given input array @param body List of user object
@param body List of user object return type:
*/
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
return type: completionHandler: (void (^)(NSError* error))completionBlock;
*/
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock; /**
Creates list of users with given input array
/** @param body List of user object
Creates list of users with given input array
return type:
*/
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
@param body List of user object
completionHandler: (void (^)(NSError* error))completionBlock;
return type:
*/
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
/**
completionHandler: (void (^)(NSError* error))completionBlock; Logs user into the system
@param username The user name for login
@param password The password for login in clear text
/**
Logs user into the system return type: NSString*
*/
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock;
@param username The user name for login
@param password The password for login in clear text
return type: NSString* /**
*/
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; Logs out current logged in user session
/** return type:
*/
-(NSNumber*) logoutUserWithCompletionBlock :
Logs out current logged in user session (void (^)(NSError* error))completionBlock;
/**
Get user by user name
return type:
*/
-(NSNumber*) logoutUserWithCompletionBlock :
(void (^)(NSError* error))completionBlock; @param username The name that needs to be fetched. Use user1 for testing.
return type: SWGUser*
*/
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
/** completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
Get user by user name
@param username The name that needs to be fetched. Use user1 for testing. /**
Updated user
This can only be done by the logged in user.
return type: SWGUser* @param username name that need to be deleted
*/ @param body Updated user object
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
return type:
*/
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Updated user /**
This can only be done by the logged in user.
@param username name that need to be deleted Delete user
@param body Updated user object This can only be done by the logged in user.
@param username The name that needs to be deleted
return type:
*/
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body
return type:
*/
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Delete user
This can only be done by the logged in user.
@param username The name that needs to be deleted
return type:
*/
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock;

File diff suppressed because it is too large Load Diff

View File

@@ -317,7 +317,7 @@ sub new {
# authentication setting, if any # authentication setting, if any
my $auth_settings = ['api_key', 'petstore_auth']; my $auth_settings = ['petstore_auth', 'api_key'];
# make the API Call # make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method, my $response = $self->{api_client}->call_api($_resource_path, $_method,

View File

@@ -327,7 +327,7 @@ class PetApi {
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array('api_key', 'petstore_auth'); $authSettings = array('petstore_auth', 'api_key');
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,

View File

@@ -9,8 +9,8 @@ from .models.order import Order
# import apis into sdk package # import apis into sdk package
from .apis.user_api import UserApi from .apis.user_api import UserApi
from .apis.pet_api import PetApi
from .apis.store_api import StoreApi from .apis.store_api import StoreApi
from .apis.pet_api import PetApi
# import ApiClient # import ApiClient
from .api_client import ApiClient from .api_client import ApiClient

View File

@@ -2,6 +2,6 @@ from __future__ import absolute_import
# import apis into api package # import apis into api package
from .user_api import UserApi from .user_api import UserApi
from .pet_api import PetApi
from .store_api import StoreApi from .store_api import StoreApi
from .pet_api import PetApi

View File

@@ -298,7 +298,7 @@ class PetApi(object):
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
# Authentication setting # Authentication setting
auth_settings = ['api_key', 'petstore_auth'] auth_settings = ['petstore_auth', 'api_key']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,

View File

@@ -1,112 +1,105 @@
#include "SWGCategory.h" #include "SWGCategory.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include #include <QJsonDocument>
<QJsonDocument> #include <QJsonArray>
#include #include <QObject>
<QJsonArray> #include <QDebug>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGCategory::SWGCategory(QString* json) { SWGCategory::SWGCategory(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGCategory::SWGCategory() { SWGCategory::SWGCategory() {
init(); init();
} }
SWGCategory::~SWGCategory() { SWGCategory::~SWGCategory() {
this->cleanup(); this->cleanup();
} }
void void
SWGCategory::init() { SWGCategory::init() {
id = 0L; id = 0L;
name = new QString(""); name = new QString("");
} }
void void
SWGCategory::cleanup() { SWGCategory::cleanup() {
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
} }
SWGCategory* SWGCategory*
SWGCategory::fromJson(QString &json) { SWGCategory::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGCategory::fromJsonObject(QJsonObject &pJson) { SWGCategory::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
} }
QString QString
SWGCategory::asJson () SWGCategory::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGCategory::asJsonObject() { SWGCategory::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("name"), name, obj, QString("QString")); toJsonValue(QString("name"), name, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGCategory::getId() {
return id;
}
void
SWGCategory::setId(qint64 id) {
this->id = id;
}
qint64 QString*
SWGCategory::getId() { SWGCategory::getName() {
return id; return name;
} }
void void
SWGCategory::setId(qint64 id) { SWGCategory::setName(QString* name) {
this->id = id; this->name = name;
} }
QString*
SWGCategory::getName() {
return name;
}
void
SWGCategory::setName(QString* name) {
this->name = name;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,48 +1,47 @@
/* /*
* SWGCategory.h * SWGCategory.h
* *
* *
*/ */
#ifndef SWGCategory_H_ #ifndef SWGCategory_H_
#define SWGCategory_H_ #define SWGCategory_H_
#include #include <QJsonObject>
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGCategory: public SWGObject { class SWGCategory: public SWGObject {
public: public:
SWGCategory(); SWGCategory();
SWGCategory(QString* json); SWGCategory(QString* json);
virtual ~SWGCategory(); virtual ~SWGCategory();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGCategory* fromJson(QString &jsonString); SWGCategory* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getName(); QString* getName();
void setName(QString* name); void setName(QString* name);
private: private:
qint64 id; qint64 id;
QString* name; QString* name;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGCategory_H_ */ #endif /* SWGCategory_H_ */

View File

@@ -1,201 +1,166 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include "SWGObject.h" #include "SWGObject.h"
#import #import <QDebug>
<QDebug> #import <QJsonArray>
#import #import <QJsonValue>
<QJsonArray>
#import
<QJsonValue>
namespace Swagger { namespace Swagger {
void void
setValue(void* value, QJsonValue obj, QString type, QString complexType) { setValue(void* value, QJsonValue obj, QString type, QString complexType) {
if(value == NULL) { if(value == NULL) {
// can't set value with a null pointer // can't set value with a null pointer
return; return;
} }
if(QStringLiteral("bool").compare(type) == 0) { if(QStringLiteral("bool").compare(type) == 0) {
bool * val = static_cast bool * val = static_cast<bool*>(value);
<bool *val = obj.toBool();
*>(value); }
*val = obj.toBool(); else if(QStringLiteral("qint32").compare(type) == 0) {
} qint32 *val = static_cast<qint32*>(value);
else if(QStringLiteral("qint32").compare(type) == 0) { *val = obj.toInt();
qint32 *val = static_cast }
<qint32 else if(QStringLiteral("qint64").compare(type) == 0) {
*>(value); qint64 *val = static_cast<qint64*>(value);
*val = obj.toInt(); *val = obj.toVariant().toLongLong();
} }
else if(QStringLiteral("qint64").compare(type) == 0) { else if (QStringLiteral("QString").compare(type) == 0) {
qint64 *val = static_cast QString **val = static_cast<QString**>(value);
<qint64
*>(value);
*val = obj.toVariant().toLongLong();
}
else if (QStringLiteral("QString").compare(type) == 0) {
QString **val = static_cast
<QString
**>(value);
if(val != NULL) { if(val != NULL) {
if(!obj.isNull()) { if(!obj.isNull()) {
// create a new value and return // create a new value and return
delete *val; delete *val;
*val = new QString(obj.toString()); *val = new QString(obj.toString());
return; return;
} }
else { else {
// set target to NULL // set target to NULL
delete *val; delete *val;
*val = NULL; *val = NULL;
} }
} }
else { else {
qDebug() << "Can't set value because the target pointer is NULL"; qDebug() << "Can't set value because the target pointer is NULL";
} }
} }
else if(type.startsWith("SWG") && obj.isObject()) { else if(type.startsWith("SWG") && obj.isObject()) {
// complex type // complex type
QJsonObject jsonObj = obj.toObject(); QJsonObject jsonObj = obj.toObject();
SWGObject * so = (SWGObject*)Swagger::create(type); SWGObject * so = (SWGObject*)Swagger::create(type);
if(so != NULL) { if(so != NULL) {
so->fromJsonObject(jsonObj); so->fromJsonObject(jsonObj);
SWGObject **val = static_cast SWGObject **val = static_cast<SWGObject**>(value);
<SWGObject
**>(value);
delete *val; delete *val;
*val = so; *val = so;
} }
} }
else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) {
// list of values // list of values
QList QList<void*>* output = new QList<void*>();
<void QJsonArray arr = obj.toArray();
*>* output = new QList foreach (const QJsonValue & jval, arr) {
<void
*>();
QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) {
if(complexType.startsWith("SWG")) { if(complexType.startsWith("SWG")) {
// it's an object // it's an object
SWGObject * val = (SWGObject*)create(complexType); SWGObject * val = (SWGObject*)create(complexType);
QJsonObject t = jval.toObject(); QJsonObject t = jval.toObject();
val->fromJsonObject(t); val->fromJsonObject(t);
output->append(val); output->append(val);
} }
else { else {
// primitives // primitives
if(QStringLiteral("qint32").compare(complexType) == 0) { if(QStringLiteral("qint32").compare(complexType) == 0) {
qint32 val; qint32 val;
setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
else if(QStringLiteral("qint64").compare(complexType) == 0) { else if(QStringLiteral("qint64").compare(complexType) == 0) {
qint64 val; qint64 val;
setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
else if(QStringLiteral("bool").compare(complexType) == 0) { else if(QStringLiteral("bool").compare(complexType) == 0) {
bool val; bool val;
setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("bool"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
}
}
QList
<void
*> **val = static_cast
<QList
<void
*>**>(value);
delete *val;
*val = output;
}
} }
}
QList<void*> **val = static_cast<QList<void*>**>(value);
delete *val;
*val = output;
}
}
void void
toJsonValue(QString name, void* value, QJsonObject* output, QString type) { toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
if(value == NULL) { if(value == NULL) {
return; return;
} }
if(type.startsWith("SWG")) { if(type.startsWith("SWG")) {
SWGObject *swgObject = reinterpret_cast SWGObject *swgObject = reinterpret_cast<SWGObject *>(value);
<SWGObject *>(value); if(swgObject != NULL) {
if(swgObject != NULL) { QJsonObject* o = (*swgObject).asJsonObject();
QJsonObject* o = (*swgObject).asJsonObject(); if(name != NULL) {
if(name != NULL) {
output->insert(name, *o); output->insert(name, *o);
delete o; delete o;
} }
else { else {
output->empty(); output->empty();
foreach(QString key, o->keys()) { foreach(QString key, o->keys()) {
output->insert(key, o->value(key)); output->insert(key, o->value(key));
}
}
}
}
else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast
<QString
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast
<qint32
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast
<qint64
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast
<bool
*>(value);
output->insert(name, QJsonValue(*str));
}
} }
}
}
}
else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast<QString*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast<qint32*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast<qint64*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast<bool*>(value);
output->insert(name, QJsonValue(*str));
}
}
void void
toJsonArray(QList toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType) {
<void foreach(void* obj, *value) {
*>* value, QJsonArray* output, QString innerName, QString innerType) { QJsonObject element;
foreach(void* obj, *value) {
QJsonObject element;
toJsonValue(NULL, obj, &element, innerType); toJsonValue(NULL, obj, &element, innerType);
output->append(element); output->append(element);
} }
} }
QString QString
stringValue(QString* value) { stringValue(QString* value) {
QString* str = static_cast QString* str = static_cast<QString*>(value);
<QString return QString(*str);
*>(value); }
return QString(*str);
}
QString QString
stringValue(qint32 value) { stringValue(qint32 value) {
return QString::number(value); return QString::number(value);
} }
QString QString
stringValue(qint64 value) { stringValue(qint64 value) {
return QString::number(value); return QString::number(value);
} }
QString QString
stringValue(bool value) { stringValue(bool value) {
return QString(value ? "true" : "false"); return QString(value ? "true" : "false");
} }
} /* namespace Swagger */ } /* namespace Swagger */

View File

@@ -1,20 +1,17 @@
#ifndef SWGHELPERS_H #ifndef SWGHELPERS_H
#define SWGHELPERS_H #define SWGHELPERS_H
#include #include <QJsonValue>
<QJsonValue>
namespace Swagger { namespace Swagger {
void setValue(void* value, QJsonValue obj, QString type, QString complexType); void setValue(void* value, QJsonValue obj, QString type, QString complexType);
void toJsonArray(QList void toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType);
<void
*>* value, QJsonArray* output, QString innerName, QString innerType);
void toJsonValue(QString name, void* value, QJsonObject* output, QString type); void toJsonValue(QString name, void* value, QJsonObject* output, QString type);
bool isCompatibleJsonValue(QString type); bool isCompatibleJsonValue(QString type);
QString stringValue(QString* value); QString stringValue(QString* value);
QString stringValue(qint32 value); QString stringValue(qint32 value);
QString stringValue(qint64 value); QString stringValue(qint64 value);
QString stringValue(bool value); QString stringValue(bool value);
} }
#endif // SWGHELPERS_H #endif // SWGHELPERS_H

View File

@@ -2,45 +2,44 @@
#define ModelFactory_H_ #define ModelFactory_H_
#include "SWGUser.h" #include "SWGUser.h"
#include "SWGCategory.h" #include "SWGCategory.h"
#include "SWGPet.h" #include "SWGPet.h"
#include "SWGTag.h" #include "SWGTag.h"
#include "SWGOrder.h" #include "SWGOrder.h"
namespace Swagger { namespace Swagger {
inline void* create(QString type) { inline void* create(QString type) {
if(QString("SWGUser").compare(type) == 0) { if(QString("SWGUser").compare(type) == 0) {
return new SWGUser(); return new SWGUser();
} }
if(QString("SWGCategory").compare(type) == 0) { if(QString("SWGCategory").compare(type) == 0) {
return new SWGCategory(); return new SWGCategory();
} }
if(QString("SWGPet").compare(type) == 0) { if(QString("SWGPet").compare(type) == 0) {
return new SWGPet(); return new SWGPet();
} }
if(QString("SWGTag").compare(type) == 0) { if(QString("SWGTag").compare(type) == 0) {
return new SWGTag(); return new SWGTag();
} }
if(QString("SWGOrder").compare(type) == 0) { if(QString("SWGOrder").compare(type) == 0) {
return new SWGOrder(); return new SWGOrder();
} }
return NULL; return NULL;
} }
inline void* create(QString json, QString type) { inline void* create(QString json, QString type) {
void* val = create(type); void* val = create(type);
if(val != NULL) { if(val != NULL) {
SWGObject* obj = static_cast SWGObject* obj = static_cast<SWGObject*>(val);
<SWGObject*>(val); return obj->fromJson(json);
return obj->fromJson(json); }
} if(type.startsWith("QString")) {
if(type.startsWith("QString")) { return new QString();
return new QString(); }
} return NULL;
return NULL; }
}
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* ModelFactory_H_ */ #endif /* ModelFactory_H_ */

View File

@@ -1,25 +1,24 @@
#ifndef _SWG_OBJECT_H_ #ifndef _SWG_OBJECT_H_
#define _SWG_OBJECT_H_ #define _SWG_OBJECT_H_
#include #include <QJsonValue>
<QJsonValue>
class SWGObject { class SWGObject {
public: public:
virtual QJsonObject* asJsonObject() { virtual QJsonObject* asJsonObject() {
return NULL; return NULL;
} }
virtual ~SWGObject() {} virtual ~SWGObject() {}
virtual SWGObject* fromJson(QString &jsonString) { virtual SWGObject* fromJson(QString &jsonString) {
Q_UNUSED(jsonString); Q_UNUSED(jsonString);
return NULL; return NULL;
} }
virtual void fromJsonObject(QJsonObject &json) { virtual void fromJsonObject(QJsonObject &json) {
Q_UNUSED(json); Q_UNUSED(json);
} }
virtual QString asJson() { virtual QString asJson() {
return QString(""); return QString("");
} }
}; };
#endif /* _SWG_OBJECT_H_ */ #endif /* _SWG_OBJECT_H_ */

View File

@@ -1,35 +1,31 @@
#include "SWGOrder.h" #include "SWGOrder.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include #include <QJsonDocument>
<QJsonDocument> #include <QJsonArray>
#include #include <QObject>
<QJsonArray> #include <QDebug>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGOrder::SWGOrder(QString* json) { SWGOrder::SWGOrder(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGOrder::SWGOrder() { SWGOrder::SWGOrder() {
init(); init();
} }
SWGOrder::~SWGOrder() { SWGOrder::~SWGOrder() {
this->cleanup(); this->cleanup();
} }
void void
SWGOrder::init() { SWGOrder::init() {
id = 0L; id = 0L;
petId = 0L; petId = 0L;
quantity = 0; quantity = 0;
@@ -37,34 +33,34 @@
status = new QString(""); status = new QString("");
complete = false; complete = false;
} }
void void
SWGOrder::cleanup() { SWGOrder::cleanup() {
if(shipDate != NULL) { if(shipDate != NULL) {
delete shipDate; delete shipDate;
} }
if(status != NULL) { if(status != NULL) {
delete status; delete status;
} }
} }
SWGOrder* SWGOrder*
SWGOrder::fromJson(QString &json) { SWGOrder::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGOrder::fromJsonObject(QJsonObject &pJson) { SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&petId, pJson["petId"], "qint64", ""); setValue(&petId, pJson["petId"], "qint64", "");
setValue(&quantity, pJson["quantity"], "qint32", ""); setValue(&quantity, pJson["quantity"], "qint32", "");
@@ -72,104 +68,97 @@
setValue(&status, pJson["status"], "QString", "QString"); setValue(&status, pJson["status"], "QString", "QString");
setValue(&complete, pJson["complete"], "bool", ""); setValue(&complete, pJson["complete"], "bool", "");
} }
QString QString
SWGOrder::asJson () SWGOrder::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGOrder::asJsonObject() { SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
obj->insert("petId", QJsonValue(petId)); obj->insert("petId", QJsonValue(petId));
obj->insert("quantity", QJsonValue(quantity)); obj->insert("quantity", QJsonValue(quantity));
toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime")); toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime"));
toJsonValue(QString("status"), status, obj, QString("QString")); toJsonValue(QString("status"), status, obj, QString("QString"));
obj->insert("complete", QJsonValue(complete)); obj->insert("complete", QJsonValue(complete));
return obj; return obj;
} }
qint64
SWGOrder::getId() {
return id;
}
void
SWGOrder::setId(qint64 id) {
this->id = id;
}
qint64 qint64
SWGOrder::getId() { SWGOrder::getPetId() {
return id; return petId;
} }
void void
SWGOrder::setId(qint64 id) { SWGOrder::setPetId(qint64 petId) {
this->id = id; this->petId = petId;
} }
qint32
SWGOrder::getQuantity() {
return quantity;
}
void
SWGOrder::setQuantity(qint32 quantity) {
this->quantity = quantity;
}
qint64 QDateTime*
SWGOrder::getPetId() { SWGOrder::getShipDate() {
return petId; return shipDate;
} }
void void
SWGOrder::setPetId(qint64 petId) { SWGOrder::setShipDate(QDateTime* shipDate) {
this->petId = petId; this->shipDate = shipDate;
} }
QString*
SWGOrder::getStatus() {
return status;
}
void
SWGOrder::setStatus(QString* status) {
this->status = status;
}
qint32 bool
SWGOrder::getQuantity() { SWGOrder::getComplete() {
return quantity; return complete;
} }
void void
SWGOrder::setQuantity(qint32 quantity) { SWGOrder::setComplete(bool complete) {
this->quantity = quantity; this->complete = complete;
} }
QDateTime*
SWGOrder::getShipDate() {
return shipDate;
}
void
SWGOrder::setShipDate(QDateTime* shipDate) {
this->shipDate = shipDate;
}
QString*
SWGOrder::getStatus() {
return status;
}
void
SWGOrder::setStatus(QString* status) {
this->status = status;
}
bool
SWGOrder::getComplete() {
return complete;
}
void
SWGOrder::setComplete(bool complete) {
this->complete = complete;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,52 +1,51 @@
/* /*
* SWGOrder.h * SWGOrder.h
* *
* *
*/ */
#ifndef SWGOrder_H_ #ifndef SWGOrder_H_
#define SWGOrder_H_ #define SWGOrder_H_
#include #include <QJsonObject>
<QJsonObject>
#include "QDateTime.h" #include "QDateTime.h"
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGOrder: public SWGObject { class SWGOrder: public SWGObject {
public: public:
SWGOrder(); SWGOrder();
SWGOrder(QString* json); SWGOrder(QString* json);
virtual ~SWGOrder(); virtual ~SWGOrder();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGOrder* fromJson(QString &jsonString); SWGOrder* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
qint64 getPetId(); qint64 getPetId();
void setPetId(qint64 petId); void setPetId(qint64 petId);
qint32 getQuantity(); qint32 getQuantity();
void setQuantity(qint32 quantity); void setQuantity(qint32 quantity);
QDateTime* getShipDate(); QDateTime* getShipDate();
void setShipDate(QDateTime* shipDate); void setShipDate(QDateTime* shipDate);
QString* getStatus(); QString* getStatus();
void setStatus(QString* status); void setStatus(QString* status);
bool getComplete(); bool getComplete();
void setComplete(bool complete); void setComplete(bool complete);
private: private:
qint64 id; qint64 id;
qint64 petId; qint64 petId;
qint32 quantity; qint32 quantity;
@@ -54,8 +53,8 @@
QString* status; QString* status;
bool complete; bool complete;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGOrder_H_ */ #endif /* SWGOrder_H_ */

View File

@@ -1,35 +1,31 @@
#include "SWGPet.h" #include "SWGPet.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include #include <QJsonDocument>
<QJsonDocument> #include <QJsonArray>
#include #include <QObject>
<QJsonArray> #include <QDebug>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGPet::SWGPet(QString* json) { SWGPet::SWGPet(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGPet::SWGPet() { SWGPet::SWGPet() {
init(); init();
} }
SWGPet::~SWGPet() { SWGPet::~SWGPet() {
this->cleanup(); this->cleanup();
} }
void void
SWGPet::init() { SWGPet::init() {
id = 0L; id = 0L;
category = new SWGCategory(); category = new SWGCategory();
name = new QString(""); name = new QString("");
@@ -37,48 +33,48 @@
tags = new QList<SWGTag*>(); tags = new QList<SWGTag*>();
status = new QString(""); status = new QString("");
} }
void void
SWGPet::cleanup() { SWGPet::cleanup() {
if(category != NULL) { if(category != NULL) {
delete category; delete category;
} }
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
if(photoUrls != NULL) { if(photoUrls != NULL) {
QList<QString*>* arr = photoUrls; QList<QString*>* arr = photoUrls;
foreach(QString* o, *arr) { foreach(QString* o, *arr) {
delete o; delete o;
}
delete photoUrls;
} }
delete photoUrls;
}
if(tags != NULL) { if(tags != NULL) {
QList<SWGTag*>* arr = tags; QList<SWGTag*>* arr = tags;
foreach(SWGTag* o, *arr) { foreach(SWGTag* o, *arr) {
delete o; delete o;
}
delete tags;
} }
delete tags;
}
if(status != NULL) { if(status != NULL) {
delete status; delete status;
} }
} }
SWGPet* SWGPet*
SWGPet::fromJson(QString &json) { SWGPet::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGPet::fromJsonObject(QJsonObject &pJson) { SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&category, pJson["category"], "SWGCategory", "SWGCategory"); setValue(&category, pJson["category"], "SWGCategory", "SWGCategory");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
@@ -86,127 +82,118 @@
setValue(&tags, pJson["tags"], "QList", "SWGTag"); setValue(&tags, pJson["tags"], "QList", "SWGTag");
setValue(&status, pJson["status"], "QString", "QString"); setValue(&status, pJson["status"], "QString", "QString");
} }
QString QString
SWGPet::asJson () SWGPet::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGPet::asJsonObject() { SWGPet::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("category"), category, obj, QString("SWGCategory")); toJsonValue(QString("category"), category, obj, QString("SWGCategory"));
toJsonValue(QString("name"), name, obj, QString("QString")); toJsonValue(QString("name"), name, obj, QString("QString"));
QList<QString*>* photoUrlsList = photoUrls; QList<QString*>* photoUrlsList = photoUrls;
QJsonArray photoUrlsJsonArray; QJsonArray photoUrlsJsonArray;
toJsonArray((QList toJsonArray((QList<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
obj->insert("photoUrls", photoUrlsJsonArray); obj->insert("photoUrls", photoUrlsJsonArray);
QList<SWGTag*>* tagsList = tags; QList<SWGTag*>* tagsList = tags;
QJsonArray tagsJsonArray; QJsonArray tagsJsonArray;
toJsonArray((QList toJsonArray((QList<void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
<void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
obj->insert("tags", tagsJsonArray); obj->insert("tags", tagsJsonArray);
toJsonValue(QString("status"), status, obj, QString("QString")); toJsonValue(QString("status"), status, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGPet::getId() {
return id;
}
void
SWGPet::setId(qint64 id) {
this->id = id;
}
qint64 SWGCategory*
SWGPet::getId() { SWGPet::getCategory() {
return id; return category;
} }
void void
SWGPet::setId(qint64 id) { SWGPet::setCategory(SWGCategory* category) {
this->id = id; this->category = category;
} }
QString*
SWGPet::getName() {
return name;
}
void
SWGPet::setName(QString* name) {
this->name = name;
}
SWGCategory* QList<QString*>*
SWGPet::getCategory() { SWGPet::getPhotoUrls() {
return category; return photoUrls;
} }
void void
SWGPet::setCategory(SWGCategory* category) { SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->category = category; this->photoUrls = photoUrls;
} }
QList<SWGTag*>*
SWGPet::getTags() {
return tags;
}
void
SWGPet::setTags(QList<SWGTag*>* tags) {
this->tags = tags;
}
QString* QString*
SWGPet::getName() { SWGPet::getStatus() {
return name; return status;
} }
void void
SWGPet::setName(QString* name) { SWGPet::setStatus(QString* status) {
this->name = name; this->status = status;
} }
QList<QString*>*
SWGPet::getPhotoUrls() {
return photoUrls;
}
void
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->photoUrls = photoUrls;
}
QList<SWGTag*>*
SWGPet::getTags() {
return tags;
}
void
SWGPet::setTags(QList<SWGTag*>* tags) {
this->tags = tags;
}
QString*
SWGPet::getStatus() {
return status;
}
void
SWGPet::setStatus(QString* status) {
this->status = status;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,54 +1,53 @@
/* /*
* SWGPet.h * SWGPet.h
* *
* *
*/ */
#ifndef SWGPet_H_ #ifndef SWGPet_H_
#define SWGPet_H_ #define SWGPet_H_
#include #include <QJsonObject>
<QJsonObject>
#include "SWGTag.h"
#include <QList>
#include "SWGCategory.h"
#include <QString> #include <QString>
#include "SWGCategory.h"
#include <QList>
#include "SWGTag.h"
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGPet: public SWGObject { class SWGPet: public SWGObject {
public: public:
SWGPet(); SWGPet();
SWGPet(QString* json); SWGPet(QString* json);
virtual ~SWGPet(); virtual ~SWGPet();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGPet* fromJson(QString &jsonString); SWGPet* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
SWGCategory* getCategory(); SWGCategory* getCategory();
void setCategory(SWGCategory* category); void setCategory(SWGCategory* category);
QString* getName(); QString* getName();
void setName(QString* name); void setName(QString* name);
QList<QString*>* getPhotoUrls(); QList<QString*>* getPhotoUrls();
void setPhotoUrls(QList<QString*>* photoUrls); void setPhotoUrls(QList<QString*>* photoUrls);
QList<SWGTag*>* getTags(); QList<SWGTag*>* getTags();
void setTags(QList<SWGTag*>* tags); void setTags(QList<SWGTag*>* tags);
QString* getStatus(); QString* getStatus();
void setStatus(QString* status); void setStatus(QString* status);
private: private:
qint64 id; qint64 id;
SWGCategory* category; SWGCategory* category;
QString* name; QString* name;
@@ -56,8 +55,8 @@
QList<SWGTag*>* tags; QList<SWGTag*>* tags;
QString* status; QString* status;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGPet_H_ */ #endif /* SWGPet_H_ */

View File

@@ -2,126 +2,339 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include #include <QJsonArray>
<QJsonArray> #include <QJsonDocument>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGPetApi::SWGPetApi() {} SWGPetApi::SWGPetApi() {}
SWGPetApi::~SWGPetApi() {} SWGPetApi::~SWGPetApi() {}
SWGPetApi::SWGPetApi(QString host, QString basePath) { SWGPetApi::SWGPetApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
}
void
SWGPetApi::updatePet(SWGPet body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::updatePetCallback);
worker->execute(&input);
}
void
SWGPetApi::updatePetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit updatePetSignal();
}
void
SWGPetApi::addPet(SWGPet body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::addPetCallback);
worker->execute(&input);
}
void
SWGPetApi::addPetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit addPetSignal();
}
void
SWGPetApi::findPetsByStatus(QList<QString*>* status) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus");
if(status->size() > 0) {
if(QString("multi").indexOf("multi") == 0) {
foreach(QString* t, *status) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=").append(stringValue(t));
} }
}
else if (QString("multi").indexOf("ssv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
qint32 count = 0;
foreach(QString* t, *status) {
if(count > 0) {
fullPath.append(" ");
}
fullPath.append(stringValue(t));
}
}
else if (QString("multi").indexOf("tsv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
qint32 count = 0;
foreach(QString* t, *status) {
if(count > 0) {
fullPath.append("\t");
}
fullPath.append(stringValue(t));
}
}
}
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
void connect(worker,
SWGPetApi::updatePet(SWGPet body) { &HttpRequestWorker::on_execution_finished,
QString fullPath; this,
fullPath.append(this->host).append(this->basePath).append("/pet"); &SWGPetApi::findPetsByStatusCallback);
worker->execute(&input);
}
void
SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QList<SWGPet*>* output = new QList<SWGPet*>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
HttpRequestWorker *worker = new HttpRequestWorker(); foreach(QJsonValue obj, jsonArray) {
HttpRequestInput input(fullPath, "PUT"); SWGPet* o = new SWGPet();
QJsonObject jv = obj.toObject();
QJsonObject * ptr = (QJsonObject*)&jv;
o->fromJsonObject(*ptr);
output->append(o);
}
worker->deleteLater();
emit findPetsByStatusSignal(output);
QString output = body.asJson(); }
input.request_body.append(output); void
SWGPetApi::findPetsByTags(QList<QString*>* tags) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/findByTags");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::updatePetCallback);
worker->execute(&input);
}
void
SWGPetApi::updatePetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
if(tags->size() > 0) {
if(QString("multi").indexOf("multi") == 0) {
foreach(QString* t, *tags) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=").append(stringValue(t));
}
}
else if (QString("multi").indexOf("ssv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
qint32 count = 0;
foreach(QString* t, *tags) {
if(count > 0) {
fullPath.append(" ");
}
fullPath.append(stringValue(t));
}
}
else if (QString("multi").indexOf("tsv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
qint32 count = 0;
foreach(QString* t, *tags) {
if(count > 0) {
fullPath.append("\t");
}
fullPath.append(stringValue(t));
}
}
}
worker->deleteLater();
emit updatePetSignal();
}
void HttpRequestWorker *worker = new HttpRequestWorker();
SWGPetApi::addPet(SWGPet body) { HttpRequestInput input(fullPath, "GET");
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::findPetsByTagsCallback);
worker->execute(&input);
}
void
SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString output = body.asJson(); QList<SWGPet*>* output = new QList<SWGPet*>();
input.request_body.append(output); QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
SWGPet* o = new SWGPet();
QJsonObject jv = obj.toObject();
QJsonObject * ptr = (QJsonObject*)&jv;
o->fromJsonObject(*ptr);
output->append(o);
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::addPetCallback);
worker->execute(&input); worker->deleteLater();
}
void emit findPetsByTagsSignal(output);
SWGPetApi::addPetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
}
void
SWGPetApi::getPetById(qint64 petId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
worker->deleteLater(); QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
emit addPetSignal();
}
void
SWGPetApi::findPetsByStatus(QList<QString*>* status) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
@@ -129,422 +342,190 @@
if(status->size() > 0) { connect(worker,
if(QString("multi").indexOf("multi") == 0) { &HttpRequestWorker::on_execution_finished,
foreach(QString* t, *status) { this,
if(fullPath.indexOf("?") > 0) &SWGPetApi::getPetByIdCallback);
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=").append(stringValue(t));
}
}
else if (QString("multi").indexOf("ssv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
qint32 count = 0;
foreach(QString* t, *status) {
if(count > 0) {
fullPath.append(" ");
}
fullPath.append(stringValue(t));
}
}
else if (QString("multi").indexOf("tsv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("status=");
qint32 count = 0;
foreach(QString* t, *status) {
if(count > 0) {
fullPath.append("\t");
}
fullPath.append(stringValue(t));
}
}
}
worker->execute(&input);
}
void
SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
QString json(worker->response);
SWGPet* output = static_cast<SWGPet*>(create(json, QString("SWGPet")));
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::findPetsByStatusCallback);
worker->execute(&input); worker->deleteLater();
}
void emit getPetByIdSignal(output);
SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
}
void
SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QList<SWGPet*>* output = new QList<SWGPet*>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) { QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
SWGPet* o = new SWGPet(); fullPath.replace(petIdPathParam, stringValue(petId));
QJsonObject jv = obj.toObject();
QJsonObject * ptr = (QJsonObject*)&jv;
o->fromJsonObject(*ptr);
output->append(o);
}
worker->deleteLater(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
emit findPetsByStatusSignal(output);
} if(name != NULL) {
input.add_var("name", *name);
}
void if(status != NULL) {
SWGPetApi::findPetsByTags(QList<QString*>* tags) { input.add_var("status", *status);
QString fullPath; }
fullPath.append(this->host).append(this->basePath).append("/pet/findByTags");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::updatePetWithFormCallback);
worker->execute(&input);
}
if(tags->size() > 0) { void
if(QString("multi").indexOf("multi") == 0) { SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) {
foreach(QString* t, *tags) { QString msg;
if(fullPath.indexOf("?") > 0) if (worker->error_type == QNetworkReply::NoError) {
fullPath.append("&"); msg = QString("Success! %1 bytes").arg(worker->response.length());
else }
fullPath.append("?"); else {
fullPath.append("tags=").append(stringValue(t)); msg = "Error: " + worker->error_str;
} }
}
else if (QString("multi").indexOf("ssv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
qint32 count = 0;
foreach(QString* t, *tags) {
if(count > 0) {
fullPath.append(" ");
}
fullPath.append(stringValue(t));
}
}
else if (QString("multi").indexOf("tsv") == 0) {
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("tags=");
qint32 count = 0;
foreach(QString* t, *tags) {
if(count > 0) {
fullPath.append("\t");
}
fullPath.append(stringValue(t));
}
}
}
worker->deleteLater();
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
emit updatePetWithFormSignal();
}
void
SWGPetApi::deletePet(QString* apiKey, qint64 petId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
connect(worker, HttpRequestWorker *worker = new HttpRequestWorker();
&HttpRequestWorker::on_execution_finished, HttpRequestInput input(fullPath, "DELETE");
this,
&SWGPetApi::findPetsByTagsCallback);
worker->execute(&input);
}
void
SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QList<SWGPet*>* output = new QList<SWGPet*>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
SWGPet* o = new SWGPet();
QJsonObject jv = obj.toObject();
QJsonObject * ptr = (QJsonObject*)&jv;
o->fromJsonObject(*ptr);
output->append(o);
}
// TODO: add header support
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::deletePetCallback);
worker->deleteLater(); worker->execute(&input);
}
emit findPetsByTagsSignal(output); void
SWGPetApi::deletePetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
}
void
SWGPetApi::getPetById(qint64 petId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
worker->deleteLater();
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
emit deletePetSignal();
}
void
SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
if(additionalMetadata != NULL) {
input.add_var("additionalMetadata", *additionalMetadata);
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::getPetByIdCallback);
worker->execute(&input);
}
void
SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::uploadFileCallback);
worker->execute(&input);
}
void
SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGPet* output = static_cast<SWGPet*>(create(json,
QString("SWGPet")));
worker->deleteLater();
emit uploadFileSignal();
worker->deleteLater(); }
} /* namespace Swagger */
emit getPetByIdSignal(output);
}
void
SWGPetApi::updatePetWithForm(QString* petId
, QString* name
, QString* status) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
if(name != NULL) {
input.add_var("name", *name);
}
if(status != NULL) {
input.add_var("status", *status);
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::updatePetWithFormCallback);
worker->execute(&input);
}
void
SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit updatePetWithFormSignal();
}
void
SWGPetApi::deletePet(QString* apiKey
, qint64 petId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
// TODO: add header support
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::deletePetCallback);
worker->execute(&input);
}
void
SWGPetApi::deletePetCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit deletePetSignal();
}
void
SWGPetApi::uploadFile(qint64 petId
, QString* additionalMetadata
, SWGHttpRequestInputFileElement* file) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage");
QString petIdPathParam("{"); petIdPathParam.append("petId").append("}");
fullPath.replace(petIdPathParam, stringValue(petId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
if(additionalMetadata != NULL) {
input.add_var("additionalMetadata", *additionalMetadata);
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGPetApi::uploadFileCallback);
worker->execute(&input);
}
void
SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit uploadFileSignal();
}
} /* namespace Swagger */

View File

@@ -7,15 +7,14 @@
#include <QString> #include <QString>
#include "SWGHttpRequest.h" #include "SWGHttpRequest.h"
#include #include <QObject>
<QObject>
namespace Swagger { namespace Swagger {
class SWGPetApi: public QObject { class SWGPetApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGPetApi(); SWGPetApi();
SWGPetApi(QString host, QString basePath); SWGPetApi(QString host, QString basePath);
~SWGPetApi(); ~SWGPetApi();
@@ -28,16 +27,11 @@
void findPetsByStatus(QList<QString*>* status); void findPetsByStatus(QList<QString*>* status);
void findPetsByTags(QList<QString*>* tags); void findPetsByTags(QList<QString*>* tags);
void getPetById(qint64 petId); void getPetById(qint64 petId);
void updatePetWithForm(QString* petId void updatePetWithForm(QString* petId, QString* name, QString* status);
, QString* name void deletePet(QString* apiKey, qint64 petId);
, QString* status); void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file);
void deletePet(QString* apiKey
, qint64 petId);
void uploadFile(qint64 petId
, QString* additionalMetadata
, SWGHttpRequestInputFileElement* file);
private: private:
void updatePetCallback (HttpRequestWorker * worker); void updatePetCallback (HttpRequestWorker * worker);
void addPetCallback (HttpRequestWorker * worker); void addPetCallback (HttpRequestWorker * worker);
void findPetsByStatusCallback (HttpRequestWorker * worker); void findPetsByStatusCallback (HttpRequestWorker * worker);
@@ -47,7 +41,7 @@
void deletePetCallback (HttpRequestWorker * worker); void deletePetCallback (HttpRequestWorker * worker);
void uploadFileCallback (HttpRequestWorker * worker); void uploadFileCallback (HttpRequestWorker * worker);
signals: signals:
void updatePetSignal(); void updatePetSignal();
void addPetSignal(); void addPetSignal();
void findPetsByStatusSignal(QList<SWGPet*>* summary); void findPetsByStatusSignal(QList<SWGPet*>* summary);
@@ -57,6 +51,6 @@
void deletePetSignal(); void deletePetSignal();
void uploadFileSignal(); void uploadFileSignal();
}; };
} }
#endif #endif

View File

@@ -2,249 +2,238 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include #include <QJsonArray>
<QJsonArray> #include <QJsonDocument>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGStoreApi::SWGStoreApi() {} SWGStoreApi::SWGStoreApi() {}
SWGStoreApi::~SWGStoreApi() {} SWGStoreApi::~SWGStoreApi() {}
SWGStoreApi::SWGStoreApi(QString host, QString basePath) { SWGStoreApi::SWGStoreApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
} }
void
SWGStoreApi::getInventory() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory");
void
SWGStoreApi::getInventory() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getInventoryCallback);
worker->execute(&input);
}
connect(worker, void
&HttpRequestWorker::on_execution_finished, SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) {
this, QString msg;
&SWGStoreApi::getInventoryCallback); if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->execute(&input);
}
void
SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QMap<QString, qint32>* output = new QMap<QString, qint32>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject obj = doc.object();
QMap<QString, qint32>* output = new QMap<QString, qint32>(); foreach(QString key, obj.keys()) {
qint32* val;
setValue(&val, obj[key], "QMap", "");
output->insert(key, *val);
}
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject obj = doc.object();
foreach(QString key, obj.keys()) {
qint32* val;
setValue(&val, obj[key], "QMap", "");
output->insert(key, *val);
}
worker->deleteLater();
emit getInventorySignal(output);
worker->deleteLater(); }
void
SWGStoreApi::placeOrder(SWGOrder body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order");
emit getInventorySignal(output);
}
void
SWGStoreApi::placeOrder(SWGOrder body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QString output = body.asJson();
input.request_body.append(output);
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::placeOrderCallback);
worker->execute(&input);
}
void
SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::placeOrderCallback);
worker->execute(&input);
}
void
SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder")));
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
worker->deleteLater();
emit placeOrderSignal(output);
}
void
SWGStoreApi::getOrderById(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
worker->deleteLater();
emit placeOrderSignal(output); QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
}
void
SWGStoreApi::getOrderById(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); HttpRequestWorker *worker = new HttpRequestWorker();
fullPath.replace(orderIdPathParam, stringValue(orderId)); HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getOrderByIdCallback);
worker->execute(&input);
}
void
SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getOrderByIdCallback);
worker->execute(&input);
}
void
SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder")));
QString json(worker->response); worker->deleteLater();
SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
emit getOrderByIdSignal(output);
}
void
SWGStoreApi::deleteOrder(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
worker->deleteLater(); QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
emit getOrderByIdSignal(output);
}
void
SWGStoreApi::deleteOrder(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::deleteOrderCallback);
worker->execute(&input);
}
void
SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker, worker->deleteLater();
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::deleteOrderCallback);
worker->execute(&input);
}
void emit deleteOrderSignal();
SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) { }
QString msg; } /* namespace Swagger */
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit deleteOrderSignal();
}
} /* namespace Swagger */

View File

@@ -7,15 +7,14 @@
#include "SWGOrder.h" #include "SWGOrder.h"
#include <QString> #include <QString>
#include #include <QObject>
<QObject>
namespace Swagger { namespace Swagger {
class SWGStoreApi: public QObject { class SWGStoreApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGStoreApi(); SWGStoreApi();
SWGStoreApi(QString host, QString basePath); SWGStoreApi(QString host, QString basePath);
~SWGStoreApi(); ~SWGStoreApi();
@@ -28,18 +27,18 @@
void getOrderById(QString* orderId); void getOrderById(QString* orderId);
void deleteOrder(QString* orderId); void deleteOrder(QString* orderId);
private: private:
void getInventoryCallback (HttpRequestWorker * worker); void getInventoryCallback (HttpRequestWorker * worker);
void placeOrderCallback (HttpRequestWorker * worker); void placeOrderCallback (HttpRequestWorker * worker);
void getOrderByIdCallback (HttpRequestWorker * worker); void getOrderByIdCallback (HttpRequestWorker * worker);
void deleteOrderCallback (HttpRequestWorker * worker); void deleteOrderCallback (HttpRequestWorker * worker);
signals: signals:
void getInventorySignal(QMap<QString, qint32>* summary); void getInventorySignal(QMap<QString, qint32>* summary);
void placeOrderSignal(SWGOrder* summary); void placeOrderSignal(SWGOrder* summary);
void getOrderByIdSignal(SWGOrder* summary); void getOrderByIdSignal(SWGOrder* summary);
void deleteOrderSignal(); void deleteOrderSignal();
}; };
} }
#endif #endif

View File

@@ -1,112 +1,105 @@
#include "SWGTag.h" #include "SWGTag.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include #include <QJsonDocument>
<QJsonDocument> #include <QJsonArray>
#include #include <QObject>
<QJsonArray> #include <QDebug>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGTag::SWGTag(QString* json) { SWGTag::SWGTag(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGTag::SWGTag() { SWGTag::SWGTag() {
init(); init();
} }
SWGTag::~SWGTag() { SWGTag::~SWGTag() {
this->cleanup(); this->cleanup();
} }
void void
SWGTag::init() { SWGTag::init() {
id = 0L; id = 0L;
name = new QString(""); name = new QString("");
} }
void void
SWGTag::cleanup() { SWGTag::cleanup() {
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
} }
SWGTag* SWGTag*
SWGTag::fromJson(QString &json) { SWGTag::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGTag::fromJsonObject(QJsonObject &pJson) { SWGTag::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
} }
QString QString
SWGTag::asJson () SWGTag::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGTag::asJsonObject() { SWGTag::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("name"), name, obj, QString("QString")); toJsonValue(QString("name"), name, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGTag::getId() {
return id;
}
void
SWGTag::setId(qint64 id) {
this->id = id;
}
qint64 QString*
SWGTag::getId() { SWGTag::getName() {
return id; return name;
} }
void void
SWGTag::setId(qint64 id) { SWGTag::setName(QString* name) {
this->id = id; this->name = name;
} }
QString*
SWGTag::getName() {
return name;
}
void
SWGTag::setName(QString* name) {
this->name = name;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,48 +1,47 @@
/* /*
* SWGTag.h * SWGTag.h
* *
* *
*/ */
#ifndef SWGTag_H_ #ifndef SWGTag_H_
#define SWGTag_H_ #define SWGTag_H_
#include #include <QJsonObject>
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGTag: public SWGObject { class SWGTag: public SWGObject {
public: public:
SWGTag(); SWGTag();
SWGTag(QString* json); SWGTag(QString* json);
virtual ~SWGTag(); virtual ~SWGTag();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGTag* fromJson(QString &jsonString); SWGTag* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getName(); QString* getName();
void setName(QString* name); void setName(QString* name);
private: private:
qint64 id; qint64 id;
QString* name; QString* name;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGTag_H_ */ #endif /* SWGTag_H_ */

View File

@@ -1,35 +1,31 @@
#include "SWGUser.h" #include "SWGUser.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include #include <QJsonDocument>
<QJsonDocument> #include <QJsonArray>
#include #include <QObject>
<QJsonArray> #include <QDebug>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGUser::SWGUser(QString* json) { SWGUser::SWGUser(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGUser::SWGUser() { SWGUser::SWGUser() {
init(); init();
} }
SWGUser::~SWGUser() { SWGUser::~SWGUser() {
this->cleanup(); this->cleanup();
} }
void void
SWGUser::init() { SWGUser::init() {
id = 0L; id = 0L;
username = new QString(""); username = new QString("");
firstName = new QString(""); firstName = new QString("");
@@ -39,44 +35,44 @@
phone = new QString(""); phone = new QString("");
userStatus = 0; userStatus = 0;
} }
void void
SWGUser::cleanup() { SWGUser::cleanup() {
if(username != NULL) { if(username != NULL) {
delete username; delete username;
} }
if(firstName != NULL) { if(firstName != NULL) {
delete firstName; delete firstName;
} }
if(lastName != NULL) { if(lastName != NULL) {
delete lastName; delete lastName;
} }
if(email != NULL) { if(email != NULL) {
delete email; delete email;
} }
if(password != NULL) { if(password != NULL) {
delete password; delete password;
} }
if(phone != NULL) { if(phone != NULL) {
delete phone; delete phone;
} }
} }
SWGUser* SWGUser*
SWGUser::fromJson(QString &json) { SWGUser::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGUser::fromJsonObject(QJsonObject &pJson) { SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&username, pJson["username"], "QString", "QString"); setValue(&username, pJson["username"], "QString", "QString");
setValue(&firstName, pJson["firstName"], "QString", "QString"); setValue(&firstName, pJson["firstName"], "QString", "QString");
@@ -86,146 +82,137 @@
setValue(&phone, pJson["phone"], "QString", "QString"); setValue(&phone, pJson["phone"], "QString", "QString");
setValue(&userStatus, pJson["userStatus"], "qint32", ""); setValue(&userStatus, pJson["userStatus"], "qint32", "");
} }
QString QString
SWGUser::asJson () SWGUser::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGUser::asJsonObject() { SWGUser::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("username"), username, obj, QString("QString")); toJsonValue(QString("username"), username, obj, QString("QString"));
toJsonValue(QString("firstName"), firstName, obj, QString("QString")); toJsonValue(QString("firstName"), firstName, obj, QString("QString"));
toJsonValue(QString("lastName"), lastName, obj, QString("QString")); toJsonValue(QString("lastName"), lastName, obj, QString("QString"));
toJsonValue(QString("email"), email, obj, QString("QString")); toJsonValue(QString("email"), email, obj, QString("QString"));
toJsonValue(QString("password"), password, obj, QString("QString")); toJsonValue(QString("password"), password, obj, QString("QString"));
toJsonValue(QString("phone"), phone, obj, QString("QString")); toJsonValue(QString("phone"), phone, obj, QString("QString"));
obj->insert("userStatus", QJsonValue(userStatus)); obj->insert("userStatus", QJsonValue(userStatus));
return obj; return obj;
} }
qint64
SWGUser::getId() {
return id;
}
void
SWGUser::setId(qint64 id) {
this->id = id;
}
qint64 QString*
SWGUser::getId() { SWGUser::getUsername() {
return id; return username;
} }
void void
SWGUser::setId(qint64 id) { SWGUser::setUsername(QString* username) {
this->id = id; this->username = username;
} }
QString*
SWGUser::getFirstName() {
return firstName;
}
void
SWGUser::setFirstName(QString* firstName) {
this->firstName = firstName;
}
QString* QString*
SWGUser::getUsername() { SWGUser::getLastName() {
return username; return lastName;
} }
void void
SWGUser::setUsername(QString* username) { SWGUser::setLastName(QString* lastName) {
this->username = username; this->lastName = lastName;
} }
QString*
SWGUser::getEmail() {
return email;
}
void
SWGUser::setEmail(QString* email) {
this->email = email;
}
QString* QString*
SWGUser::getFirstName() { SWGUser::getPassword() {
return firstName; return password;
} }
void void
SWGUser::setFirstName(QString* firstName) { SWGUser::setPassword(QString* password) {
this->firstName = firstName; this->password = password;
} }
QString*
SWGUser::getPhone() {
return phone;
}
void
SWGUser::setPhone(QString* phone) {
this->phone = phone;
}
QString* qint32
SWGUser::getLastName() { SWGUser::getUserStatus() {
return lastName; return userStatus;
} }
void void
SWGUser::setLastName(QString* lastName) { SWGUser::setUserStatus(qint32 userStatus) {
this->lastName = lastName; this->userStatus = userStatus;
} }
QString*
SWGUser::getEmail() {
return email;
}
void
SWGUser::setEmail(QString* email) {
this->email = email;
}
QString*
SWGUser::getPassword() {
return password;
}
void
SWGUser::setPassword(QString* password) {
this->password = password;
}
QString*
SWGUser::getPhone() {
return phone;
}
void
SWGUser::setPhone(QString* phone) {
this->phone = phone;
}
qint32
SWGUser::getUserStatus() {
return userStatus;
}
void
SWGUser::setUserStatus(qint32 userStatus) {
this->userStatus = userStatus;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,55 +1,54 @@
/* /*
* SWGUser.h * SWGUser.h
* *
* *
*/ */
#ifndef SWGUser_H_ #ifndef SWGUser_H_
#define SWGUser_H_ #define SWGUser_H_
#include #include <QJsonObject>
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGUser: public SWGObject { class SWGUser: public SWGObject {
public: public:
SWGUser(); SWGUser();
SWGUser(QString* json); SWGUser(QString* json);
virtual ~SWGUser(); virtual ~SWGUser();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGUser* fromJson(QString &jsonString); SWGUser* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getUsername(); QString* getUsername();
void setUsername(QString* username); void setUsername(QString* username);
QString* getFirstName(); QString* getFirstName();
void setFirstName(QString* firstName); void setFirstName(QString* firstName);
QString* getLastName(); QString* getLastName();
void setLastName(QString* lastName); void setLastName(QString* lastName);
QString* getEmail(); QString* getEmail();
void setEmail(QString* email); void setEmail(QString* email);
QString* getPassword(); QString* getPassword();
void setPassword(QString* password); void setPassword(QString* password);
QString* getPhone(); QString* getPhone();
void setPhone(QString* phone); void setPhone(QString* phone);
qint32 getUserStatus(); qint32 getUserStatus();
void setUserStatus(qint32 userStatus); void setUserStatus(qint32 userStatus);
private: private:
qint64 id; qint64 id;
QString* username; QString* username;
QString* firstName; QString* firstName;
@@ -59,8 +58,8 @@
QString* phone; QString* phone;
qint32 userStatus; qint32 userStatus;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGUser_H_ */ #endif /* SWGUser_H_ */

View File

@@ -2,463 +2,442 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include #include <QJsonArray>
<QJsonArray> #include <QJsonDocument>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGUserApi::SWGUserApi() {} SWGUserApi::SWGUserApi() {}
SWGUserApi::~SWGUserApi() {} SWGUserApi::~SWGUserApi() {}
SWGUserApi::SWGUserApi(QString host, QString basePath) { SWGUserApi::SWGUserApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
} }
void
SWGUserApi::createUser(SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user");
void
SWGUserApi::createUser(SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QString output = body.asJson();
input.request_body.append(output);
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUserCallback);
worker->execute(&input);
}
connect(worker, void
&HttpRequestWorker::on_execution_finished, SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
this, QString msg;
&SWGUserApi::createUserCallback); if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->execute(&input);
}
void
SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
worker->deleteLater(); emit createUserSignal();
}
void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithArray");
emit createUserSignal();
}
void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithArray");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithArrayInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithArrayInputCallback);
worker->execute(&input);
}
void worker->deleteLater();
SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
emit createUsersWithArrayInputSignal();
}
void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
worker->deleteLater();
emit createUsersWithArrayInputSignal();
}
void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input); worker->deleteLater();
}
void
SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
emit createUsersWithListInputSignal();
}
void
SWGUserApi::loginUser(QString* username, QString* password) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/login");
worker->deleteLater();
emit createUsersWithListInputSignal();
}
void if(fullPath.indexOf("?") > 0)
SWGUserApi::loginUser(QString* username fullPath.append("&");
, QString* password) { else
QString fullPath; fullPath.append("?");
fullPath.append(this->host).append(this->basePath).append("/user/login"); fullPath.append(QUrl::toPercentEncoding("username"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(username)));
if(fullPath.indexOf("?") > 0) if(fullPath.indexOf("?") > 0)
fullPath.append("&"); fullPath.append("&");
else else
fullPath.append("?"); fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("username")) fullPath.append(QUrl::toPercentEncoding("password"))
.append("=") .append("=")
.append(QUrl::toPercentEncoding(stringValue(username))); .append(QUrl::toPercentEncoding(stringValue(password)));
if(fullPath.indexOf("?") > 0) HttpRequestWorker *worker = new HttpRequestWorker();
fullPath.append("&"); HttpRequestInput input(fullPath, "GET");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(password)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::loginUserCallback);
worker->execute(&input);
}
void
SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::loginUserCallback);
worker->execute(&input);
}
void
SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
QString* output = static_cast<QString*>(create(json, QString("QString")));
worker->deleteLater();
QString json(worker->response); emit loginUserSignal(output);
QString* output = static_cast<QString*>(create(json,
QString("QString")));
}
void
SWGUserApi::logoutUser() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout");
worker->deleteLater();
emit loginUserSignal(output);
} HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
void
SWGUserApi::logoutUser() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::logoutUserCallback);
worker->execute(&input);
}
void
SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::logoutUserCallback);
worker->execute(&input); emit logoutUserSignal();
} }
void
SWGUserApi::getUserByName(QString* username) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
void
SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
worker->deleteLater();
emit logoutUserSignal(); HttpRequestWorker *worker = new HttpRequestWorker();
} HttpRequestInput input(fullPath, "GET");
void
SWGUserApi::getUserByName(QString* username) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker(); connect(worker,
HttpRequestInput input(fullPath, "GET"); &HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::getUserByNameCallback);
worker->execute(&input);
}
void
SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::getUserByNameCallback);
worker->execute(&input); QString json(worker->response);
} SWGUser* output = static_cast<SWGUser*>(create(json, QString("SWGUser")));
void
SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit getUserByNameSignal(output);
}
void
SWGUserApi::updateUser(QString* username, SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString json(worker->response);
SWGUser* output = static_cast<SWGUser*>(create(json,
QString("SWGUser")));
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
worker->deleteLater();
emit getUserByNameSignal(output); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
}
void
SWGUserApi::updateUser(QString* username
, SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
QString output = body.asJson();
input.request_body.append(output);
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::updateUserCallback);
worker->execute(&input);
}
void
SWGUserApi::updateUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString output = body.asJson();
input.request_body.append(output);
worker->deleteLater();
emit updateUserSignal();
}
void
SWGUserApi::deleteUser(QString* username) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::updateUserCallback);
worker->execute(&input); QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
} fullPath.replace(usernamePathParam, stringValue(username));
void
SWGUserApi::updateUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
emit updateUserSignal();
}
void
SWGUserApi::deleteUser(QString* username) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::deleteUserCallback);
worker->execute(&input);
}
HttpRequestWorker *worker = new HttpRequestWorker(); void
HttpRequestInput input(fullPath, "DELETE"); SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit deleteUserSignal();
}
connect(worker, } /* namespace Swagger */
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::deleteUserCallback);
worker->execute(&input);
}
void
SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
emit deleteUserSignal();
}
} /* namespace Swagger */

View File

@@ -7,15 +7,14 @@
#include <QList> #include <QList>
#include <QString> #include <QString>
#include #include <QObject>
<QObject>
namespace Swagger { namespace Swagger {
class SWGUserApi: public QObject { class SWGUserApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGUserApi(); SWGUserApi();
SWGUserApi(QString host, QString basePath); SWGUserApi(QString host, QString basePath);
~SWGUserApi(); ~SWGUserApi();
@@ -26,15 +25,13 @@
void createUser(SWGUser body); void createUser(SWGUser body);
void createUsersWithArrayInput(QList<SWGUser*>* body); void createUsersWithArrayInput(QList<SWGUser*>* body);
void createUsersWithListInput(QList<SWGUser*>* body); void createUsersWithListInput(QList<SWGUser*>* body);
void loginUser(QString* username void loginUser(QString* username, QString* password);
, QString* password);
void logoutUser(); void logoutUser();
void getUserByName(QString* username); void getUserByName(QString* username);
void updateUser(QString* username void updateUser(QString* username, SWGUser body);
, SWGUser body);
void deleteUser(QString* username); void deleteUser(QString* username);
private: private:
void createUserCallback (HttpRequestWorker * worker); void createUserCallback (HttpRequestWorker * worker);
void createUsersWithArrayInputCallback (HttpRequestWorker * worker); void createUsersWithArrayInputCallback (HttpRequestWorker * worker);
void createUsersWithListInputCallback (HttpRequestWorker * worker); void createUsersWithListInputCallback (HttpRequestWorker * worker);
@@ -44,7 +41,7 @@
void updateUserCallback (HttpRequestWorker * worker); void updateUserCallback (HttpRequestWorker * worker);
void deleteUserCallback (HttpRequestWorker * worker); void deleteUserCallback (HttpRequestWorker * worker);
signals: signals:
void createUserSignal(); void createUserSignal();
void createUsersWithArrayInputSignal(); void createUsersWithArrayInputSignal();
void createUsersWithListInputSignal(); void createUsersWithListInputSignal();
@@ -54,6 +51,6 @@
void updateUserSignal(); void updateUserSignal();
void deleteUserSignal(); void deleteUserSignal();
}; };
} }
#endif #endif

View File

@@ -1,146 +1,143 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-java-client</artifactId> <artifactId>swagger-java-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-java-client</name> <name>swagger-java-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<scm> <scm>
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection> <connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection> <developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
<url>https://github.com/swagger-api/swagger-codegen</url> <url>https://github.com/swagger-api/swagger-codegen</url>
</scm> </scm>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version> <version>2.12</version>
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>loggerPath</name> <name>loggerPath</name>
<value>conf/log4j.properties</value> <value>conf/log4j.properties</value>
</property> </property>
</systemProperties> </systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine> <argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel> <parallel>methods</parallel>
<forkMode>pertest</forkMode> <forkMode>pertest</forkMode>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/main/java</source>
src/main/java</source> </sources>
</sources> </configuration>
</configuration> </execution>
</execution> <execution>
<execution> <id>add_test_sources</id>
<id>add_test_sources</id> <phase>generate-test-sources</phase>
<phase>generate-test-sources</phase> <goals>
<goals> <goal>add-test-source</goal>
<goal>add-test-source</goal> </goals>
</goals> <configuration>
<configuration> <sources>
<sources> <source>src/test/java</source>
<source> </sources>
src/test/java</source> </configuration>
</sources> </execution>
</configuration> </executions>
</execution> </plugin>
</executions> <plugin>
</plugin> <groupId>org.apache.maven.plugins</groupId>
<plugin> <artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>2.3.2</version>
<artifactId>maven-compiler-plugin</artifactId> <configuration>
<version>2.3.2</version> <source>1.6</source>
<configuration> <target>1.6</target>
<source> </configuration>
1.6</source> </plugin>
<target>1.6</target> </plugins>
</configuration> </build>
</plugin> <dependencies>
</plugins> <dependency>
</build> <groupId>io.swagger</groupId>
<dependencies> <artifactId>swagger-annotations</artifactId>
<dependency> <version>${swagger-annotations-version}</version>
<groupId>io.swagger</groupId> </dependency>
<artifactId>swagger-annotations</artifactId> <dependency>
<version>${swagger-annotations-version}</version> <groupId>com.google.code.gson</groupId>
</dependency> <artifactId>gson</artifactId>
<dependency> <version>${gson-version}</version>
<groupId>com.google.code.gson</groupId> <scope>compile</scope>
<artifactId>gson</artifactId> </dependency>
<version>${gson-version}</version> <dependency>
<scope>compile</scope> <groupId>com.squareup.retrofit</groupId>
</dependency> <artifactId>retrofit</artifactId>
<dependency> <version>${retrofit-version}</version>
<groupId>com.squareup.retrofit</groupId> <scope>compile</scope>
<artifactId>retrofit</artifactId> </dependency>
<version>${retrofit-version}</version>
<scope>compile</scope>
</dependency>
<!-- test dependencies --> <!-- test dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${junit-version}</version> <version>${junit-version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<swagger-annotations-version>1.5.0</swagger-annotations-version> <swagger-annotations-version>1.5.0</swagger-annotations-version>
<gson-version>2.3.1</gson-version> <gson-version>2.3.1</gson-version>
<retrofit-version>1.9.0</retrofit-version> <retrofit-version>1.9.0</retrofit-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>
</properties> </properties>
</project> </project>

View File

@@ -6,18 +6,18 @@ import retrofit.RestAdapter;
import retrofit.converter.GsonConverter; import retrofit.converter.GsonConverter;
public class ServiceGenerator { public class ServiceGenerator {
// No need to instantiate this class. // No need to instantiate this class.
private ServiceGenerator() { } private ServiceGenerator() { }
public static <S> S createService(Class<S> serviceClass) { public static <S> S createService(Class<S> serviceClass) {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create(); .create();
RestAdapter adapter = new RestAdapter.Builder() RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://petstore.swagger.io/v2") .setEndpoint("http://petstore.swagger.io/v2")
.setConverter(new GsonConverter(gson)) .setConverter(new GsonConverter(gson))
.build(); .build();
return adapter.create(serviceClass); return adapter.create(serviceClass);
} }
} }

View File

@@ -9,109 +9,109 @@ import java.util.*;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import java.io.File; import java.io.File;
public interface PetApi { public interface PetApi {
/** /**
* Update an existing pet * Update an existing pet
* *
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return Void * @return Void
*/ */
@PUT("/pet") @PUT("/pet")
Void updatePet( Void updatePet(
@Body Pet body @Body Pet body
); );
/** /**
* Add a new pet to the store * Add a new pet to the store
* *
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return Void * @return Void
*/ */
@POST("/pet") @POST("/pet")
Void addPet( Void addPet(
@Body Pet body @Body Pet body
); );
/** /**
* Finds Pets by status * Finds Pets by status
* Multiple status values can be provided with comma seperated strings * Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter * @param status Status values that need to be considered for filter
* @return List<Pet> * @return List<Pet>
*/ */
@GET("/pet/findByStatus") @GET("/pet/findByStatus")
List<Pet> findPetsByStatus( List<Pet> findPetsByStatus(
@Query("status") List<String> status @Query("status") List<String> status
); );
/** /**
* Finds Pets by tags * Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by * @param tags Tags to filter by
* @return List<Pet> * @return List<Pet>
*/ */
@GET("/pet/findByTags") @GET("/pet/findByTags")
List<Pet> findPetsByTags( List<Pet> findPetsByTags(
@Query("tags") List<String> tags @Query("tags") List<String> tags
); );
/** /**
* Find pet by ID * Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions * Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched * @param petId ID of pet that needs to be fetched
* @return Pet * @return Pet
*/ */
@GET("/pet/{petId}") @GET("/pet/{petId}")
Pet getPetById( Pet getPetById(
@Path("petId") Long petId @Path("petId") Long petId
); );
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
* *
* @param petId ID of pet that needs to be updated * @param petId ID of pet that needs to be updated
* @param name Updated name of the pet * @param name Updated name of the pet
* @param status Updated status of the pet * @param status Updated status of the pet
* @return Void * @return Void
*/ */
@FormUrlEncoded @FormUrlEncoded
@POST("/pet/{petId}") @POST("/pet/{petId}")
Void updatePetWithForm( Void updatePetWithForm(
@Path("petId") String petId,@Field("name") String name,@Field("status") String status @Path("petId") String petId,@Field("name") String name,@Field("status") String status
); );
/** /**
* Deletes a pet * Deletes a pet
* *
* @param apiKey * @param apiKey
* @param petId Pet id to delete * @param petId Pet id to delete
* @return Void * @return Void
*/ */
@DELETE("/pet/{petId}") @DELETE("/pet/{petId}")
Void deletePet( Void deletePet(
@Header("api_key") String apiKey,@Path("petId") Long petId @Header("api_key") String apiKey,@Path("petId") Long petId
); );
/** /**
* uploads an image * uploads an image
* *
* @param petId ID of pet to update * @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server * @param additionalMetadata Additional data to pass to server
* @param file file to upload * @param file file to upload
* @return Void * @return Void
*/ */
@Multipart @Multipart
@POST("/pet/{petId}/uploadImage") @POST("/pet/{petId}/uploadImage")
Void uploadFile( Void uploadFile(
@Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file
); );
} }

View File

@@ -9,52 +9,52 @@ import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order; import io.swagger.client.model.Order;
public interface StoreApi { public interface StoreApi {
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
* @return Map<String, Integer> * @return Map<String, Integer>
*/ */
@GET("/store/inventory") @GET("/store/inventory")
Map<String, Integer> getInventory(); Map<String, Integer> getInventory();
/** /**
* Place an order for a pet * Place an order for a pet
* *
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Order * @return Order
*/ */
@POST("/store/order") @POST("/store/order")
Order placeOrder( Order placeOrder(
@Body Order body @Body Order body
); );
/** /**
* Find purchase order by ID * Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions * For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @return Order * @return Order
*/ */
@GET("/store/order/{orderId}") @GET("/store/order/{orderId}")
Order getOrderById( Order getOrderById(
@Path("orderId") String orderId @Path("orderId") String orderId
); );
/** /**
* Delete purchase order by ID * Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * 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 * @param orderId ID of the order that needs to be deleted
* @return Void * @return Void
*/ */
@DELETE("/store/order/{orderId}") @DELETE("/store/order/{orderId}")
Void deleteOrder( Void deleteOrder(
@Path("orderId") String orderId @Path("orderId") String orderId
); );
} }

View File

@@ -9,102 +9,102 @@ import java.util.*;
import io.swagger.client.model.User; import io.swagger.client.model.User;
import java.util.*; import java.util.*;
public interface UserApi { public interface UserApi {
/** /**
* Create user * Create user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* @param body Created user object * @param body Created user object
* @return Void * @return Void
*/ */
@POST("/user") @POST("/user")
Void createUser( Void createUser(
@Body User body @Body User body
); );
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
* @param body List of user object * @param body List of user object
* @return Void * @return Void
*/ */
@POST("/user/createWithArray") @POST("/user/createWithArray")
Void createUsersWithArrayInput( Void createUsersWithArrayInput(
@Body List<User> body @Body List<User> body
); );
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
* @param body List of user object * @param body List of user object
* @return Void * @return Void
*/ */
@POST("/user/createWithList") @POST("/user/createWithList")
Void createUsersWithListInput( Void createUsersWithListInput(
@Body List<User> body @Body List<User> body
); );
/** /**
* Logs user into the system * Logs user into the system
* *
* @param username The user name for login * @param username The user name for login
* @param password The password for login in clear text * @param password The password for login in clear text
* @return String * @return String
*/ */
@GET("/user/login") @GET("/user/login")
String loginUser( String loginUser(
@Query("username") String username,@Query("password") String password @Query("username") String username,@Query("password") String password
); );
/** /**
* Logs out current logged in user session * Logs out current logged in user session
* *
* @return Void * @return Void
*/ */
@GET("/user/logout") @GET("/user/logout")
Void logoutUser(); Void logoutUser();
/** /**
* Get user by user name * Get user by user name
* *
* @param username The name that needs to be fetched. Use user1 for testing. * @param username The name that needs to be fetched. Use user1 for testing.
* @return User * @return User
*/ */
@GET("/user/{username}") @GET("/user/{username}")
User getUserByName( User getUserByName(
@Path("username") String username @Path("username") String username
); );
/** /**
* Updated user * Updated user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* @param username name that need to be deleted * @param username name that need to be deleted
* @param body Updated user object * @param body Updated user object
* @return Void * @return Void
*/ */
@PUT("/user/{username}") @PUT("/user/{username}")
Void updateUser( Void updateUser(
@Path("username") String username,@Body User body @Path("username") String username,@Body User body
); );
/** /**
* Delete user * Delete user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* @param username The name that needs to be deleted * @param username The name that needs to be deleted
* @return Void * @return Void
*/ */
@DELETE("/user/{username}") @DELETE("/user/{username}")
Void deleteUser( Void deleteUser(
@Path("username") String username @Path("username") String username
); );
} }

View File

@@ -5,46 +5,45 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Category { public class Category {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Category {\n"); sb.append("class Category {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -6,106 +6,105 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Order { public class Order {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("petId") @SerializedName("petId")
private Long petId = null; private Long petId = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("quantity") @SerializedName("quantity")
private Integer quantity = null; private Integer quantity = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("shipDate") @SerializedName("shipDate")
private Date shipDate = null; private Date shipDate = null;
public enum StatusEnum { public enum StatusEnum {
placed, approved, delivered, placed, approved, delivered,
}; };
/** /**
* Order Status * Order Status
**/ **/
@ApiModelProperty(value = "Order Status") @ApiModelProperty(value = "Order Status")
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("complete") @SerializedName("complete")
private Boolean complete = null; private Boolean complete = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public Long getPetId() { public Long getPetId() {
return petId; return petId;
} }
public void setPetId(Long petId) { public void setPetId(Long petId) {
this.petId = petId; this.petId = petId;
} }
public Integer getQuantity() { public Integer getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(Integer quantity) { public void setQuantity(Integer quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
public Date getShipDate() { public Date getShipDate() {
return shipDate; return shipDate;
} }
public void setShipDate(Date shipDate) { public void setShipDate(Date shipDate) {
this.shipDate = shipDate; this.shipDate = shipDate;
} }
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
public Boolean getComplete() { public Boolean getComplete() {
return complete; return complete;
} }
public void setComplete(Boolean complete) { public void setComplete(Boolean complete) {
this.complete = complete; this.complete = complete;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Order {\n"); sb.append("class Order {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" petId: ").append(petId).append("\n"); sb.append(" petId: ").append(petId).append("\n");
sb.append(" quantity: ").append(quantity).append("\n"); sb.append(" quantity: ").append(quantity).append("\n");
sb.append(" shipDate: ").append(shipDate).append("\n"); sb.append(" shipDate: ").append(shipDate).append("\n");
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append(" complete: ").append(complete).append("\n"); sb.append(" complete: ").append(complete).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,113 +1,112 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.client.model.Category; import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*; import java.util.*;
import io.swagger.client.model.Tag;
import io.swagger.annotations.*; import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Pet { public class Pet {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("category") @SerializedName("category")
private Category category = null; private Category category = null;
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@SerializedName("photoUrls") @SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>() ; private List<String> photoUrls = new ArrayList<String>() ;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("tags") @SerializedName("tags")
private List<Tag> tags = new ArrayList<Tag>() ; private List<Tag> tags = new ArrayList<Tag>() ;
public enum StatusEnum { public enum StatusEnum {
available, pending, sold, available, pending, sold,
}; };
/** /**
* pet status in the store * pet status in the store
**/ **/
@ApiModelProperty(value = "pet status in the store") @ApiModelProperty(value = "pet status in the store")
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public Category getCategory() { public Category getCategory() {
return category; return category;
} }
public void setCategory(Category category) { public void setCategory(Category category) {
this.category = category; this.category = category;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public List<String> getPhotoUrls() { public List<String> getPhotoUrls() {
return photoUrls; return photoUrls;
} }
public void setPhotoUrls(List<String> photoUrls) { public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls; this.photoUrls = photoUrls;
} }
public List<Tag> getTags() { public List<Tag> getTags() {
return tags; return tags;
} }
public void setTags(List<Tag> tags) { public void setTags(List<Tag> tags) {
this.tags = tags; this.tags = tags;
} }
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n"); sb.append("class Pet {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" category: ").append(category).append("\n"); sb.append(" category: ").append(category).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append(" photoUrls: ").append(photoUrls).append("\n"); sb.append(" photoUrls: ").append(photoUrls).append("\n");
sb.append(" tags: ").append(tags).append("\n"); sb.append(" tags: ").append(tags).append("\n");
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,46 +5,45 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Tag { public class Tag {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n"); sb.append("class Tag {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -5,131 +5,130 @@ import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class User { public class User {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("username") @SerializedName("username")
private String username = null; private String username = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("firstName") @SerializedName("firstName")
private String firstName = null; private String firstName = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("lastName") @SerializedName("lastName")
private String lastName = null; private String lastName = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("email") @SerializedName("email")
private String email = null; private String email = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("password") @SerializedName("password")
private String password = null; private String password = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("phone") @SerializedName("phone")
private String phone = null; private String phone = null;
/** /**
* User Status * User Status
**/ **/
@ApiModelProperty(value = "User Status") @ApiModelProperty(value = "User Status")
@SerializedName("userStatus") @SerializedName("userStatus")
private Integer userStatus = null; private Integer userStatus = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
public Integer getUserStatus() { public Integer getUserStatus() {
return userStatus; return userStatus;
} }
public void setUserStatus(Integer userStatus) { public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus; this.userStatus = userStatus;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class User {\n"); sb.append("class User {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" username: ").append(username).append("\n"); sb.append(" username: ").append(username).append("\n");
sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" firstName: ").append(firstName).append("\n");
sb.append(" lastName: ").append(lastName).append("\n"); sb.append(" lastName: ").append(lastName).append("\n");
sb.append(" email: ").append(email).append("\n"); sb.append(" email: ").append(email).append("\n");
sb.append(" password: ").append(password).append("\n"); sb.append(" password: ").append(password).append("\n");
sb.append(" phone: ").append(phone).append("\n"); sb.append(" phone: ").append(phone).append("\n");
sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append(" userStatus: ").append(userStatus).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -16,8 +16,8 @@ require 'swagger_client/models/order'
# APIs # APIs
require 'swagger_client/api/user_api' require 'swagger_client/api/user_api'
require 'swagger_client/api/pet_api'
require 'swagger_client/api/store_api' require 'swagger_client/api/store_api'
require 'swagger_client/api/pet_api'
module SwaggerClient module SwaggerClient
# Initialize the default configuration # Initialize the default configuration

View File

@@ -190,7 +190,7 @@ module SwaggerClient
post_body = nil post_body = nil
auth_names = ['api_key', 'petstore_auth'] auth_names = ['petstore_auth', 'api_key']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Pet.new() and obj.build_from_hash(response) obj = Pet.new() and obj.build_from_hash(response)
end end

View File

@@ -1,224 +1,221 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-scala-client</artifactId> <artifactId>swagger-scala-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-scala-client</name> <name>swagger-scala-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<prerequisites> <prerequisites>
<maven>2.2.0</maven> <maven>2.2.0</maven>
</prerequisites> </prerequisites>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
<id>maven-mongodb-plugin-repo</id> <id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name> <name>maven mongodb plugin repository</name>
<url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url> <url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout> <layout>default</layout>
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version> <version>2.12</version>
<configuration> <configuration>
<systemProperties> <systemProperties>
<property> <property>
<name>loggerPath</name> <name>loggerPath</name>
<value>conf/log4j.properties</value> <value>conf/log4j.properties</value>
</property> </property>
</systemProperties> </systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine> <argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel> <parallel>methods</parallel>
<forkMode>pertest</forkMode> <forkMode>pertest</forkMode>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/main/java</source>
src/main/java</source> </sources>
</sources> </configuration>
</configuration> </execution>
</execution> <execution>
<execution> <id>add_test_sources</id>
<id>add_test_sources</id> <phase>generate-test-sources</phase>
<phase>generate-test-sources</phase> <goals>
<goals> <goal>add-test-source</goal>
<goal>add-test-source</goal> </goals>
</goals> <configuration>
<configuration> <sources>
<sources> <source>src/test/java</source>
<source> </sources>
src/test/java</source> </configuration>
</sources> </execution>
</configuration> </executions>
</execution> </plugin>
</executions> <plugin>
</plugin> <groupId>org.apache.maven.plugins</groupId>
<plugin> <artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId> <version>2.3.2</version>
<artifactId>maven-compiler-plugin</artifactId> <configuration>
<version>2.3.2</version> <source>1.6</source>
<configuration> <target>1.6</target>
<source> </configuration>
1.6</source> </plugin>
<target>1.6</target> <plugin>
</configuration> <groupId>net.alchim31.maven</groupId>
</plugin> <artifactId>scala-maven-plugin</artifactId>
<plugin> <version>${scala-maven-plugin-version}</version>
<groupId>net.alchim31.maven</groupId> <executions>
<artifactId>scala-maven-plugin</artifactId> <execution>
<version>${scala-maven-plugin-version}</version> <id>scala-compile-first</id>
<executions> <phase>process-resources</phase>
<execution> <goals>
<id>scala-compile-first</id> <goal>add-source</goal>
<phase>process-resources</phase> <goal>compile</goal>
<goals> </goals>
<goal>add-source</goal> </execution>
<goal>compile</goal> <execution>
</goals> <id>scala-test-compile</id>
</execution> <phase>process-test-resources</phase>
<execution> <goals>
<id>scala-test-compile</id> <goal>testCompile</goal>
<phase>process-test-resources</phase> </goals>
<goals> </execution>
<goal>testCompile</goal> </executions>
</goals> <configuration>
</execution> <jvmArgs>
</executions> <jvmArg>-Xms128m</jvmArg>
<configuration> <jvmArg>-Xmx1500m</jvmArg>
<jvmArgs> </jvmArgs>
<jvmArg>-Xms128m</jvmArg> </configuration>
<jvmArg>-Xmx1500m</jvmArg> </plugin>
</jvmArgs> </plugins>
</configuration> </build>
</plugin> <reporting>
</plugins> <plugins>
</build> <plugin>
<reporting> <groupId>org.scala-tools</groupId>
<plugins> <artifactId>maven-scala-plugin</artifactId>
<plugin> <configuration>
<groupId>org.scala-tools</groupId> <scalaVersion>${scala-version}</scalaVersion>
<artifactId>maven-scala-plugin</artifactId> </configuration>
<configuration> </plugin>
<scalaVersion>${scala-version}</scalaVersion> </plugins>
</configuration> </reporting>
</plugin> <dependencies>
</plugins> <dependency>
</reporting> <groupId>com.fasterxml.jackson.module</groupId>
<dependencies> <artifactId>jackson-module-scala_2.10</artifactId>
<dependency> <version>${jackson-version}</version>
<groupId>com.fasterxml.jackson.module</groupId> </dependency>
<artifactId>jackson-module-scala_2.10</artifactId> <dependency>
<version>${jackson-version}</version> <groupId>com.sun.jersey</groupId>
</dependency> <artifactId>jersey-client</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey</groupId> </dependency>
<artifactId>jersey-client</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>com.sun.jersey.contribs</groupId>
</dependency> <artifactId>jersey-multipart</artifactId>
<dependency> <version>${jersey-version}</version>
<groupId>com.sun.jersey.contribs</groupId> </dependency>
<artifactId>jersey-multipart</artifactId> <dependency>
<version>${jersey-version}</version> <groupId>org.jfarcand</groupId>
</dependency> <artifactId>jersey-ahc-client</artifactId>
<dependency> <version>${jersey-async-version}</version>
<groupId>org.jfarcand</groupId> <scope>compile</scope>
<artifactId>jersey-ahc-client</artifactId> </dependency>
<version>${jersey-async-version}</version> <dependency>
<scope>compile</scope> <groupId>org.scala-lang</groupId>
</dependency> <artifactId>scala-library</artifactId>
<dependency> <version>${scala-version}</version>
<groupId>org.scala-lang</groupId> </dependency>
<artifactId>scala-library</artifactId> <dependency>
<version>${scala-version}</version> <groupId>io.swagger</groupId>
</dependency> <artifactId>swagger-core</artifactId>
<dependency> <version>${swagger-core-version}</version>
<groupId>io.swagger</groupId> </dependency>
<artifactId>swagger-core</artifactId> <dependency>
<version>${swagger-core-version}</version> <groupId>org.scalatest</groupId>
</dependency> <artifactId>scalatest_2.10</artifactId>
<dependency> <version>${scala-test-version}</version>
<groupId>org.scalatest</groupId> <scope>test</scope>
<artifactId>scalatest_2.10</artifactId> </dependency>
<version>${scala-test-version}</version> <dependency>
<scope>test</scope> <groupId>junit</groupId>
</dependency> <artifactId>junit</artifactId>
<dependency> <version>${junit-version}</version>
<groupId>junit</groupId> <scope>test</scope>
<artifactId>junit</artifactId> </dependency>
<version>${junit-version}</version> <dependency>
<scope>test</scope> <groupId>joda-time</groupId>
</dependency> <artifactId>joda-time</artifactId>
<dependency> <version>${joda-time-version}</version>
<groupId>joda-time</groupId> </dependency>
<artifactId>joda-time</artifactId> <dependency>
<version>${joda-time-version}</version> <groupId>org.joda</groupId>
</dependency> <artifactId>joda-convert</artifactId>
<dependency> <version>${joda-version}</version>
<groupId>org.joda</groupId> </dependency>
<artifactId>joda-convert</artifactId> </dependencies>
<version>${joda-version}</version> <properties>
</dependency> <scala-version>2.10.4</scala-version>
</dependencies> <joda-version>1.2</joda-version>
<properties> <joda-time-version>2.2</joda-time-version>
<scala-version>2.10.4</scala-version> <jersey-version>1.7</jersey-version>
<joda-version>1.2</joda-version> <swagger-core-version>1.5.0</swagger-core-version>
<joda-time-version>2.2</joda-time-version> <jersey-async-version>1.0.5</jersey-async-version>
<jersey-version>1.7</jersey-version> <maven-plugin.version>1.0.0</maven-plugin.version>
<swagger-core-version>1.5.0</swagger-core-version> <jackson-version>2.4.2</jackson-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.4.2</jackson-version>
<junit-version>4.8.1</junit-version> <junit-version>4.8.1</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version> <scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>2.1.3</scala-test-version> <scala-test-version>2.1.3</scala-test-version>
</properties> </properties>
</project> </project>

View File

@@ -25,179 +25,179 @@ import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil { object ScalaJsonUtil {
def getJsonMapper = { def getJsonMapper = {
val mapper = new ObjectMapper() val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule()) mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule()); mapper.registerModule(new JodaModule());
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper mapper
} }
} }
class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
httpHeaders: HashMap[String, String] = HashMap(), httpHeaders: HashMap[String, String] = HashMap(),
hostMap: HashMap[String, Client] = HashMap(), hostMap: HashMap[String, Client] = HashMap(),
asyncHttpClient: Boolean = false, asyncHttpClient: Boolean = false,
authScheme: String = "", authScheme: String = "",
authPreemptive: Boolean = false) { authPreemptive: Boolean = false) {
var defaultHeaders: HashMap[String, String] = httpHeaders var defaultHeaders: HashMap[String, String] = httpHeaders
def escape(value: String): String = { def escape(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
} }
def escape(value: Long): String = value.toString def escape(value: Long): String = value.toString
def escape(value: Double): String = value.toString def escape(value: Double): String = value.toString
def escape(value: Float): String = value.toString def escape(value: Float): String = value.toString
def deserialize(json: String, containerType: String, cls: Class[_]) = { def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) { if (cls == classOf[String]) {
json match { json match {
case s: String => { case s: String => {
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2)
else s else s
} }
case _ => null case _ => null
} }
} else { } else {
containerType.toLowerCase match { containerType.toLowerCase match {
case "array" => { case "array" => {
val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList response.asScala.toList
} }
case "list" => { case "list" => {
val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList response.asScala.toList
} }
case _ => { case _ => {
json match { json match {
case e: String if ("\"\"" == e) => null case e: String if ("\"\"" == e) => null
case _ => mapper.readValue(json, cls) case _ => mapper.readValue(json, cls)
} }
} }
} }
} }
} }
def serialize(obj: AnyRef): String = { def serialize(obj: AnyRef): String = {
if (obj != null) { if (obj != null) {
obj match { obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj) case _ => mapper.writeValueAsString(obj)
} }
} else null } 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 = { 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 client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") 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) val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2)) headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.map(p => { defaultHeaders.map(p => {
headerParams.contains(p._1) match { headerParams.contains(p._1) match {
case true => // override default with supplied header case true => // override default with supplied header
case false => if (p._2 != null) builder.header(p._1, p._2) case false => if (p._2 != null) builder.header(p._1, p._2)
} }
}) })
var formData: MultivaluedMapImpl = null var formData: MultivaluedMapImpl = null
if(contentType == "application/x-www-form-urlencoded") { if(contentType == "application/x-www-form-urlencoded") {
formData = new MultivaluedMapImpl() formData = new MultivaluedMapImpl()
formParams.map(p => formData.add(p._1, p._2)) formParams.map(p => formData.add(p._1, p._2))
} }
val response: ClientResponse = method match { val response: ClientResponse = method match {
case "GET" => { case "GET" => {
builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse]
} }
case "POST" => { case "POST" => {
if(formData != null) builder.post(classOf[ClientResponse], formData) if(formData != null) builder.post(classOf[ClientResponse], formData)
else if(body != null && body.isInstanceOf[File]) { else if(body != null && body.isInstanceOf[File]) {
val file = body.asInstanceOf[File] val file = body.asInstanceOf[File]
val form = new FormDataMultiPart() val form = new FormDataMultiPart()
form.field("filename", file.getName()) form.field("filename", file.getName())
form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
builder.post(classOf[ClientResponse], form) builder.post(classOf[ClientResponse], form)
} }
else { else {
if(body == null) builder.post(classOf[ClientResponse], serialize(body)) if(body == null) builder.post(classOf[ClientResponse], serialize(body))
else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body))
} }
} }
case "PUT" => { case "PUT" => {
if(formData != null) builder.post(classOf[ClientResponse], formData) if(formData != null) builder.post(classOf[ClientResponse], formData)
else if(body == null) builder.put(classOf[ClientResponse], null) else if(body == null) builder.put(classOf[ClientResponse], null)
else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body))
} }
case "DELETE" => { case "DELETE" => {
builder.delete(classOf[ClientResponse]) builder.delete(classOf[ClientResponse])
} }
case _ => null case _ => null
} }
response.getClientResponseStatus().getStatusCode() match { response.getClientResponseStatus().getStatusCode() match {
case 204 => "" case 204 => ""
case code: Int if (Range(200, 299).contains(code)) => { case code: Int if (Range(200, 299).contains(code)) => {
response.hasEntity() match { response.hasEntity() match {
case true => response.getEntity(classOf[String]) case true => response.getEntity(classOf[String])
case false => "" case false => ""
} }
} }
case _ => { case _ => {
val entity = response.hasEntity() match { val entity = response.hasEntity() match {
case true => response.getEntity(classOf[String]) case true => response.getEntity(classOf[String])
case false => "no data" case false => "no data"
} }
throw new ApiException( throw new ApiException(
response.getClientResponseStatus().getStatusCode(), response.getClientResponseStatus().getStatusCode(),
entity) entity)
} }
} }
} }
def getClient(host: String): Client = { def getClient(host: String): Client = {
hostMap.contains(host) match { hostMap.contains(host) match {
case true => hostMap(host) case true => hostMap(host)
case false => { case false => {
val client = newClient(host) val client = newClient(host)
// client.addFilter(new LoggingFilter()) // client.addFilter(new LoggingFilter())
hostMap += host -> client hostMap += host -> client
client client
} }
} }
} }
def newClient(host: String): Client = asyncHttpClient match { def newClient(host: String): Client = asyncHttpClient match {
case true => { case true => {
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import com.ning.http.client.Realm import com.ning.http.client.Realm
val config: DefaultAhcConfig = new DefaultAhcConfig() val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) { if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config.getAsyncHttpClientConfigBuilder config.getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build) .setUsePreemptiveAuth(authPreemptive).build)
} }
AhcHttpClient.create(config) AhcHttpClient.create(config)
} }
case _ => Client.create() case _ => Client.create()
} }
} }
object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper,
httpHeaders = HashMap(), httpHeaders = HashMap(),
hostMap = HashMap(), hostMap = HashMap(),
asyncHttpClient = false, asyncHttpClient = false,
authScheme = "", authScheme = "",
authPreemptive = false) authPreemptive = false)
class ApiException(val code: Int, msg: String) extends RuntimeException(msg) class ApiException(val code: Int, msg: String) extends RuntimeException(msg)

View File

@@ -15,31 +15,31 @@ import java.util.Date
import scala.collection.mutable.HashMap import scala.collection.mutable.HashMap
class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker) { defApiInvoker: ApiInvoker = ApiInvoker) {
var basePath = defBasePath var basePath = defBasePath
var apiInvoker = defApiInvoker var apiInvoker = defApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
/** /**
* Update an existing pet * Update an existing pet
* *
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return void * @return void
*/ */
def updatePet (body: Pet) = { def updatePet (body: Pet) = {
// create path and map variables // create path and map variables
val path = "/pet".replaceAll("\\{format\\}","json") val path = "/pet".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json", "application/xml", "application/json") val contentTypes = List("application/json", "application/xml", "application/json")
val contentType = contentTypes(0) val contentType = contentTypes(0)
// query params // query params
val queryParams = new HashMap[String, String] val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String] val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String] val formParams = new HashMap[String, String]
@@ -47,388 +47,388 @@ import scala.collection.mutable.HashMap
var postBody: AnyRef = body var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart() val mp = new FormDataMultiPart()
postBody = mp postBody = mp
} }
else { else {
}
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/pet".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json", "application/xml", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
* @return List[Pet]
*/
def findPetsByStatus (status: List[String] /* = available */) : Option[List[Pet]] = {
// create path and map variables
val path = "/pet/findByStatus".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(status) != "null") queryParams += "status" -> status.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
* @return List[Pet]
*/
def findPetsByTags (tags: List[String]) : Option[List[Pet]] = {
// create path and map variables
val path = "/pet/findByTags".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
def getPetById (petId: Long) : Option[Pet] = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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
* @param status Updated status of the pet
* @return void
*/
def updatePetWithForm (petId: String, name: String, status: String) = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/x-www-form-urlencoded", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
mp.field("name", name.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
mp.field("status", status.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
postBody = mp
}
else {
formParams += "name" -> name.toString()
formParams += "status" -> status.toString()
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Deletes a pet
*
* @param apiKey
* @param petId Pet id to delete
* @return void
*/
def deletePet (apiKey: String, petId: Long) = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
headerParams += "api_key" -> apiKey
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return void
*/
def uploadFile (petId: Long, additionalMetadata: String, file: File) = {
// create path and map variables
val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("multipart/form-data", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
mp.field("additionalMetadata", additionalMetadata.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
mp.field("file", file.getName)
mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
postBody = mp
}
else {
formParams += "additionalMetadata" -> additionalMetadata.toString()
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
} }
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/pet".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json", "application/xml", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
* @return List[Pet]
*/
def findPetsByStatus (status: List[String] /* = available */) : Option[List[Pet]] = {
// create path and map variables
val path = "/pet/findByStatus".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(status) != "null") queryParams += "status" -> status.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
* @return List[Pet]
*/
def findPetsByTags (tags: List[String]) : Option[List[Pet]] = {
// create path and map variables
val path = "/pet/findByTags".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
def getPetById (petId: Long) : Option[Pet] = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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
* @param status Updated status of the pet
* @return void
*/
def updatePetWithForm (petId: String, name: String, status: String) = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/x-www-form-urlencoded", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
mp.field("name", name.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
mp.field("status", status.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
postBody = mp
}
else {
formParams += "name" -> name.toString()
formParams += "status" -> status.toString()
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Deletes a pet
*
* @param apiKey
* @param petId Pet id to delete
* @return void
*/
def deletePet (apiKey: String, petId: Long) = {
// create path and map variables
val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
headerParams += "api_key" -> apiKey
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return void
*/
def uploadFile (petId: Long, additionalMetadata: String, file: File) = {
// create path and map variables
val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId))
val contentTypes = List("multipart/form-data", "application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
mp.field("additionalMetadata", additionalMetadata.toString(), MediaType.MULTIPART_FORM_DATA_TYPE)
mp.field("file", file.getName)
mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE))
postBody = mp
}
else {
formParams += "additionalMetadata" -> additionalMetadata.toString()
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -14,30 +14,30 @@ import java.util.Date
import scala.collection.mutable.HashMap import scala.collection.mutable.HashMap
class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker) { defApiInvoker: ApiInvoker = ApiInvoker) {
var basePath = defBasePath var basePath = defBasePath
var apiInvoker = defApiInvoker var apiInvoker = defApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
* @return Map[String, Integer] * @return Map[String, Integer]
*/ */
def getInventory () : Option[Map[String, Integer]] = { def getInventory () : Option[Map[String, Integer]] = {
// create path and map variables // create path and map variables
val path = "/store/inventory".replaceAll("\\{format\\}","json") val path = "/store/inventory".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json") val contentTypes = List("application/json")
val contentType = contentTypes(0) val contentType = contentTypes(0)
// query params // query params
val queryParams = new HashMap[String, String] val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String] val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String] val formParams = new HashMap[String, String]
@@ -45,175 +45,175 @@ import scala.collection.mutable.HashMap
var postBody: AnyRef = null var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart() val mp = new FormDataMultiPart()
postBody = mp postBody = mp
} }
else { else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
*/
def placeOrder (body: Order) : Option[Order] = {
// create path and map variables
val path = "/store/order".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
def getOrderById (orderId: String) : Option[Order] = {
// create path and map variables
val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
} }
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
*/
def placeOrder (body: Order) : Option[Order] = {
// create path and map variables
val path = "/store/order".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
def getOrderById (orderId: String) : Option[Order] = {
// create path and map variables
val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -14,31 +14,31 @@ import java.util.Date
import scala.collection.mutable.HashMap import scala.collection.mutable.HashMap
class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker) { defApiInvoker: ApiInvoker = ApiInvoker) {
var basePath = defBasePath var basePath = defBasePath
var apiInvoker = defApiInvoker var apiInvoker = defApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
/** /**
* Create user * Create user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* @param body Created user object * @param body Created user object
* @return void * @return void
*/ */
def createUser (body: User) = { def createUser (body: User) = {
// create path and map variables // create path and map variables
val path = "/user".replaceAll("\\{format\\}","json") val path = "/user".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json") val contentTypes = List("application/json")
val contentType = contentTypes(0) val contentType = contentTypes(0)
// query params // query params
val queryParams = new HashMap[String, String] val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String] val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String] val formParams = new HashMap[String, String]
@@ -46,367 +46,367 @@ import scala.collection.mutable.HashMap
var postBody: AnyRef = body var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) { if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart() val mp = new FormDataMultiPart()
postBody = mp postBody = mp
} }
else { else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
def createUsersWithArrayInput (body: List[User]) = {
// create path and map variables
val path = "/user/createWithArray".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
def createUsersWithListInput (body: List[User]) = {
// create path and map variables
val path = "/user/createWithList".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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] = {
// create path and map variables
val path = "/user/login".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(username) != "null") queryParams += "username" -> username.toString
if(String.valueOf(password) != "null") queryParams += "password" -> password.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Logs out current logged in user session
*
* @return void
*/
def logoutUser () = {
// create path and map variables
val path = "/user/logout".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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] = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
} }
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
def createUsersWithArrayInput (body: List[User]) = {
// create path and map variables
val path = "/user/createWithArray".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
def createUsersWithListInput (body: List[User]) = {
// create path and map variables
val path = "/user/createWithList".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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] = {
// create path and map variables
val path = "/user/login".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(username) != "null") queryParams += "username" -> username.toString
if(String.valueOf(password) != "null") queryParams += "password" -> password.toString
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Logs out current logged in user session
*
* @return void
*/
def logoutUser () = {
// create path and map variables
val path = "/user/logout".replaceAll("\\{format\\}","json")
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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] = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = body
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* 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) = {
// create path and map variables
val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -3,9 +3,7 @@ package io.swagger.client.model
case class Category (
case class Category ( id: Long,
id: Long, name: String)
name: String)

Some files were not shown because too many files have changed in this diff Show More