Add sample client usage for retrofit2 with rx adapter and java 8

This commit is contained in:
Silvio Heuberger 2016-01-22 14:12:10 +01:00
parent 7dcc1c839e
commit 042dd59a38
26 changed files with 2535 additions and 0 deletions

View File

@ -0,0 +1,43 @@
# swagger-petstore-retrofit2
## Requirements
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
## Installation & Usage
To install the API client library to your local Maven repository, simply execute:
```shell
mvn install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn deploy
```
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*:
```xml
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-petstore-retrofit2</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
```
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue.
## Author
apiteam@swagger.io

View File

@ -0,0 +1,62 @@
group = 'io.swagger'
version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
allprojects {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-retrofit2'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
ext {
okhttp_version = "2.5.0"
oltu_version = "1.0.0"
retrofit_version = "2.0.0-beta2"
gson_version = "2.4"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
rx_java_version = "1.0.15"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "com.squareup.retrofit:converter-gson:$retrofit_version"
compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version"
compile "com.google.code.gson:gson:$gson_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
testCompile "junit:junit:$junit_version"
}

View File

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

View File

@ -0,0 +1 @@
Hello world!

View File

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

View File

@ -0,0 +1 @@
rootProject.name = "swagger-petstore-retrofit2"

View File

@ -0,0 +1,3 @@
<manifest package="io.swagger.client" xmlns:android="http://schemas.android.com/apk/res/android">
<application />
</manifest>

View File

@ -0,0 +1,345 @@
package io.swagger.client;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import retrofit.Converter;
import retrofit.Retrofit;
import retrofit.GsonConverterFactory;
import retrofit.RxJavaCallAdapterFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
import io.swagger.client.auth.OAuth.AccessTokenListener;
import io.swagger.client.auth.OAuthFlow;
public class ApiClient {
private Map<String, Interceptor> apiAuthorizations;
private OkHttpClient okClient;
private Retrofit.Builder adapterBuilder;
public ApiClient() {
apiAuthorizations = new LinkedHashMap<String, Interceptor>();
createDefaultAdapter();
}
public ApiClient(String[] authNames) {
this();
for(String authName : authNames) {
Interceptor auth;
if (authName == "petstore_auth") {
auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets");
} else if (authName == "api_key") {
auth = new ApiKeyAuth("header", "api_key");
} else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);
}
}
/**
* Basic constructor for single auth name
* @param authName
*/
public ApiClient(String authName) {
this(new String[]{authName});
}
/**
* Helper constructor for single api key
* @param authName
* @param apiKey
*/
public ApiClient(String authName, String apiKey) {
this(authName);
this.setApiKey(apiKey);
}
/**
* Helper constructor for single basic auth or password oauth2
* @param authName
* @param username
* @param password
*/
public ApiClient(String authName, String username, String password) {
this(authName);
this.setCredentials(username, password);
}
/**
* Helper constructor for single password oauth2
* @param authName
* @param clientId
* @param secret
* @param username
* @param password
*/
public ApiClient(String authName, String clientId, String secret, String username, String password) {
this(authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret)
.setUsername(username)
.setPassword(password);
}
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create();
okClient = new OkHttpClient();
String baseUrl = "http://petstore.swagger.io/v2";
if(!baseUrl.endsWith("/"))
baseUrl = baseUrl + "/";
adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(gson));
}
public <S> S createService(Class<S> serviceClass) {
return adapterBuilder.build().create(serviceClass);
}
/**
* Helper method to configure the first api key found
* @param apiKey
*/
private void setApiKey(String apiKey) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof ApiKeyAuth) {
ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization;
keyAuth.setApiKey(apiKey);
return;
}
}
}
/**
* Helper method to configure the username/password for basic auth or password oauth
* @param username
* @param password
*/
private void setCredentials(String username, String password) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
}
}
}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return
*/
public TokenRequestBuilder getTokenEndPoint() {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getTokenRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
* @return
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
}
/**
* Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one)
* @param accessToken
*/
public void setAccessToken(String accessToken) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.setAccessToken(accessToken);
return;
}
}
}
/**
* Helper method to configure the oauth accessCode/implicit flow parameters
* @param clientId
* @param clientSecret
* @param redirectURI
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
}
/**
* Adds an authorization to be used by the client
* @param authName
* @param authorization
*/
public void addAuthorization(String authName, Interceptor authorization) {
if (apiAuthorizations.containsKey(authName)) {
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
}
apiAuthorizations.put(authName, authorization);
okClient.interceptors().add(authorization);
}
public Map<String, Interceptor> getApiAuthorizations() {
return apiAuthorizations;
}
public void setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) {
this.apiAuthorizations = apiAuthorizations;
}
public Retrofit.Builder getAdapterBuilder() {
return adapterBuilder;
}
public void setAdapterBuilder(Retrofit.Builder adapterBuilder) {
this.adapterBuilder = adapterBuilder;
}
public OkHttpClient getOkClient() {
return okClient;
}
public void addAuthsToOkClient(OkHttpClient okClient) {
for(Interceptor apiAuthorization : apiAuthorizations.values()) {
okClient.interceptors().add(apiAuthorization);
}
}
/**
* Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit
* @param okClient
*/
public void configureFromOkclient(OkHttpClient okClient) {
OkHttpClient clone = okClient.clone();
addAuthsToOkClient(clone);
adapterBuilder.client(clone);
}
}
/**
* This wrapper is to take care of this case:
* when the deserialization fails due to JsonParseException and the
* expected type is String, then just return the body string.
*/
class GsonResponseBodyConverterToString<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final Type type;
GsonResponseBodyConverterToString(Gson gson, Type type) {
this.gson = gson;
this.type = type;
}
@Override public T convert(ResponseBody value) throws IOException {
String returned = value.string();
try {
return gson.fromJson(returned, type);
}
catch (JsonParseException e) {
return (T) returned;
}
}
}
class GsonCustomConverterFactory extends Converter.Factory
{
public static GsonCustomConverterFactory create(Gson gson) {
return new GsonCustomConverterFactory(gson);
}
private final Gson gson;
private final GsonConverterFactory gsonConverterFactory;
private GsonCustomConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
this.gsonConverterFactory = GsonConverterFactory.create(gson);
}
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
if(type.equals(String.class))
return new GsonResponseBodyConverterToString<Object>(gson, type);
else
return gsonConverterFactory.fromResponseBody(type, annotations);
}
@Override
public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
return gsonConverterFactory.toRequestBody(type, annotations);
}
}

View File

@ -0,0 +1,95 @@
package io.swagger.client;
import java.util.Arrays;
import java.util.List;
public class CollectionFormats {
public static class CSVParams {
protected List<String> params;
public CSVParams() {
}
public CSVParams(List<String> params) {
this.params = params;
}
public CSVParams(String... params) {
this.params = Arrays.asList(params);
}
public List<String> getParams() {
return params;
}
public void setParams(List<String> params) {
this.params = params;
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), ",");
}
}
public static class SSVParams extends CSVParams {
public SSVParams() {
}
public SSVParams(List<String> params) {
super(params);
}
public SSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), " ");
}
}
public static class TSVParams extends CSVParams {
public TSVParams() {
}
public TSVParams(List<String> params) {
super(params);
}
public TSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join( params.toArray(new String[0]), "\t");
}
}
public static class PIPESParams extends CSVParams {
public PIPESParams() {
}
public PIPESParams(List<String> params) {
super(params);
}
public PIPESParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), "|");
}
}
}

View File

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

View File

@ -0,0 +1,155 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import io.swagger.client.model.Pet;
import java.io.File;
import java.util.*;
public interface PetApi {
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return Call<Void>
*/
@PUT("pet")
Observable<Void> updatePet(
@Body Pet body
);
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return Call<Void>
*/
@POST("pet")
Observable<Void> addPet(
@Body Pet body
);
/**
* 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 Call<List<Pet>>
*/
@GET("pet/findByStatus")
Observable<List<Pet>> findPetsByStatus(
@Query("status") List<String> status
);
/**
* 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 Call<List<Pet>>
*/
@GET("pet/findByTags")
Observable<List<Pet>> findPetsByTags(
@Query("tags") List<String> tags
);
/**
* 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 Call<Pet>
*/
@GET("pet/{petId}")
Observable<Pet> getPetById(
@Path("petId") Long petId
);
/**
* 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 Call<Void>
*/
@FormUrlEncoded
@POST("pet/{petId}")
Observable<Void> updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status
);
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
* @return Call<Void>
*/
@DELETE("pet/{petId}")
Observable<Void> deletePet(
@Path("petId") Long petId, @Header("api_key") String apiKey
);
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return Call<Void>
*/
@Multipart
@POST("pet/{petId}/uploadImage")
Observable<Void> uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file
);
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* 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 Call<byte[]>
*/
@GET("pet/{petId}?testing_byte_array=true")
Observable<byte[]> getPetByIdWithByteArray(
@Path("petId") Long petId
);
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return Call<Void>
*/
@POST("pet?testing_byte_array=true")
Observable<Void> addPetUsingByteArray(
@Body byte[] body
);
}

View File

@ -0,0 +1,68 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import java.util.Map;
import io.swagger.client.model.Order;
import java.util.*;
public interface StoreApi {
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Call<Map<String, Integer>>
*/
@GET("store/inventory")
Observable<Map<String, Integer>> getInventory();
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Call<Order>
*/
@POST("store/order")
Observable<Order> placeOrder(
@Body Order body
);
/**
* 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 Call<Order>
*/
@GET("store/order/{orderId}")
Observable<Order> getOrderById(
@Path("orderId") String orderId
);
/**
* 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 Call<Void>
*/
@DELETE("store/order/{orderId}")
Observable<Void> deleteOrder(
@Path("orderId") String orderId
);
}

View File

@ -0,0 +1,122 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import rx.Observable;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
import io.swagger.client.model.User;
import java.util.*;
import java.util.*;
public interface UserApi {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return Call<Void>
*/
@POST("user")
Observable<Void> createUser(
@Body User body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Call<Void>
*/
@POST("user/createWithArray")
Observable<Void> createUsersWithArrayInput(
@Body List<User> body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Call<Void>
*/
@POST("user/createWithList")
Observable<Void> createUsersWithListInput(
@Body List<User> body
);
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return Call<String>
*/
@GET("user/login")
Observable<String> loginUser(
@Query("username") String username, @Query("password") String password
);
/**
* Logs out current logged in user session
*
* @return Call<Void>
*/
@GET("user/logout")
Observable<Void> logoutUser();
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return Call<User>
*/
@GET("user/{username}")
Observable<User> getUserByName(
@Path("username") String username
);
/**
* 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 Call<Void>
*/
@PUT("user/{username}")
Observable<Void> updateUser(
@Path("username") String username, @Body User body
);
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return Call<Void>
*/
@DELETE("user/{username}")
Observable<Void> deleteUser(
@Path("username") String username
);
}

View File

@ -0,0 +1,68 @@
package io.swagger.client.auth;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public class ApiKeyAuth implements Interceptor {
private final String location;
private final String paramName;
private String apiKey;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
String paramValue;
Request request = chain.request();
if (location == "query") {
String newQuery = request.uri().getQuery();
paramValue = paramName + "=" + apiKey;
if (newQuery == null) {
newQuery = paramValue;
} else {
newQuery += "&" + paramValue;
}
URI newUri;
try {
newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(),
request.uri().getPath(), newQuery, request.uri().getFragment());
} catch (URISyntaxException e) {
throw new IOException(e);
}
request = request.newBuilder().url(newUri.toURL()).build();
} else if (location == "header") {
request = request.newBuilder()
.addHeader(paramName, apiKey)
.build();
}
return chain.proceed(request);
}
}

View File

@ -0,0 +1,49 @@
package io.swagger.client.auth;
import java.io.IOException;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
public class HttpBasicAuth implements Interceptor {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setCredentials(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header("Authorization") == null) {
String credentials = Credentials.basic(username, password);
request = request.newBuilder()
.addHeader("Authorization", credentials)
.build();
}
return chain.proceed(request);
}
}

View File

@ -0,0 +1,161 @@
package io.swagger.client.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.io.IOException;
import java.util.Map;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.token.BasicOAuthToken;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.Response;
public class OAuth implements Interceptor {
public interface AccessTokenListener {
public void notify(BasicOAuthToken token);
}
private volatile String accessToken;
private OAuthClient oauthClient;
private TokenRequestBuilder tokenRequestBuilder;
private AuthenticationRequestBuilder authenticationRequestBuilder;
private AccessTokenListener accessTokenListener;
public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) {
this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = requestBuilder;
}
public OAuth(TokenRequestBuilder requestBuilder ) {
this(new OkHttpClient(), requestBuilder);
}
public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes));
setFlow(flow);
authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
}
public void setFlow(OAuthFlow flow) {
switch(flow) {
case accessCode:
case implicit:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
break;
case password:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case application:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
}
@Override
public Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header("Authorization") != null) {
return chain.proceed(request);
}
// If first time, get the token
OAuthClientRequest oAuthRequest;
if (getAccessToken() == null) {
updateAccessToken(null);
}
// Build the request
Builder rb = request.newBuilder();
String requestAccessToken = new String(getAccessToken());
try {
oAuthRequest = new OAuthBearerClientRequest(request.urlString())
.setAccessToken(requestAccessToken)
.buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
for ( Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet() ) {
rb.addHeader(header.getKey(), header.getValue());
}
rb.url( oAuthRequest.getLocationUri());
//Execute the request
Response response = chain.proceed(rb.build());
// 401 most likely indicates that access token has expired.
// Time to refresh and resend the request
if ( response.code() == HTTP_UNAUTHORIZED ) {
updateAccessToken(requestAccessToken);
return intercept( chain );
}
return response;
}
public synchronized void updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage());
setAccessToken(accessTokenResponse.getAccessToken());
if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
} catch (OAuthSystemException e) {
throw new IOException(e);
} catch (OAuthProblemException e) {
throw new IOException(e);
}
}
}
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
this.accessTokenListener = accessTokenListener;
}
public synchronized String getAccessToken() {
return accessToken;
}
public synchronized void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}
public AuthenticationRequestBuilder getAuthenticationRequestBuilder() {
return authenticationRequestBuilder;
}
public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) {
this.authenticationRequestBuilder = authenticationRequestBuilder;
}
}

View File

@ -0,0 +1,5 @@
package io.swagger.client.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
}

View File

@ -0,0 +1,69 @@
package io.swagger.client.auth;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.oltu.oauth2.client.HttpClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
public class OAuthOkHttpClient implements HttpClient {
private OkHttpClient client;
public OAuthOkHttpClient() {
this.client = new OkHttpClient();
}
public OAuthOkHttpClient(OkHttpClient client) {
this.client = client;
}
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
String requestMethod, Class<T> responseClass)
throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if(headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(entry.getValue());
} else {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
requestBuilder.method(requestMethod, body);
try {
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(
response.body().string(),
response.body().contentType().toString(),
response.code(),
responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
}
}
public void shutdown() {
// Nothing to do here
}
}

View File

@ -0,0 +1,85 @@
package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Category {
@SerializedName("id")
private Long id = null;
@SerializedName("name")
private String name = null;
/**
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,174 @@
package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Order {
@SerializedName("id")
private Long id = null;
@SerializedName("petId")
private Long petId = null;
@SerializedName("quantity")
private Integer quantity = null;
@SerializedName("shipDate")
private Date shipDate = null;
public enum StatusEnum {
@SerializedName("placed")
PLACED("placed"),
@SerializedName("approved")
APPROVED("approved"),
@SerializedName("delivered")
DELIVERED("delivered");
private String value;
StatusEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
@SerializedName("status")
private StatusEnum status = null;
@SerializedName("complete")
private Boolean complete = null;
/**
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
@ApiModelProperty(value = "")
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
this.petId = petId;
}
/**
**/
@ApiModelProperty(value = "")
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
/**
**/
@ApiModelProperty(value = "")
public Date getShipDate() {
return shipDate;
}
public void setShipDate(Date shipDate) {
this.shipDate = shipDate;
}
/**
* Order Status
**/
@ApiModelProperty(value = "Order Status")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
/**
**/
@ApiModelProperty(value = "")
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(id, order.id) &&
Objects.equals(petId, order.petId) &&
Objects.equals(quantity, order.quantity) &&
Objects.equals(shipDate, order.shipDate) &&
Objects.equals(status, order.status) &&
Objects.equals(complete, order.complete);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,176 @@
package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Pet {
@SerializedName("id")
private Long id = null;
@SerializedName("category")
private Category category = null;
@SerializedName("name")
private String name = null;
@SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>();
@SerializedName("tags")
private List<Tag> tags = new ArrayList<Tag>();
public enum StatusEnum {
@SerializedName("available")
AVAILABLE("available"),
@SerializedName("pending")
PENDING("pending"),
@SerializedName("sold")
SOLD("sold");
private String value;
StatusEnum(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
@SerializedName("status")
private StatusEnum status = null;
/**
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
@ApiModelProperty(value = "")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
**/
@ApiModelProperty(required = true, value = "")
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
/**
**/
@ApiModelProperty(value = "")
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
/**
* pet status in the store
**/
@ApiModelProperty(value = "pet status in the store")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(id, pet.id) &&
Objects.equals(category, pet.category) &&
Objects.equals(name, pet.name) &&
Objects.equals(photoUrls, pet.photoUrls) &&
Objects.equals(tags, pet.tags) &&
Objects.equals(status, pet.status);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,85 @@
package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Tag {
@SerializedName("id")
private Long id = null;
@SerializedName("name")
private String name = null;
/**
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,182 @@
package io.swagger.client.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class User {
@SerializedName("id")
private Long id = null;
@SerializedName("username")
private String username = null;
@SerializedName("firstName")
private String firstName = null;
@SerializedName("lastName")
private String lastName = null;
@SerializedName("email")
private String email = null;
@SerializedName("password")
private String password = null;
@SerializedName("phone")
private String phone = null;
@SerializedName("userStatus")
private Integer userStatus = null;
/**
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
@ApiModelProperty(value = "")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
/**
**/
@ApiModelProperty(value = "")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
**/
@ApiModelProperty(value = "")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
**/
@ApiModelProperty(value = "")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/**
**/
@ApiModelProperty(value = "")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
**/
@ApiModelProperty(value = "")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
/**
* User Status
**/
@ApiModelProperty(value = "User Status")
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id) &&
Objects.equals(username, user.username) &&
Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) &&
Objects.equals(email, user.email) &&
Objects.equals(password, user.password) &&
Objects.equals(phone, user.phone) &&
Objects.equals(userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,214 @@
package io.swagger.petstore.test;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.*;
import rx.Notification;
import rx.Observable;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import rx.Subscriber;
import rx.functions.Action1;
import rx.observers.TestSubscriber;
import static org.junit.Assert.*;
public class PetApiTest {
PetApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(PetApi.class);
}
@Test
public void testCreateAndGetPet() throws Exception {
final Pet pet = createRandomPet();
api.addPet(pet).subscribe(aVoid -> {
api.getPetById(pet.getId()).subscribe(fetched -> {
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
});
});
}
@Test
public void testUpdatePet() throws Exception {
final Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet).subscribe(aVoid -> {
api.getPetById(pet.getId()).subscribe(fetched -> {
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
});
});
}
@Test
public void testFindPetsByStatus() throws Exception {
final Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
api.updatePet(pet).subscribe(aVoid -> {
api.findPetsByStatus(Arrays.asList(new String[]{"available"})).subscribe(pets -> {
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
});
});
}
@Test
public void testFindPetsByTags() throws Exception {
final Pet pet = createRandomPet();
pet.setName("monster");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<Tag> tags = new ArrayList<Tag>();
Tag tag1 = new Tag();
tag1.setName("friendly");
tags.add(tag1);
pet.setTags(tags);
api.updatePet(pet).subscribe(aVoid -> {
api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).subscribe(pets -> {
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
});
});
}
@Test
public void testUpdatePetWithForm() throws Exception {
final Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet).subscribe(aVoid1 -> {
api.getPetById(pet.getId()).subscribe(fetched -> {
api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null)
.subscribe(aVoid -> {
api.getPetById(fetched.getId()).subscribe(updated -> {
assertEquals(updated.getName(), "furt");
});
});
});
});
}
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet).subscribe(aVoid -> {
});
api.getPetById(pet.getId()).subscribe(fetched -> {
api.deletePet(fetched.getId(), null).subscribe(aVoid -> {
api.getPetById(fetched.getId()).subscribe(
deletedPet -> {
fail("Should not have found deleted pet.");
},
exception -> {
// expected, because the pet has been deleted.
});
});
});
}
@Test
public void testUploadFile() throws Exception {
File file = File.createTempFile("test", "hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
Pet pet = createRandomPet();
api.addPet(pet).subscribe(aVoid -> {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), file);
api.uploadFile(pet.getId(), "a test file", body).subscribe(
aVoid1 -> {
// intentionally left blank.
},
error -> {
// this also yields a 400 for other tests, so I guess it's okay...
});
});
}
@Test
public void testEqualsAndHashCode() {
Pet pet1 = new Pet();
Pet pet2 = new Pet();
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
pet2.setName("really-happy");
pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertFalse(pet1.equals(pet2));
assertFalse(pet2.equals(pet1));
assertFalse(pet1.hashCode() == (pet2.hashCode()));
assertTrue(pet2.equals(pet2));
assertTrue(pet2.hashCode() == pet2.hashCode());
pet1.setName("really-happy");
pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}));
assertTrue(pet1.equals(pet2));
assertTrue(pet2.equals(pet1));
assertTrue(pet1.hashCode() == pet2.hashCode());
assertTrue(pet1.equals(pet1));
assertTrue(pet1.hashCode() == pet1.hashCode());
}
private Pet createRandomPet() {
Pet pet = new Pet();
pet.setId(System.currentTimeMillis());
pet.setName("gorilla");
Category category = new Category();
category.setName("really-happy");
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.AVAILABLE);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"});
pet.setPhotoUrls(photos);
return pet;
}
}

View File

@ -0,0 +1,71 @@
package io.swagger.petstore.test;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import java.util.Map;
import org.junit.*;
import retrofit.Response;
import static org.junit.Assert.*;
public class StoreApiTest {
StoreApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(StoreApi.class);
}
@Test
public void testGetInventory() throws Exception {
api.getInventory().subscribe(inventory -> {
assertTrue(inventory.keySet().size() > 0);
});
}
@Test
public void testPlaceOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order).subscribe(placed -> {});
api.getOrderById(String.valueOf(order.getId())).subscribe(fetched -> {
assertEquals(order.getId(), fetched.getId());
assertEquals(order.getPetId(), fetched.getPetId());
assertEquals(order.getQuantity(), fetched.getQuantity());
});
}
@Test
public void testDeleteOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order).subscribe(order1 -> {
});
api.getOrderById(String.valueOf(order.getId())).subscribe(fetched -> {
assertEquals(fetched.getId(), order.getId());
});
api.deleteOrder(String.valueOf(order.getId())).subscribe(aVoid -> {
});
api.getOrderById(String.valueOf(order.getId())).subscribe(
order1 -> {
throw new RuntimeException("Should not have found deleted order.");
},
error -> {}
);
}
private Order createOrder() {
Order order = new Order();
order.setId(new Long(System.currentTimeMillis()));
order.setPetId(new Long(200));
order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date());
order.setStatus(Order.StatusEnum.PLACED);
order.setComplete(true);
return order;
}
}

View File

@ -0,0 +1,88 @@
package io.swagger.petstore.test;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*;
import io.swagger.client.model.*;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
public class UserApiTest {
UserApi api = null;
@Before
public void setup() {
api = new ApiClient().createService(UserApi.class);
}
@Test
public void testCreateUser() throws Exception {
User user = createUser();
api.createUser(user).subscribe(aVoid -> {
api.getUserByName(user.getUsername()).subscribe(fetched -> {
assertEquals(user.getId(), fetched.getId());
});
});
}
@Test
public void testCreateUsersWithArray() throws Exception {
User user1 = createUser();
user1.setUsername("abc123");
User user2 = createUser();
user2.setUsername("123abc");
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).subscribe(aVoid -> {});
api.getUserByName(user1.getUsername()).subscribe(fetched -> {
assertEquals(user1.getId(), fetched.getId());
});
}
@Test
public void testCreateUsersWithList() throws Exception {
User user1 = createUser();
user1.setUsername("abc123");
User user2 = createUser();
user2.setUsername("123abc");
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).subscribe(aVoid -> {});
api.getUserByName(user1.getUsername()).subscribe(fetched -> {
assertEquals(user1.getId(), fetched.getId());
});
}
@Test
public void testLoginUser() throws Exception {
User user = createUser();
api.createUser(user);
api.loginUser(user.getUsername(), user.getPassword()).subscribe(token -> {
assertTrue(token.startsWith("logged in user session:"));
});
}
@Test
public void logoutUser() throws Exception {
api.logoutUser();
}
private User createUser() {
User user = new User();
user.setId(System.currentTimeMillis());
user.setUsername("fred");
user.setFirstName("Fred");
user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com");
user.setPassword("xxXXxx");
user.setPhone("408-867-5309");
user.setUserStatus(123);
return user;
}
}