Merge branch 'master' into java-datetime-format

This commit is contained in:
xhh 2015-11-12 17:10:08 +08:00
commit 6b3fc79dec
64 changed files with 3814 additions and 145 deletions

View File

@ -6,7 +6,7 @@
## Overview ## Overview
This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server.
Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more.
# Table of contents # Table of contents
@ -63,7 +63,7 @@ You need the following installed and available in your $PATH:
* [Java 7](http://java.oracle.com) * [Java 7](http://java.oracle.com)
* [Apache maven 3.0.3 or greater](http://maven.apache.org/) * [Apache maven 3.0.3 or greater](http://maven.apache.org/)
#### OS X Users #### OS X Users
Don't forget to install Java 7. You probably have 1.6 or 1.8. Don't forget to install Java 7. You probably have 1.6 or 1.8.
@ -173,10 +173,10 @@ OPTIONS
-v, --verbose -v, --verbose
verbose mode verbose mode
-s , --skip-overwrite -s , --skip-overwrite
specifies if the existing files should be overwritten during specifies if the existing files should be overwritten during
the generation the generation
``` ```
You can then compile and run the client, as well as unit tests against it: You can then compile and run the client, as well as unit tests against it:
@ -351,6 +351,7 @@ CONFIG OPTIONS
jersey2 - HTTP client: Jersey client 2.6 jersey2 - HTTP client: Jersey client 2.6
okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1
retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)
retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)
``` ```
Your config file for java can look like Your config file for java can look like

View File

@ -27,6 +27,7 @@ cd $APP_DIR
./bin/java-petstore-jersey2.sh ./bin/java-petstore-jersey2.sh
./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-okhttp-gson.sh
./bin/java-petstore-retrofit.sh ./bin/java-petstore-retrofit.sh
+./bin/java-petstore-retrofit2.sh
./bin/jaxrs-petstore-server.sh ./bin/jaxrs-petstore-server.sh
./bin/nodejs-petstore-server.sh ./bin/nodejs-petstore-server.sh
./bin/objc-petstore.sh ./bin/objc-petstore.sh

View File

@ -0,0 +1,4 @@
{
"library": "retrofit2",
"artifactId": "swagger-petstore-retrofit2"
}

31
bin/java-petstore-retrofit2.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2"
java $JAVA_OPTS -jar $executable $ags

View File

@ -100,6 +100,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY); library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries); library.setEnum(supportedLibraries);
@ -217,7 +218,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java"));
if (!"retrofit".equals(getLibrary())) { if (!("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
@ -231,7 +232,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
// "build.sbt" is for development with SBT // "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
} else if ("retrofit".equals(getLibrary())) { } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
} else { } else {
@ -496,7 +497,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
allowableValues.put("enumVars", enumVars); allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE // handle default value for enum, e.g. available => StatusEnum.AVAILABLE
if (var.defaultValue != null && !"null".equals(var.defaultValue)) { if (var.defaultValue != null) {
String enumName = null; String enumName = null;
for (Map<String, String> enumVar : enumVars) { for (Map<String, String> enumVar : enumVars) {
if (var.defaultValue.equals(enumVar.get("value"))) { if (var.defaultValue.equals(enumVar.get("value"))) {
@ -504,10 +505,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
break; break;
} }
} }
if (enumName == null) { if (enumName != null) {
throw new RuntimeException("default value of property \"" + var.baseName + "\" is not in allowed values: " + var.defaultValue); var.defaultValue = var.datatypeWithEnum + "." + enumName;
} }
var.defaultValue = var.datatypeWithEnum + "." + enumName;
} }
} }
} }
@ -515,7 +515,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if("retrofit".equals(getLibrary())) { if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations"); Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) { if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
@ -531,6 +531,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
if (operation.returnType == null) { if (operation.returnType == null) {
operation.returnType = "Void"; operation.returnType = "Void";
} }
if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/"))
operation.path = operation.path.substring(1);
} }
} }
} }

View File

@ -1,6 +1,7 @@
package {{invokerPackage}}.auth; package {{invokerPackage}}.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@ -85,42 +86,55 @@ public class OAuth implements Interceptor {
updateAccessToken(null); updateAccessToken(null);
} }
// Build the request if (getAccessToken() != null) {
Builder rb = request.newBuilder(); // Build the request
Builder rb = request.newBuilder();
String requestAccessToken = new String(getAccessToken());
try { String requestAccessToken = new String(getAccessToken());
oAuthRequest = new OAuthBearerClientRequest(request.urlString()) try {
.setAccessToken(requestAccessToken) oAuthRequest = new OAuthBearerClientRequest(request.urlString())
.buildHeaderMessage(); .setAccessToken(requestAccessToken)
} catch (OAuthSystemException e) { .buildHeaderMessage();
throw new IOException(e); } 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 != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) {
if (updateAccessToken(requestAccessToken)) {
return intercept( chain );
}
}
return response;
} else {
return chain.proceed(chain.request());
} }
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 { /*
* Returns true if the access token has been updated
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try { try {
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage());
setAccessToken(accessTokenResponse.getAccessToken()); if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
if (accessTokenListener != null) { setAccessToken(accessTokenResponse.getAccessToken());
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); if (accessTokenListener != null) {
accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
return getAccessToken().equals(requestAccessToken);
} else {
return false;
} }
} catch (OAuthSystemException e) { } catch (OAuthSystemException e) {
throw new IOException(e); throw new IOException(e);
@ -128,6 +142,7 @@ public class OAuth implements Interceptor {
throw new IOException(e); throw new IOException(e);
} }
} }
return true;
} }
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {

View File

@ -0,0 +1,343 @@
package {{invokerPackage}};
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 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 {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
import {{invokerPackage}}.auth.OAuth.AccessTokenListener;
import {{invokerPackage}}.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) { {{#hasAuthMethods}}
Interceptor auth;
{{#authMethods}}if (authName == "{{name}}") { {{#isBasic}}
auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}}
} else {{/authMethods}}{
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}}
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}}
}
}
/**
* 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 = "{{basePath}}";
if(!baseUrl.endsWith("/"))
baseUrl = baseUrl + "/";
adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
.client(okClient)
.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 {{invokerPackage}};
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,34 @@
package {{package}};
import {{invokerPackage}}.CollectionFormats.*;
import retrofit.Call;
import retrofit.http.*;
import com.squareup.okhttp.RequestBody;
{{#imports}}import {{import}};
{{/imports}}
{{^fullJavaUtil}}
import java.util.*;
{{/fullJavaUtil}}
{{#operations}}
public interface {{classname}} {
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>
*/
{{#formParams}}{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{path}}")
Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{nickname}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,68 @@
package {{invokerPackage}}.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 {{invokerPackage}}.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 {{invokerPackage}}.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,69 @@
package {{invokerPackage}}.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 @@
{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -0,0 +1,106 @@
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
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"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile 'com.google.code.gson:gson:$gson_version'
compile 'com.squareup.retrofit:converter-gson:$retrofit_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 @@
{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}\"") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}}

View File

@ -0,0 +1 @@
{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}}

View File

@ -0,0 +1,58 @@
package {{package}};
import {{invokerPackage}}.StringUtil;
{{#imports}}import {{import}};
{{/imports}}
import com.google.gson.annotations.SerializedName;
{{#serializableModel}}
import java.io.Serializable;{{/serializableModel}}
import io.swagger.annotations.*;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}}
{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}}
@SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/vars}}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n");
{{/vars}}sb.append("}");
return sb.toString();
}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1 @@
{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}

View File

@ -0,0 +1,158 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<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.6</source>
<target>1.6</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>
<!-- 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>
<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 @@
{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}}

View File

@ -1 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} {{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -33,7 +33,11 @@ namespace {{package}} {
} }
{{#operation}} {{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}*/
public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> {
const path = this.basePath + '{{path}}'{{#pathParams}} const path = this.basePath + '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}};

View File

@ -18,7 +18,7 @@ namespace {{package}} {
* {{{description}}} * {{{description}}}
*/ */
{{/description}} {{/description}}
{{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}} {{/vars}}
} }

View File

@ -167,7 +167,11 @@ export class {{classname}} {
return <T1&T2>objA; return <T1&T2>objA;
} }
{{#operation}} {{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}*/
public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> {
const path = this.url + this.basePath + '{{path}}'{{#pathParams}} const path = this.url + this.basePath + '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}};

13
pom.xml
View File

@ -353,6 +353,18 @@
<module>samples/client/petstore/java/retrofit</module> <module>samples/client/petstore/java/retrofit</module>
</modules> </modules>
</profile> </profile>
<profile>
<id>java-client-retrofit2</id>
<activation>
<property>
<name>env</name>
<value>java</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/java/retrofit2</module>
</modules>
</profile>
<profile> <profile>
<id>scala-client</id> <id>scala-client</id>
<activation> <activation>
@ -427,6 +439,7 @@
<module>samples/client/petstore/java/jersey2</module> <module>samples/client/petstore/java/jersey2</module>
<module>samples/client/petstore/java/okhttp-gson</module> <module>samples/client/petstore/java/okhttp-gson</module>
<module>samples/client/petstore/java/retrofit</module> <module>samples/client/petstore/java/retrofit</module>
<module>samples/client/petstore/java/retrofit2</module>
<module>samples/client/petstore/scala</module> <module>samples/client/petstore/scala</module>
<module>samples/server/petstore/spring-mvc</module> <module>samples/server/petstore/spring-mvc</module>
<!--module>samples/client/petstore/objc</module--> <!--module>samples/client/petstore/objc</module-->

View File

@ -73,7 +73,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(System.currentTimeMillis());
user.setUsername("fred"); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com"); user.setEmail("fred@fredmeyer.com");

View File

@ -73,7 +73,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(System.currentTimeMillis());
user.setUsername("fred"); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com"); user.setEmail("fred@fredmeyer.com");

View File

@ -73,7 +73,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(System.currentTimeMillis());
user.setUsername("fred"); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com"); user.setEmail("fred@fredmeyer.com");

View File

@ -71,7 +71,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(System.currentTimeMillis());
user.setUsername("fred"); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");
user.setEmail("fred@fredmeyer.com"); user.setEmail("fred@fredmeyer.com");

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -0,0 +1,106 @@
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()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
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"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile 'com.google.code.gson:gson:$gson_version'
compile 'com.squareup.retrofit:converter-gson:$retrofit_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,158 @@
<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.6</source>
<target>1.6</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>
<!-- 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>
<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,342 @@
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 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)
.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,51 @@
package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-10T12:25:26.227+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();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
public static String toIndentedString(Object o) {
if (o == null) return "null";
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,127 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import retrofit.Call;
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")
Call<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")
Call<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")
Call<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")
Call<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}")
Call<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}")
Call<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}")
Call<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")
Call<Void> uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file
);
}

View File

@ -0,0 +1,66 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import retrofit.Call;
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")
Call<Map<String, Integer>> getInventory();
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Call<Order>
*/
@POST("store/order")
Call<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}")
Call<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}")
Call<Void> deleteOrder(
@Path("orderId") String orderId
);
}

View File

@ -0,0 +1,120 @@
package io.swagger.client.api;
import io.swagger.client.CollectionFormats.*;
import retrofit.Call;
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")
Call<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")
Call<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")
Call<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")
Call<String> loginUser(
@Query("username") String username, @Query("password") String password
);
/**
* Logs out current logged in user session
*
* @return Call<Void>
*/
@GET("user/logout")
Call<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}")
Call<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}")
Call<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}")
Call<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,57 @@
package io.swagger.client.model;
import io.swagger.client.StringUtil;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.*;
@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 String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,142 @@
package io.swagger.client.model;
import io.swagger.client.StringUtil;
import java.util.Date;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.*;
@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 String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n");
sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,144 @@
package io.swagger.client.model;
import io.swagger.client.StringUtil;
import io.swagger.client.model.Category;
import java.util.*;
import io.swagger.client.model.Tag;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.*;
@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 String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n");
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n");
sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,57 @@
package io.swagger.client.model;
import io.swagger.client.StringUtil;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.*;
@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 String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,148 @@
package io.swagger.client.model;
import io.swagger.client.StringUtil;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.*;
@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 String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n");
sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n");
sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
}

View File

@ -0,0 +1,160 @@
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.*;
import retrofit.Response;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
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 {
Pet pet = createRandomPet();
Response<Void> rp2 = api.addPet(pet).execute();
Response<Pet> rp = api.getPetById(pet.getId()).execute();
Pet fetched = rp.body();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet).execute();
Pet fetched = api.getPetById(pet.getId()).execute().body();
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testFindPetsByStatus() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.AVAILABLE);
api.updatePet(pet).execute();
List<Pet> pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})).execute().body();
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 {
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).execute();
List<Pet> pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).execute().body();
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 {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet).execute();
Pet fetched = api.getPetById(pet.getId()).execute().body();
api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null).execute();
Pet updated = api.getPetById(fetched.getId()).execute().body();
assertEquals(updated.getName(), "furt");
}
@Test
public void testDeletePet() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet).execute();
Pet fetched = api.getPetById(pet.getId()).execute().body();
api.deletePet(fetched.getId(), null).execute();
assertFalse(api.getPetById(fetched.getId()).execute().isSuccess());
}
@Test
public void testUploadFile() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet).execute();
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", RequestBody.create(MediaType.parse("text/plain"), file)).execute();
}
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,64 @@
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 {
Map<String, Integer> inventory = api.getInventory().execute().body();
assertTrue(inventory.keySet().size() > 0);
}
@Test
public void testPlaceOrder() throws Exception {
Order order = createOrder();
api.placeOrder(order).execute();
Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body();
assertEquals(order.getId(), fetched.getId());
assertEquals(order.getPetId(), fetched.getPetId());
assertEquals(order.getQuantity(), fetched.getQuantity());
}
@Test
public void testDeleteOrder() throws Exception {
Order order = createOrder();
Response<Order> aa = api.placeOrder(order).execute();
Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body();
assertEquals(fetched.getId(), order.getId());
api.deleteOrder(String.valueOf(order.getId())).execute();
api.getOrderById(String.valueOf(order.getId())).execute();
//also in retrofit 1 should return an error but don't, check server api impl.
}
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,84 @@
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).execute();
User fetched = api.getUserByName(user.getUsername()).execute().body();
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})).execute();
User fetched = api.getUserByName(user1.getUsername()).execute().body();
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})).execute();
User fetched = api.getUserByName(user1.getUsername()).execute().body();
assertEquals(user1.getId(), fetched.getId());
}
@Test
public void testLoginUser() throws Exception {
User user = createUser();
api.createUser(user).execute();
String token = api.loginUser(user.getUsername(), user.getPassword()).execute().body();
assertTrue(token.startsWith("logged in user session:"));
}
@Test
public void logoutUser() throws Exception {
api.logoutUser().execute();
}
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;
}
}

View File

@ -11,21 +11,41 @@ import scala.collection.JavaConverters._
import scala.beans.BeanProperty import scala.beans.BeanProperty
@RunWith(classOf[JUnitRunner]) @RunWith(classOf[JUnitRunner])
class UserApiTest extends FlatSpec with Matchers { class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll {
behavior of "UserApi" behavior of "UserApi"
val api = new UserApi val api = new UserApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key" api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
// preparation before running a test
override def beforeAll() {
val user = User(
11222,
"scala-test-username",
"scala-test-first",
"scala-test-last",
"scala_test@fail.com",
"SCALATEST",
"408-867-5309",
1)
api.createUser(user)
}
// cleanup after running a test
override def afterAll() {
api.deleteUser("scala-test-username")
}
it should "fetch a user" in { it should "fetch a user" in {
api.getUserByName("user1") match { api.getUserByName("scala-test-username") match {
case Some(user) => { case Some(user) => {
user.id should be(1) user.id should be(11222)
user.username should be("user1") user.username should be("scala-test-username")
user.password should be("XXXXXXXXXXX") user.password should be("SCALATEST")
user.email should be("email1@test.com") user.email should be("scala_test@fail.com")
user.firstName should be("first name 1") user.firstName should be("scala-test-first")
user.lastName should be("last name 1") user.lastName should be("scala-test-last")
user.phone should be("123-456-7890") user.phone should be("408-867-5309")
user.userStatus should be(1) user.userStatus should be(1)
} }
case None => case None =>
@ -33,7 +53,7 @@ class UserApiTest extends FlatSpec with Matchers {
} }
it should "authenticate a user" in { it should "authenticate a user" in {
api.loginUser("user1", "XXXXXXXXXXX") match { api.loginUser("scala-test-username", "SCALATEST") match {
case Some(status) => status.startsWith("logged in user session") match { case Some(status) => status.startsWith("logged in user session") match {
case true => // success! case true => // success!
case _ => fail("didn't get expected message " + status) case _ => fail("didn't get expected message " + status)
@ -46,28 +66,6 @@ class UserApiTest extends FlatSpec with Matchers {
api.logoutUser api.logoutUser
} }
it should "create a user" in {
val user = User(
1002,
"johnny",
"Johnny",
"Rocket",
"johnny@fail.com",
"XXXXXXXXXXX",
"408-867-5309",
1)
api.createUser(user)
api.getUserByName("johnny") match {
case Some(user) => {
user.id should be(1002)
user.username should be("johnny")
}
case None =>
}
}
it should "create 2 users" in { it should "create 2 users" in {
val userArray = (for (i <- (1 to 2)) yield { val userArray = (for (i <- (1 to 2)) yield {
User( User(
@ -149,4 +147,4 @@ class UserApiTest extends FlatSpec with Matchers {
case None => case None =>
} }
} }
} }

View File

@ -5,9 +5,9 @@ namespace API.Client {
export interface Category { export interface Category {
id: number; id?: number;
name: string; name?: string;
} }
} }

View File

@ -5,20 +5,20 @@ namespace API.Client {
export interface Order { export interface Order {
id: number; id?: number;
petId: number; petId?: number;
quantity: number; quantity?: number;
shipDate: Date; shipDate?: Date;
/** /**
* Order Status * Order Status
*/ */
status: Order.StatusEnum; status?: Order.StatusEnum;
complete: boolean; complete?: boolean;
} }
export namespace Order { export namespace Order {

View File

@ -5,20 +5,20 @@ namespace API.Client {
export interface Pet { export interface Pet {
id: number; id?: number;
category: Category; category?: Category;
name: string; name: string;
photoUrls: Array<string>; photoUrls: Array<string>;
tags: Array<Tag>; tags?: Array<Tag>;
/** /**
* pet status in the store * pet status in the store
*/ */
status: Pet.StatusEnum; status?: Pet.StatusEnum;
} }
export namespace Pet { export namespace Pet {

View File

@ -26,7 +26,11 @@ namespace API.Client {
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/pet'; const path = this.basePath + '/pet';
@ -49,7 +53,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/pet'; const path = this.basePath + '/pet';
@ -72,7 +80,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public findPetsByStatus (status?: Array<string>, extraHttpRequestParams?: any ) : ng.IHttpPromise<Array<Pet>> { public findPetsByStatus (status?: Array<string>, extraHttpRequestParams?: any ) : ng.IHttpPromise<Array<Pet>> {
const path = this.basePath + '/pet/findByStatus'; const path = this.basePath + '/pet/findByStatus';
@ -98,7 +110,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public findPetsByTags (tags?: Array<string>, extraHttpRequestParams?: any ) : ng.IHttpPromise<Array<Pet>> { public findPetsByTags (tags?: Array<string>, extraHttpRequestParams?: any ) : ng.IHttpPromise<Array<Pet>> {
const path = this.basePath + '/pet/findByTags'; const path = this.basePath + '/pet/findByTags';
@ -124,7 +140,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<Pet> { public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<Pet> {
const path = this.basePath + '/pet/{petId}' const path = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -151,7 +171,13 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/pet/{petId}' const path = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -187,7 +213,12 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/pet/{petId}' const path = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -216,7 +247,13 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/pet/{petId}/uploadImage' const path = this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));

View File

@ -26,7 +26,10 @@ namespace API.Client {
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> {
const path = this.basePath + '/store/inventory'; const path = this.basePath + '/store/inventory';
@ -48,7 +51,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise<Order> { public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise<Order> {
const path = this.basePath + '/store/order'; const path = this.basePath + '/store/order';
@ -71,7 +78,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<Order> { public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<Order> {
const path = this.basePath + '/store/order/{orderId}' const path = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId)); .replace('{' + 'orderId' + '}', String(orderId));
@ -98,7 +109,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/store/order/{orderId}' const path = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId)); .replace('{' + 'orderId' + '}', String(orderId));

View File

@ -5,9 +5,9 @@ namespace API.Client {
export interface Tag { export interface Tag {
id: number; id?: number;
name: string; name?: string;
} }
} }

View File

@ -5,24 +5,24 @@ namespace API.Client {
export interface User { export interface User {
id: number; id?: number;
username: string; username?: string;
firstName: string; firstName?: string;
lastName: string; lastName?: string;
email: string; email?: string;
password: string; password?: string;
phone: string; phone?: string;
/** /**
* User Status * User Status
*/ */
userStatus: number; userStatus?: number;
} }
} }

View File

@ -26,7 +26,11 @@ namespace API.Client {
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user'; const path = this.basePath + '/user';
@ -49,7 +53,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (body?: Array<User>, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public createUsersWithArrayInput (body?: Array<User>, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user/createWithArray'; const path = this.basePath + '/user/createWithArray';
@ -72,7 +80,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (body?: Array<User>, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public createUsersWithListInput (body?: Array<User>, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user/createWithList'; const path = this.basePath + '/user/createWithList';
@ -95,7 +107,12 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<string> { public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<string> {
const path = this.basePath + '/user/login'; const path = this.basePath + '/user/login';
@ -125,7 +142,10 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Logs out current logged in user session
*
*/
public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user/logout'; const path = this.basePath + '/user/logout';
@ -147,7 +167,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<User> { public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<User> {
const path = this.basePath + '/user/{username}' const path = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));
@ -174,7 +198,12 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* 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
*/
public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user/{username}' const path = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));
@ -202,7 +231,11 @@ namespace API.Client {
return this.$http(httpRequestParams); return this.$http(httpRequestParams);
} }
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> {
const path = this.basePath + '/user/{username}' const path = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));

View File

@ -153,7 +153,11 @@ export class UserApi {
} }
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user'; const path = this.url + this.basePath + '/user';
let queryParameters: any = {}; let queryParameters: any = {};
@ -198,7 +202,11 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (body?: Array<User>) : Promise<{ response: http.ClientResponse; body?: any; }> { public createUsersWithArrayInput (body?: Array<User>) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user/createWithArray'; const path = this.url + this.basePath + '/user/createWithArray';
let queryParameters: any = {}; let queryParameters: any = {};
@ -243,7 +251,11 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (body?: Array<User>) : Promise<{ response: http.ClientResponse; body?: any; }> { public createUsersWithListInput (body?: Array<User>) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user/createWithList'; const path = this.url + this.basePath + '/user/createWithList';
let queryParameters: any = {}; let queryParameters: any = {};
@ -288,7 +300,12 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> {
const path = this.url + this.basePath + '/user/login'; const path = this.url + this.basePath + '/user/login';
let queryParameters: any = {}; let queryParameters: any = {};
@ -340,7 +357,10 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Logs out current logged in user session
*
*/
public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user/logout'; const path = this.url + this.basePath + '/user/logout';
let queryParameters: any = {}; let queryParameters: any = {};
@ -384,7 +404,11 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> {
const path = this.url + this.basePath + '/user/{username}' const path = this.url + this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));
@ -434,7 +458,12 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user/{username}' const path = this.url + this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));
@ -485,7 +514,11 @@ export class UserApi {
return deferred.promise; return deferred.promise;
} }
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/user/{username}' const path = this.url + this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(username)); .replace('{' + 'username' + '}', String(username));
@ -572,7 +605,11 @@ export class PetApi {
} }
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/pet'; const path = this.url + this.basePath + '/pet';
let queryParameters: any = {}; let queryParameters: any = {};
@ -619,7 +656,11 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/pet'; const path = this.url + this.basePath + '/pet';
let queryParameters: any = {}; let queryParameters: any = {};
@ -666,7 +707,11 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public findPetsByStatus (status?: Array<string>) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> { public findPetsByStatus (status?: Array<string>) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> {
const path = this.url + this.basePath + '/pet/findByStatus'; const path = this.url + this.basePath + '/pet/findByStatus';
let queryParameters: any = {}; let queryParameters: any = {};
@ -716,7 +761,11 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public findPetsByTags (tags?: Array<string>) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> { public findPetsByTags (tags?: Array<string>) : Promise<{ response: http.ClientResponse; body: Array<Pet>; }> {
const path = this.url + this.basePath + '/pet/findByTags'; const path = this.url + this.basePath + '/pet/findByTags';
let queryParameters: any = {}; let queryParameters: any = {};
@ -766,7 +815,11 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> {
const path = this.url + this.basePath + '/pet/{petId}' const path = this.url + this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -818,7 +871,13 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/pet/{petId}' const path = this.url + this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -878,7 +937,12 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/pet/{petId}' const path = this.url + this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -932,7 +996,13 @@ export class PetApi {
return deferred.promise; return deferred.promise;
} }
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/pet/{petId}/uploadImage' const path = this.url + this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(petId)); .replace('{' + 'petId' + '}', String(petId));
@ -1030,7 +1100,10 @@ export class StoreApi {
} }
return <T1&T2>objA; return <T1&T2>objA;
} }
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> {
const path = this.url + this.basePath + '/store/inventory'; const path = this.url + this.basePath + '/store/inventory';
let queryParameters: any = {}; let queryParameters: any = {};
@ -1076,7 +1149,11 @@ export class StoreApi {
return deferred.promise; return deferred.promise;
} }
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> {
const path = this.url + this.basePath + '/store/order'; const path = this.url + this.basePath + '/store/order';
let queryParameters: any = {}; let queryParameters: any = {};
@ -1121,7 +1198,11 @@ export class StoreApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> {
const path = this.url + this.basePath + '/store/order/{orderId}' const path = this.url + this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId)); .replace('{' + 'orderId' + '}', String(orderId));
@ -1171,7 +1252,11 @@ export class StoreApi {
return deferred.promise; return deferred.promise;
} }
/**
* 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
*/
public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> {
const path = this.url + this.basePath + '/store/order/{orderId}' const path = this.url + this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(orderId)); .replace('{' + 'orderId' + '}', String(orderId));