diff --git a/bin/java-petstore.sh b/bin/java-petstore-jersey1.sh similarity index 79% rename from bin/java-petstore.sh rename to bin/java-petstore-jersey1.sh index be6472d7aad..27aa0f826ba 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore-jersey1.sh @@ -26,9 +26,9 @@ 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-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/default -DhideGenerationTimestamp=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples/client/petstore/java/jersey1 -DhideGenerationTimestamp=true --library=jersey1" -echo "Removing files and folders under samples/client/petstore/java/default/src/main" -rm -rf samples/client/petstore/java/default/src/main -find samples/client/petstore/java/default -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +echo "Removing files and folders under samples/client/petstore/java/jersey1/src/main" +rm -rf samples/client/petstore/java/jersey1/src/main +find samples/client/petstore/java/jersey1 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 27e95190648..c365f2b7035 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -32,17 +32,19 @@ public class JavaClientCodegen extends AbstractJavaCodegen { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); - CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); - library.setEnum(supportedLibraries); - library.setDefault(DEFAULT_LIBRARY); - cliOptions.add(library); + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + libraryOption.setDefault("okhttp-gson"); + cliOptions.add(libraryOption); + + setLibrary("okhttp-gson"); } @@ -96,6 +98,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen { supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); if (!StringUtils.isEmpty(getLibrary())) { + // set library to okhttp-gson as default + setLibrary("okhttp-gson"); + //TODO: add sbt support to default client supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } @@ -116,7 +121,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen { if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); additionalProperties.put("jackson", "true"); - } else if ("okhttp-gson".equals(getLibrary())) { + } else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); @@ -131,8 +136,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen { } else if("jersey2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); additionalProperties.put("jackson", "true"); - } else if(StringUtils.isEmpty(getLibrary())) { + } else if("jersey1".equals(getLibrary())) { additionalProperties.put("jackson", "true"); + } else { + LOGGER.error("Unknown library option (-l/--library): " + StringUtils.isEmpty(getLibrary())); } } @@ -175,7 +182,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if(!BooleanUtils.toBoolean(model.isEnum)) { - final String lib = getLibrary(); + //final String lib = getLibrary(); //Needed imports for Jackson based libraries if(additionalProperties.containsKey("jackson")) { model.imports.add("JsonProperty"); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 3712dcd7224..9c75d671607 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -790,6 +790,7 @@ public class ApiClient { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -984,6 +985,7 @@ public class ApiClient { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 4cb2a34ab20..bc1176ff8c5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -92,6 +92,7 @@ public class JSON { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { @@ -287,4 +288,4 @@ class LocalDateTypeAdapter extends TypeAdapter { } } } -{{/java8}} \ No newline at end of file +{{/java8}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index bfc25b8f5cc..f05c0e32700 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -163,6 +163,7 @@ public class DefaultGeneratorTest { final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json"); CodegenConfig codegenConfig = new JavaClientCodegen(); + codegenConfig.setLibrary("jersey1"); codegenConfig.setOutputDir(output.getAbsolutePath()); ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index bca63e37eed..c58844fb1da 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -22,6 +22,6 @@ public class OnlineJavaClientOptionsTest { assertNotNull(options); final CliOption opt = options.get(CodegenConstants.LIBRARY); assertNotNull(opt); - assertEquals(opt.getDefault(), JavaClientCodegen.DEFAULT_LIBRARY); + assertEquals(opt.getDefault(), "okhttp-gson"); } } diff --git a/pom.xml b/pom.xml index 10886a26069..2be7b856d8f 100644 --- a/pom.xml +++ b/pom.xml @@ -283,7 +283,7 @@ - java-client + java-client-jersey1 env @@ -291,7 +291,7 @@ - samples/client/petstore/java/default + samples/client/petstore/java/jersey1 diff --git a/samples/client/petstore/java/default/docs/ApiResponse.md b/samples/client/petstore/java/default/docs/ApiResponse.md deleted file mode 100644 index 1c17767c2b7..00000000000 --- a/samples/client/petstore/java/default/docs/ApiResponse.md +++ /dev/null @@ -1,12 +0,0 @@ - -# ApiResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] -**type** | **String** | | [optional] -**message** | **String** | | [optional] - - - diff --git a/samples/client/petstore/java/default/docs/InlineResponse200.md b/samples/client/petstore/java/default/docs/InlineResponse200.md deleted file mode 100644 index 487ebe429e4..00000000000 --- a/samples/client/petstore/java/default/docs/InlineResponse200.md +++ /dev/null @@ -1,24 +0,0 @@ - -# InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**photoUrls** | **List<String>** | | [optional] -**name** | **String** | | [optional] -**id** | **Long** | | -**category** | **Object** | | [optional] -**tags** | [**List<Tag>**](Tag.md) | | [optional] -**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] - - - -## Enum: StatusEnum -Name | Value ----- | ----- -AVAILABLE | available -PENDING | pending -SOLD | sold - - - diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java deleted file mode 100644 index b16fdbbdfa9..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ /dev/null @@ -1,687 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.GenericType; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.api.client.WebResource.Builder; - -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.MediaType; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.TimeZone; - -import java.net.URLEncoder; - -import java.io.File; -import java.io.UnsupportedEncodingException; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import io.swagger.client.auth.Authentication; -import io.swagger.client.auth.HttpBasicAuth; -import io.swagger.client.auth.ApiKeyAuth; -import io.swagger.client.auth.OAuth; - - -public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "http://petstore.swagger.io/v2"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private ObjectMapper objectMapper; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; - - public ApiClient() { - objectMapper = new ObjectMapper(); - objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - objectMapper.registerModule(new JodaModule()); - objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); - - dateFormat = ApiClient.buildDefaultDateFormat(); - - // Set default User-Agent. - setUserAgent("Swagger-Codegen/1.0.0/java"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - - rebuildHttpClient(); - } - - public static DateFormat buildDefaultDateFormat() { - // Use RFC3339 format for date and datetime. - // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - // Use UTC as the default time zone. - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - return dateFormat; - } - - /** - * Build the Client used to make HTTP requests with the latest settings, - * i.e. objectMapper and debugging. - * TODO: better to use the Builder Pattern? - */ - public ApiClient rebuildHttpClient() { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) { - client.addFilter(new LoggingFilter()); - } - this.httpClient = client; - return this; - } - - /** - * Returns the current object mapper used for JSON serialization/deserialization. - *

- * Note: If you make changes to the object mapper, remember to set it back via - * setObjectMapper in order to trigger HTTP client rebuilding. - *

- */ - public ObjectMapper getObjectMapper() { - return objectMapper; - } - - public ApiClient setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - // Need to rebuild the Client as it depends on object mapper. - rebuildHttpClient(); - return this; - } - - public Client getHttpClient() { - return httpClient; - } - - public ApiClient setHttpClient(Client httpClient) { - this.httpClient = httpClient; - return this; - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Gets the status code of the previous request - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Gets the response headers of the previous request - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - */ - public void setAccessToken(String accessToken) { - for (Authentication auth : authentications.values()) { - if (auth instanceof OAuth) { - ((OAuth) auth).setAccessToken(accessToken); - return; - } - } - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - // Need to rebuild the Client as it depends on the value of debugging. - rebuildHttpClient(); - return this; - } - - /** - * Connect timeout (in milliseconds). - */ - public int getConnectTimeout() { - return connectionTimeout; - } - - /** - * Set the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link Integer#MAX_VALUE}. - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - httpClient.setConnectTimeout(connectionTimeout); - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - // Also set the date format for model (de)serialization with Date properties. - this.objectMapper.setDateFormat((DateFormat) dateFormat.clone()); - // Need to rebuild the Client as objectMapper changes. - rebuildHttpClient(); - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDate((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { - if(b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - */ - public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return "application/json"; - } - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string according the given - * Content-Type (only JSON is supported for now). - */ - public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - return mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - return this.getXWWWFormUrlencodedParams(formParams); - } else { - // We let Jersey attempt to serialize the body - return obj; - } - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param path The sub path - * @param queryParams The query parameters - * @return The full URL - */ - private String buildUrl(String path, List queryParams) { - final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - return url.toString(); - } - - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { - if (body != null && !formParams.isEmpty()) { - throw new ApiException(500, "Cannot have body and form params"); - } - - updateParamsForAuth(authNames, queryParams, headerParams); - - final String url = buildUrl(path, queryParams); - Builder builder; - if (accept == null) { - builder = httpClient.resource(url).getRequestBuilder(); - } else { - builder = httpClient.resource(url).accept(accept); - } - - for (String key : headerParams.keySet()) { - builder = builder.header(key, headerParams.get(key)); - } - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - builder = builder.header(key, defaultHeaderMap.get(key)); - } - } - - ClientResponse response = null; - - if ("GET".equals(method)) { - response = (ClientResponse) builder.get(ClientResponse.class); - } else if ("POST".equals(method)) { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PUT".equals(method)) { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("DELETE".equals(method)) { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); - } else if ("PATCH".equals(method)) { - response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); - } - else { - throw new ApiException(500, "unknown method type " + method); - } - return response; - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - if it is not binary, otherwise null - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @return The response body in type of string - */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - - ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); - - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = response.getHeaders(); - - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if (returnType == null) - return null; - else - return response.getEntity(returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = response.getEntity(String.class); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Encode the given form parameters as request body. - */ - private String getXWWWFormUrlencodedParams(Map formParams) { - StringBuilder formParamBuilder = new StringBuilder(); - - for (Entry param : formParams.entrySet()) { - String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) - .append("=") - .append(URLEncoder.encode(valueStr, "utf8")); - formParamBuilder.append("&"); - } catch (UnsupportedEncodingException e) { - // move on to next - } - } - - String encodedFormParams = formParamBuilder.toString(); - if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); - } - - return encodedFormParams; - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java deleted file mode 100644 index c772f9402da..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/FakeApi.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import org.joda.time.LocalDate; -import org.joda.time.DateTime; -import java.math.BigDecimal; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param string None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @throws ApiException if fails to make API call - */ - public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException(400, "Missing the required parameter 'number' when calling testEndpointParameters"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException(400, "Missing the required parameter '_double' when calling testEndpointParameters"); - } - - // verify the required parameter 'string' is set - if (string == null) { - throw new ApiException(400, "Missing the required parameter 'string' when calling testEndpointParameters"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException(400, "Missing the required parameter '_byte' when calling testEndpointParameters"); - } - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (integer != null) - localVarFormParams.put("integer", integer); -if (int32 != null) - localVarFormParams.put("int32", int32); -if (int64 != null) - localVarFormParams.put("int64", int64); -if (number != null) - localVarFormParams.put("number", number); -if (_float != null) - localVarFormParams.put("float", _float); -if (_double != null) - localVarFormParams.put("double", _double); -if (string != null) - localVarFormParams.put("string", string); -if (_byte != null) - localVarFormParams.put("byte", _byte); -if (binary != null) - localVarFormParams.put("binary", binary); -if (date != null) - localVarFormParams.put("date", date); -if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); -if (password != null) - localVarFormParams.put("password", password); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * To test enum query parameters - * - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException if fails to make API call - */ - public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - - if (enumQueryString != null) - localVarFormParams.put("enum_query_string", enumQueryString); -if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java deleted file mode 100644 index c126283d2aa..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ /dev/null @@ -1,410 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Pet; -import java.io.File; -import io.swagger.client.model.ModelApiResponse; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void addPet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException if fails to make API call - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByStatus(List status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List - * @throws ApiException if fails to make API call - */ - public List findPetsByTags(List tags) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException if fails to make API call - */ - public Pet getPetById(Long petId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException if fails to make API call - */ - public void updatePet(Pet body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException if fails to make API call - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (name != null) - localVarFormParams.put("name", name); -if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException if fails to make API call - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); -if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java deleted file mode 100644 index b30edd4f22f..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Order; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteOrder(String orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - * @throws ApiException if fails to make API call - */ - public Map getInventory() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { "api_key" }; - - GenericType> localVarReturnType = new GenericType>() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order getOrderById(Long orderId) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException if fails to make API call - */ - public Order placeOrder(Order body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java deleted file mode 100644 index 9d6a1bb12fd..00000000000 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ /dev/null @@ -1,396 +0,0 @@ -/** - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.User; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException if fails to make API call - */ - public void createUser(User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithArrayInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException if fails to make API call - */ - public void createUsersWithListInput(List body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException if fails to make API call - */ - public void deleteUser(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException if fails to make API call - */ - public User getUserByName(String username) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException if fails to make API call - */ - public String loginUser(String username, String password) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } - /** - * Logs out current logged in user session - * - * @throws ApiException if fails to make API call - */ - public void logoutUser() throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException if fails to make API call - */ - public void updateUser(String username, User body) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - - apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java b/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java deleted file mode 100644 index d0be1523e45..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/PetstoreProfiling.java +++ /dev/null @@ -1,106 +0,0 @@ -package io.swagger; - -import java.io.*; -import java.util.*; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -public class PetstoreProfiling { - public int total = 5; - public Long newPetId = 50003L; - public String outputFile = "./petstore_profiling.output"; - - public void callApis(int index, List> results) { - long start; - - try { - PetApi petApi = new PetApi(); - - /* ADD PET */ - Pet pet = new Pet(); - pet.setId(newPetId); - pet.setName("profiler"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - pet.setPhotoUrls(Arrays.asList("http://profiler.com")); - // new tag - Tag tag = new Tag(); - tag.setId(newPetId); // use the same id as pet - tag.setName("profile tag 1"); - // new category - Category category = new Category(); - category.setId(newPetId); // use the same id as pet - category.setName("profile category 1"); - - pet.setTags(Arrays.asList(tag)); - pet.setCategory(category); - - /* ADD PET */ - start = System.nanoTime(); - petApi.addPet(pet); - results.add(buildResult(index, "ADD PET", System.nanoTime() - start)); - - /* GET PET */ - start = System.nanoTime(); - pet = petApi.getPetById(newPetId); - results.add(buildResult(index, "GET PET", System.nanoTime() - start)); - - /* UPDATE PET WITH FORM */ - start = System.nanoTime(); - petApi.updatePetWithForm(newPetId, "new profiler", "sold"); - results.add(buildResult(index, "UPDATE PET", System.nanoTime() - start)); - - /* DELETE PET */ - start = System.nanoTime(); - petApi.deletePet(newPetId, "special-key"); - results.add(buildResult(index, "DELETE PET", System.nanoTime() - start)); - } catch (ApiException e) { - System.out.println("Caught error: " + e.getMessage()); - System.out.println("HTTP response headers: " + e.getResponseHeaders()); - System.out.println("HTTP response body: " + e.getResponseBody()); - System.out.println("HTTP status code: " + e.getCode()); - } - } - - public void run() { - System.out.printf("Running profiling... (total: %s)\n", total); - - List> results = new ArrayList>(); - for (int i = 0; i < total; i++) { - callApis(i, results); - } - writeResultsToFile(results); - - System.out.printf("Profiling results written to %s\n", outputFile); - } - - private Map buildResult(int index, String name, long time) { - Map result = new HashMap(); - result.put("index", String.valueOf(index)); - result.put("name", name); - result.put("time", String.valueOf(time / 1000000000.0)); - return result; - } - - private void writeResultsToFile(List> results) { - try { - java.io.File file = new java.io.File(outputFile); - PrintWriter writer = new PrintWriter(file); - String command = "mvn compile test-compile exec:java -Dexec.classpathScope=test -Dexec.mainClass=\"io.swagger.PetstoreProfiling\""; - writer.println("# To run the profiling:"); - writer.printf("# %s\n\n", command); - for (Map result : results) { - writer.printf("%s: %s => %s\n", result.get("index"), result.get("name"), result.get("time")); - } - writer.close(); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - public static void main(String[] args) { - final PetstoreProfiling profiling = new PetstoreProfiling(); - profiling.run(); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java b/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java deleted file mode 100644 index 7ddf142426e..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/TestUtils.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.swagger; - -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; - -public class TestUtils { - private static final AtomicLong atomicId = createAtomicId(); - - public static long nextId() { - return atomicId.getAndIncrement(); - } - - private static AtomicLong createAtomicId() { - int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000; - return new AtomicLong((long) baseId); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java deleted file mode 100644 index 19b55257d0c..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package io.swagger.client; - -import io.swagger.client.auth.*; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class ApiClientTest { - ApiClient apiClient = null; - - @Before - public void setup() { - apiClient = new ApiClient(); - } - - @Test - public void testParseAndFormatDate() { - // default date format - String dateStr = "2015-11-07T03:49:09.356Z"; - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); - - // custom date format: without milli-seconds, custom time zone - DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - format.setTimeZone(TimeZone.getTimeZone("GMT+10")); - apiClient.setDateFormat(format); - dateStr = "2015-11-07T13:49:09+10:00"; - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); - } - - @Test - public void testIsJsonMime() { - assertFalse(apiClient.isJsonMime(null)); - assertFalse(apiClient.isJsonMime("")); - assertFalse(apiClient.isJsonMime("text/plain")); - assertFalse(apiClient.isJsonMime("application/xml")); - assertFalse(apiClient.isJsonMime("application/jsonp")); - - assertTrue(apiClient.isJsonMime("application/json")); - assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); - assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); - } - - @Test - public void testSelectHeaderAccept() { - String[] accepts = {"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); - - accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; - assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); - - accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; - assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); - - accepts = new String[]{"text/plain", "application/xml"}; - assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); - - accepts = new String[]{}; - assertNull(apiClient.selectHeaderAccept(accepts)); - } - - @Test - public void testSelectHeaderContentType() { - String[] contentTypes = {"application/json", "application/xml"}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - - contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; - assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); - - contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; - assertEquals("application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); - - contentTypes = new String[]{"text/plain", "application/xml"}; - assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); - - contentTypes = new String[]{}; - assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); - } - - @Test - public void testGetAuthentications() { - Map auths = apiClient.getAuthentications(); - - Authentication auth = auths.get("api_key"); - assertNotNull(auth); - assertTrue(auth instanceof ApiKeyAuth); - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; - assertEquals("header", apiKeyAuth.getLocation()); - assertEquals("api_key", apiKeyAuth.getParamName()); - - auth = auths.get("petstore_auth"); - assertTrue(auth instanceof OAuth); - assertSame(auth, apiClient.getAuthentication("petstore_auth")); - - assertNull(auths.get("unknown")); - - try { - auths.put("my_auth", new HttpBasicAuth()); - fail("the authentications returned should not be modifiable"); - } catch (UnsupportedOperationException e) { - } - } - - @Ignore("There is no more basic auth in petstore security definitions") - @Test - public void testSetUsernameAndPassword() { - HttpBasicAuth auth = null; - for (Authentication _auth : apiClient.getAuthentications().values()) { - if (_auth instanceof HttpBasicAuth) { - auth = (HttpBasicAuth) _auth; - break; - } - } - auth.setUsername(null); - auth.setPassword(null); - - apiClient.setUsername("my-username"); - apiClient.setPassword("my-password"); - assertEquals("my-username", auth.getUsername()); - assertEquals("my-password", auth.getPassword()); - - // reset values - auth.setUsername(null); - auth.setPassword(null); - } - - @Test - public void testSetApiKeyAndPrefix() { - ApiKeyAuth auth = null; - for (Authentication _auth : apiClient.getAuthentications().values()) { - if (_auth instanceof ApiKeyAuth) { - auth = (ApiKeyAuth) _auth; - break; - } - } - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - - apiClient.setApiKey("my-api-key"); - apiClient.setApiKeyPrefix("Token"); - assertEquals("my-api-key", auth.getApiKey()); - assertEquals("Token", auth.getApiKeyPrefix()); - - // reset values - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - } - - @Test - public void testParameterToPairsWhenNameIsInvalid() throws Exception { - List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); - List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); - - assertTrue(pairs_a.isEmpty()); - assertTrue(pairs_b.isEmpty()); - } - - @Test - public void testParameterToPairsWhenValueIsNull() throws Exception { - List pairs = apiClient.parameterToPairs("csv", "param-a", null); - - assertTrue(pairs.isEmpty()); - } - - @Test - public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { - - // single empty string - List pairs = apiClient.parameterToPairs("csv", "param-a", " "); - assertEquals(1, pairs.size()); - - // list of empty strings - List strs = new ArrayList(); - strs.add(" "); - strs.add(" "); - strs.add(" "); - - List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); - - assertEquals(1, concatStrings.size()); - assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters - } - - @Test - public void testParameterToPairsWhenValueIsNotCollection() throws Exception { - String name = "param-a"; - Integer value = 1; - - List pairs = apiClient.parameterToPairs("csv", name, value); - - assertEquals(1, pairs.size()); - assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); - } - - @Test - public void testParameterToPairsWhenValueIsCollection() throws Exception { - Map collectionFormatMap = new HashMap(); - collectionFormatMap.put("csv", ","); - collectionFormatMap.put("tsv", "\t"); - collectionFormatMap.put("ssv", " "); - collectionFormatMap.put("pipes", "\\|"); - collectionFormatMap.put("", ","); // no format, must default to csv - collectionFormatMap.put("unknown", ","); // all other formats, must default to csv - - String name = "param-a"; - - List values = new ArrayList(); - values.add("value-a"); - values.add(123); - values.add(new Date()); - - // check for multi separately - List multiPairs = apiClient.parameterToPairs("multi", name, values); - assertEquals(values.size(), multiPairs.size()); - - // all other formats - for (String collectionFormat : collectionFormatMap.keySet()) { - List pairs = apiClient.parameterToPairs(collectionFormat, name, values); - - assertEquals(1, pairs.size()); - - String delimiter = collectionFormatMap.get(collectionFormat); - String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); - - // must equal input values - assertEquals(values.size(), pairValueSplit.length); - } - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java deleted file mode 100644 index b95eb74605e..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.swagger.client; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class ConfigurationTest { - @Test - public void testDefaultApiClient() { - ApiClient apiClient = Configuration.getDefaultApiClient(); - assertNotNull(apiClient); - assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); - assertFalse(apiClient.isDebugging()); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java deleted file mode 100644 index 4b03c7a9812..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.swagger.client; - -import org.junit.*; -import static org.junit.Assert.*; - - -public class StringUtilTest { - @Test - public void testContainsIgnoreCase() { - assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); - assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); - assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); - assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); - assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); - - assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); - assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); - assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); - } - - @Test - public void testJoin() { - String[] array = {"aa", "bb", "cc"}; - assertEquals("aa,bb,cc", StringUtil.join(array, ",")); - assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); - assertEquals("aabbcc", StringUtil.join(array, "")); - assertEquals("aa bb cc", StringUtil.join(array, " ")); - assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); - - assertEquals("", StringUtil.join(new String[]{}, ",")); - assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java deleted file mode 100644 index c564001ad70..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/FakeApiTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import java.math.BigDecimal; -import java.util.Date; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for FakeApi - */ -public class FakeApiTest { - - private final FakeApi api = new FakeApi(); - - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void testEndpointParametersTest() throws ApiException { - BigDecimal number = null; - Double _double = null; - String string = null; - byte[] _byte = null; - Integer integer = null; - Integer int32 = null; - Long int64 = null; - Float _float = null; - byte[] binary = null; - Date date = null; - Date dateTime = null; - String password = null; - // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); - - // TODO: test validations - } - -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java deleted file mode 100644 index e75a9c7e7da..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/PetApiTest.java +++ /dev/null @@ -1,306 +0,0 @@ -package io.swagger.client.api; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import io.swagger.TestUtils; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -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 java.util.Map; - -import org.junit.*; -import static org.junit.Assert.*; - -public class PetApiTest { - private PetApi api; - private ObjectMapper mapper; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* - @Test - public void testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - assertTrue(categoryIdObj instanceof Integer); - Integer categoryIdInt = (Integer) categoryIdObj; - assertEquals(category.getId(), Long.valueOf(categoryIdInt)); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - 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); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); - 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 tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - 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); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - 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", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.writeValueAsString(o); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private T deserializeJson(String json, Class klass) { - if (mapper == null) { - mapper = createObjectMapper(); - } - try { - return mapper.readValue(json, klass); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private ObjectMapper createObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.registerModule(new JodaModule()); - return mapper; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java deleted file mode 100644 index 51779f265f0..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/StoreApiTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.TestUtils; - -import io.swagger.client.ApiException; - -import io.swagger.client.*; -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; -import java.util.Map; -import java.text.SimpleDateFormat; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.junit.*; -import static org.junit.Assert.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - // set custom date format that is used by the petstore server - api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - /* - @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); - - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - assertTrue(firstEntry.getValue() instanceof Integer); - } - */ - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - assertEquals(order.getShipDate().withZone(DateTimeZone.UTC), fetched.getShipDate().withZone(DateTimeZone.UTC)); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(DateTime.now()); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java deleted file mode 100644 index c7fb92d2552..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/api/UserApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.TestUtils; - -import io.swagger.client.api.*; -import io.swagger.client.auth.*; -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 UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java deleted file mode 100644 index 5bdb4fb78fb..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.swagger.client.auth; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Map; -import java.util.List; - -import io.swagger.client.Pair; -import org.junit.*; -import static org.junit.Assert.*; - - -public class ApiKeyAuthTest { - @Test - public void testApplyToParamsInQuery() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); - auth.setApiKey("my-api-key"); - auth.applyToParams(queryParams, headerParams); - - assertEquals(1, queryParams.size()); - for (Pair queryParam : queryParams) { - assertEquals("my-api-key", queryParam.getValue()); - } - - // no changes to header parameters - assertEquals(0, headerParams.size()); - } - - @Test - public void testApplyToParamsInHeaderWithPrefix() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); - auth.setApiKey("my-api-token"); - auth.setApiKeyPrefix("Token"); - auth.applyToParams(queryParams, headerParams); - - // no changes to query parameters - assertEquals(0, queryParams.size()); - assertEquals(1, headerParams.size()); - assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); - } -} diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java deleted file mode 100644 index 52c5497ba83..00000000000 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.swagger.client.auth; - -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Map; -import java.util.List; - -import io.swagger.client.Pair; -import org.junit.*; -import static org.junit.Assert.*; - - -public class HttpBasicAuthTest { - HttpBasicAuth auth = null; - - @Before - public void setup() { - auth = new HttpBasicAuth(); - } - - @Test - public void testApplyToParams() { - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - - auth.setUsername("my-username"); - auth.setPassword("my-password"); - auth.applyToParams(queryParams, headerParams); - - // no changes to query parameters - assertEquals(0, queryParams.size()); - assertEquals(1, headerParams.size()); - // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix - String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; - assertEquals(expected, headerParams.get("Authorization")); - - // null username should be treated as empty string - auth.setUsername(null); - auth.applyToParams(queryParams, headerParams); - // the string below is base64-encoded result of ":my-password" with the "Basic " prefix - expected = "Basic Om15LXBhc3N3b3Jk"; - assertEquals(expected, headerParams.get("Authorization")); - - // null password should be treated as empty string - auth.setUsername("my-username"); - auth.setPassword(null); - auth.applyToParams(queryParams, headerParams); - // the string below is base64-encoded result of "my-username:" with the "Basic " prefix - expected = "Basic bXktdXNlcm5hbWU6"; - assertEquals(expected, headerParams.get("Authorization")); - } -} diff --git a/samples/client/petstore/java/default/.gitignore b/samples/client/petstore/java/jersey1/.gitignore similarity index 100% rename from samples/client/petstore/java/default/.gitignore rename to samples/client/petstore/java/jersey1/.gitignore diff --git a/samples/client/petstore/java/default/.swagger-codegen-ignore b/samples/client/petstore/java/jersey1/.swagger-codegen-ignore similarity index 100% rename from samples/client/petstore/java/default/.swagger-codegen-ignore rename to samples/client/petstore/java/jersey1/.swagger-codegen-ignore diff --git a/samples/client/petstore/java/default/.travis.yml b/samples/client/petstore/java/jersey1/.travis.yml similarity index 100% rename from samples/client/petstore/java/default/.travis.yml rename to samples/client/petstore/java/jersey1/.travis.yml diff --git a/samples/client/petstore/java/default/LICENSE b/samples/client/petstore/java/jersey1/LICENSE similarity index 100% rename from samples/client/petstore/java/default/LICENSE rename to samples/client/petstore/java/jersey1/LICENSE diff --git a/samples/client/petstore/java/default/README.md b/samples/client/petstore/java/jersey1/README.md similarity index 69% rename from samples/client/petstore/java/default/README.md rename to samples/client/petstore/java/jersey1/README.md index 562d76a8db4..c824c828980 100644 --- a/samples/client/petstore/java/default/README.md +++ b/samples/client/petstore/java/jersey1/README.md @@ -61,30 +61,32 @@ Please follow the [installation](#installation) instruction and execute the foll import io.swagger.client.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; -import io.swagger.client.api.PetApi; +import io.swagger.client.api.FakeApi; import java.io.File; import java.util.*; -public class PetApiExample { +public class FakeApiExample { public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - - - - PetApi apiInstance = new PetApi(); - - Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + FakeApi apiInstance = new FakeApi(); + BigDecimal number = new BigDecimal(); // BigDecimal | None + Double _double = 3.4D; // Double | None + String string = "string_example"; // String | None + byte[] _byte = B; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 789L; // Long | None + Float _float = 3.4F; // Float | None + byte[] binary = B; // byte[] | None + LocalDate date = new LocalDate(); // LocalDate | None + DateTime dateTime = new DateTime(); // DateTime | None + String password = "password_example"; // String | None try { - apiInstance.addPet(body); + apiInstance.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); } } @@ -98,21 +100,18 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumQueryParameters**](docs/FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters *PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**addPetUsingByteArray**](docs/PetApi.md#addPetUsingByteArray) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding a new pet to the store *PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status *PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags *PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**getPetByIdInObject**](docs/PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -*PetApi* | [**petPetIdtestingByteArraytrueGet**](docs/PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by 'Find pet by ID' *PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet *PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data *PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image *StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status *StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' *StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID *StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet *UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user @@ -127,16 +126,29 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) - [Dog](docs/Dog.md) - - [InlineResponse200](docs/InlineResponse200.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) @@ -145,6 +157,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -154,40 +172,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### test_api_client_id - -- **Type**: API key -- **API key parameter name**: x-test_api_client_id -- **Location**: HTTP header - -### test_api_client_secret - -- **Type**: API key -- **API key parameter name**: x-test_api_client_secret -- **Location**: HTTP header - -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - -### test_http_basic - -- **Type**: HTTP basic authentication - -### test_api_key_query - -- **Type**: API key -- **API key parameter name**: test_api_key_query -- **Location**: URL query string - -### test_api_key_header - -- **Type**: API key -- **API key parameter name**: test_api_key_header -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/jersey1/build.gradle similarity index 72% rename from samples/client/petstore/java/default/build.gradle rename to samples/client/petstore/java/jersey1/build.gradle index 1e4969e26fd..0ec352a14c8 100644 --- a/samples/client/petstore/java/default/build.gradle +++ b/samples/client/petstore/java/jersey1/build.gradle @@ -23,7 +23,7 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' - + android { compileSdkVersion 23 buildToolsVersion '23.0.2' @@ -35,7 +35,7 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } - + // Rename the aar correctly libraryVariants.all { variant -> variant.outputs.each { output -> @@ -51,7 +51,7 @@ if(hasProperty('target') && target == 'android') { provided 'javax.annotation:jsr250-api:1.0' } } - + afterEvaluate { android.libraryVariants.all { variant -> def task = project.tasks.create "jar${variant.name.capitalize()}", Jar @@ -63,12 +63,12 @@ if(hasProperty('target') && target == 'android') { artifacts.add('archives', task); } } - + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } - + artifacts { archives sourcesJar } @@ -80,37 +80,24 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 - + install { repositories.mavenInstaller { pom.artifactId = 'swagger-java-client' } } - + task execute(type:JavaExec) { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } } -ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.5" - jersey_version = "1.19.1" - jodatime_version = "2.9.4" - junit_version = "4.12" -} - dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "com.sun.jersey:jersey-client:$jersey_version" - compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" - compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" - compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" - compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" - compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" - compile "joda-time:joda-time:$jodatime_version" - compile "com.brsanthu:migbase64:2.2" - testCompile "junit:junit:$junit_version" + compile 'io.swagger:swagger-annotations:1.5.8' + compile 'com.squareup.okhttp:okhttp:2.7.5' + compile 'com.squareup.okhttp:logging-interceptor:2.7.5' + compile 'com.google.code.gson:gson:2.6.2' + compile 'joda-time:joda-time:2.9.3' + testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/jersey1/build.sbt b/samples/client/petstore/java/jersey1/build.sbt new file mode 100644 index 00000000000..59bf09eb5a7 --- /dev/null +++ b/samples/client/petstore/java/jersey1/build.sbt @@ -0,0 +1,20 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-java-client", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.8", + "com.squareup.okhttp" % "okhttp" % "2.7.5", + "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", + "com.google.code.gson" % "gson" % "2.6.2", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/AdditionalPropertiesClass.md rename to samples/client/petstore/java/jersey1/docs/AdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Animal.md b/samples/client/petstore/java/jersey1/docs/Animal.md similarity index 100% rename from samples/client/petstore/java/default/docs/Animal.md rename to samples/client/petstore/java/jersey1/docs/Animal.md diff --git a/samples/client/petstore/java/default/docs/AnimalFarm.md b/samples/client/petstore/java/jersey1/docs/AnimalFarm.md similarity index 100% rename from samples/client/petstore/java/default/docs/AnimalFarm.md rename to samples/client/petstore/java/jersey1/docs/AnimalFarm.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfArrayOfNumberOnly.md rename to samples/client/petstore/java/jersey1/docs/ArrayOfArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/jersey1/docs/ArrayOfNumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayOfNumberOnly.md rename to samples/client/petstore/java/jersey1/docs/ArrayOfNumberOnly.md diff --git a/samples/client/petstore/java/default/docs/ArrayTest.md b/samples/client/petstore/java/jersey1/docs/ArrayTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/ArrayTest.md rename to samples/client/petstore/java/jersey1/docs/ArrayTest.md diff --git a/samples/client/petstore/java/default/docs/Cat.md b/samples/client/petstore/java/jersey1/docs/Cat.md similarity index 100% rename from samples/client/petstore/java/default/docs/Cat.md rename to samples/client/petstore/java/jersey1/docs/Cat.md diff --git a/samples/client/petstore/java/default/docs/Category.md b/samples/client/petstore/java/jersey1/docs/Category.md similarity index 100% rename from samples/client/petstore/java/default/docs/Category.md rename to samples/client/petstore/java/jersey1/docs/Category.md diff --git a/samples/client/petstore/java/default/docs/Dog.md b/samples/client/petstore/java/jersey1/docs/Dog.md similarity index 100% rename from samples/client/petstore/java/default/docs/Dog.md rename to samples/client/petstore/java/jersey1/docs/Dog.md diff --git a/samples/client/petstore/java/default/docs/EnumClass.md b/samples/client/petstore/java/jersey1/docs/EnumClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumClass.md rename to samples/client/petstore/java/jersey1/docs/EnumClass.md diff --git a/samples/client/petstore/java/default/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/EnumTest.md rename to samples/client/petstore/java/jersey1/docs/EnumTest.md diff --git a/samples/client/petstore/java/default/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/FakeApi.md rename to samples/client/petstore/java/jersey1/docs/FakeApi.md diff --git a/samples/client/petstore/java/default/docs/FormatTest.md b/samples/client/petstore/java/jersey1/docs/FormatTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/FormatTest.md rename to samples/client/petstore/java/jersey1/docs/FormatTest.md diff --git a/samples/client/petstore/java/default/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/HasOnlyReadOnly.md rename to samples/client/petstore/java/jersey1/docs/HasOnlyReadOnly.md diff --git a/samples/client/petstore/java/default/docs/MapTest.md b/samples/client/petstore/java/jersey1/docs/MapTest.md similarity index 100% rename from samples/client/petstore/java/default/docs/MapTest.md rename to samples/client/petstore/java/jersey1/docs/MapTest.md diff --git a/samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md similarity index 100% rename from samples/client/petstore/java/default/docs/MixedPropertiesAndAdditionalPropertiesClass.md rename to samples/client/petstore/java/jersey1/docs/MixedPropertiesAndAdditionalPropertiesClass.md diff --git a/samples/client/petstore/java/default/docs/Model200Response.md b/samples/client/petstore/java/jersey1/docs/Model200Response.md similarity index 100% rename from samples/client/petstore/java/default/docs/Model200Response.md rename to samples/client/petstore/java/jersey1/docs/Model200Response.md diff --git a/samples/client/petstore/java/default/docs/ModelApiResponse.md b/samples/client/petstore/java/jersey1/docs/ModelApiResponse.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelApiResponse.md rename to samples/client/petstore/java/jersey1/docs/ModelApiResponse.md diff --git a/samples/client/petstore/java/default/docs/ModelReturn.md b/samples/client/petstore/java/jersey1/docs/ModelReturn.md similarity index 100% rename from samples/client/petstore/java/default/docs/ModelReturn.md rename to samples/client/petstore/java/jersey1/docs/ModelReturn.md diff --git a/samples/client/petstore/java/default/docs/Name.md b/samples/client/petstore/java/jersey1/docs/Name.md similarity index 100% rename from samples/client/petstore/java/default/docs/Name.md rename to samples/client/petstore/java/jersey1/docs/Name.md diff --git a/samples/client/petstore/java/default/docs/NumberOnly.md b/samples/client/petstore/java/jersey1/docs/NumberOnly.md similarity index 100% rename from samples/client/petstore/java/default/docs/NumberOnly.md rename to samples/client/petstore/java/jersey1/docs/NumberOnly.md diff --git a/samples/client/petstore/java/default/docs/Order.md b/samples/client/petstore/java/jersey1/docs/Order.md similarity index 100% rename from samples/client/petstore/java/default/docs/Order.md rename to samples/client/petstore/java/jersey1/docs/Order.md diff --git a/samples/client/petstore/java/default/docs/Pet.md b/samples/client/petstore/java/jersey1/docs/Pet.md similarity index 100% rename from samples/client/petstore/java/default/docs/Pet.md rename to samples/client/petstore/java/jersey1/docs/Pet.md diff --git a/samples/client/petstore/java/default/docs/PetApi.md b/samples/client/petstore/java/jersey1/docs/PetApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/PetApi.md rename to samples/client/petstore/java/jersey1/docs/PetApi.md diff --git a/samples/client/petstore/java/default/docs/ReadOnlyFirst.md b/samples/client/petstore/java/jersey1/docs/ReadOnlyFirst.md similarity index 100% rename from samples/client/petstore/java/default/docs/ReadOnlyFirst.md rename to samples/client/petstore/java/jersey1/docs/ReadOnlyFirst.md diff --git a/samples/client/petstore/java/default/docs/SpecialModelName.md b/samples/client/petstore/java/jersey1/docs/SpecialModelName.md similarity index 100% rename from samples/client/petstore/java/default/docs/SpecialModelName.md rename to samples/client/petstore/java/jersey1/docs/SpecialModelName.md diff --git a/samples/client/petstore/java/default/docs/StoreApi.md b/samples/client/petstore/java/jersey1/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/StoreApi.md rename to samples/client/petstore/java/jersey1/docs/StoreApi.md diff --git a/samples/client/petstore/java/default/docs/Tag.md b/samples/client/petstore/java/jersey1/docs/Tag.md similarity index 100% rename from samples/client/petstore/java/default/docs/Tag.md rename to samples/client/petstore/java/jersey1/docs/Tag.md diff --git a/samples/client/petstore/java/default/docs/User.md b/samples/client/petstore/java/jersey1/docs/User.md similarity index 100% rename from samples/client/petstore/java/default/docs/User.md rename to samples/client/petstore/java/jersey1/docs/User.md diff --git a/samples/client/petstore/java/default/docs/UserApi.md b/samples/client/petstore/java/jersey1/docs/UserApi.md similarity index 100% rename from samples/client/petstore/java/default/docs/UserApi.md rename to samples/client/petstore/java/jersey1/docs/UserApi.md diff --git a/samples/client/petstore/java/default/git_push.sh b/samples/client/petstore/java/jersey1/git_push.sh similarity index 100% rename from samples/client/petstore/java/default/git_push.sh rename to samples/client/petstore/java/jersey1/git_push.sh diff --git a/samples/client/petstore/java/default/gradle.properties b/samples/client/petstore/java/jersey1/gradle.properties similarity index 100% rename from samples/client/petstore/java/default/gradle.properties rename to samples/client/petstore/java/jersey1/gradle.properties diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar similarity index 100% rename from samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.jar rename to samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.jar diff --git a/samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from samples/client/petstore/java/default/gradle/wrapper/gradle-wrapper.properties rename to samples/client/petstore/java/jersey1/gradle/wrapper/gradle-wrapper.properties diff --git a/samples/client/petstore/java/default/gradlew b/samples/client/petstore/java/jersey1/gradlew similarity index 100% rename from samples/client/petstore/java/default/gradlew rename to samples/client/petstore/java/jersey1/gradlew diff --git a/samples/client/petstore/java/default/gradlew.bat b/samples/client/petstore/java/jersey1/gradlew.bat similarity index 100% rename from samples/client/petstore/java/default/gradlew.bat rename to samples/client/petstore/java/jersey1/gradlew.bat diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/jersey1/pom.xml similarity index 65% rename from samples/client/petstore/java/default/pom.xml rename to samples/client/petstore/java/jersey1/pom.xml index c4cb68e99f4..638d5395d46 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -6,7 +6,11 @@ jar swagger-java-client 1.0.0 - + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + 2.2.0 @@ -92,61 +96,28 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - io.swagger swagger-annotations - ${swagger-annotations-version} - - - - - com.sun.jersey - jersey-client - ${jersey-version} + ${swagger-core-version} - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} + com.squareup.okhttp + okhttp + ${okhttp-version} - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} + com.squareup.okhttp + logging-interceptor + ${okhttp-version} - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} + com.google.code.gson + gson + ${gson-version} joda-time @@ -154,13 +125,6 @@ ${jodatime-version} - - - com.brsanthu - migbase64 - 2.2 - - junit @@ -170,12 +134,15 @@ - UTF-8 - 1.5.8 - 1.19.1 - 2.7.5 - 2.9.4 + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.7.5 + 2.6.2 + 2.9.3 1.0.0 4.12 + UTF-8 diff --git a/samples/client/petstore/java/default/settings.gradle b/samples/client/petstore/java/jersey1/settings.gradle similarity index 100% rename from samples/client/petstore/java/default/settings.gradle rename to samples/client/petstore/java/jersey1/settings.gradle diff --git a/samples/client/petstore/java/default/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/java/default/src/main/AndroidManifest.xml rename to samples/client/petstore/java/jersey1/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..3ca33cf8017 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,74 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API downlond processing. + * + * @param bytesRead bytes Read + * @param contentLength content lenngth of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..0204c5c96aa --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,1324 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import okio.BufferedSink; +import okio.Okio; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + public static final double JAVA_VERSION; + public static final boolean IS_ANDROID; + public static final int ANDROID_SDK_VERSION; + + static { + JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); + boolean isAndroid; + try { + Class.forName("android.app.Activity"); + isAndroid = true; + } catch (ClassNotFoundException e) { + isAndroid = false; + } + IS_ANDROID = isAndroid; + int sdkVersion = 0; + if (IS_ANDROID) { + try { + sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); + } catch (Exception e) { + try { + sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); + } catch (Exception e2) { } + } + } + ANDROID_SDK_VERSION = sdkVersion; + } + + /** + * The datetime format to be used when lenientDatetimeFormat is enabled. + */ + public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /* + * Constructor for ApiClient + */ + public ApiClient() { + httpClient = new OkHttpClient(); + + verifyingSsl = true; + + json = new JSON(this); + + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + initDatetimeFormat(); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; + + // Set default User-Agent. + setUserAgent("Swagger-Codegen/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get base path + * + * @return Baes path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client + * + * @param httpClient An instance of OkHttpClient + * @return Api Client + */ + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + public DateFormat getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + this.dateLength = this.dateFormat.format(new Date()).length(); + return this; + } + + public DateFormat getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { + this.datetimeFormat = datetimeFormat; + return this; + } + + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + * @return True if lenientDatetimeFormat flag is set to true + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + * @param str String to be parsed + * @return Date + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see ISO 8601 + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + DateFormat format; + if (lenientDatetimeFormat) { + /* + * When lenientDatetimeFormat is enabled, normalize the date string + * into LENIENT_DATETIME_FORMAT to support various formats + * defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); + } else { + format = this.datetimeFormat; + } + + try { + return format.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /* + * Parse date or date time in string format into Date object. + * + * @param str Date time string to be parsed + * @return Date representation of the string + */ + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string (Date format). + * + * @param date Date object + * @return Formatted date in string representation + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given Date object into string (Datetime format). + * + * @param date Date object + * @return Formatted datetime in string representation + */ + public String formatDatetime(Date date) { + return datetimeFormat.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see setLenient + * + * @return True if lenientOnJson is enabled, false otherwise. + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + /** + * Set LenientOnJson + * + * @param lenient True to enable lenientOnJson + * @return ApiClient + */ + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the tempoaray folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.getConnectTimeout(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); + return this; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Format to {@code Pair} objects. + * + * @param collectionFormat collection format (e.g. csv, tsv) + * @param name Name + * @param value Value + * @return A list of Pair objects + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create(MediaType.parse(contentType), (File) obj); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(MediaType.parse(contentType), content); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @throws IOException If fail to prepare file for download + * @return Prepared file for the download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @throws ApiException If fail to execute the call + * @return ApiResponse<T> + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @throws ApiException If the response has a unsuccessful status code or + * fail to deserialize the response body + * @return Type + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param progressRequestListener Progress request listener + * @return The HTTP call + * @throws ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) { + contentType = "application/json"; + } + + RequestBody reqBody; + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = serialize(body, contentType); + } + + Request request = null; + + if(progressRequestListener != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the ofrm of Map + * @param reqBuilder Reqeust.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. + */ + private void initDatetimeFormat() { + String formatWithTimeZone = null; + if (IS_ANDROID) { + if (ANDROID_SDK_VERSION >= 18) { + // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; + } + } else if (JAVA_VERSION >= 1.7) { + // The time zone format "XXX" is available since Java 1.7 + formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; + } + if (formatWithTimeZone != null) { + this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); + // NOTE: Use the system's default time zone (mainly for datetime formatting). + } else { + // Use a common format that works across all systems. + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + // Always use the UTC time zone as we are using a constant trailing "Z" here. + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java new file mode 100644 index 00000000000..d7dde1ee939 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiResponse.java @@ -0,0 +1,71 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param T The type of data that is deserialized from response body + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + public int getStatusCode() { + return statusCode; + } + + public Map> getHeaders() { + return headers; + } + + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Configuration.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..a0b9c9c1cf0 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,236 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + /** + * JSON constructor. + * + * @param apiClient An instance of ApiClient + */ + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) + .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + /** + * Constructor for DateAdapter + * + * @param apiClient Api client + */ + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + /** + * Serialize + * + * @param src Date + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Json Element + */ + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + /** + * Deserialize + * + * @param json Json element + * @param date Type + * @param typeOfSrc Type + * @param context Json Serialization Context + * @return Date + * @throw JsonParseException if fail to parse + */ + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} + +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java new file mode 100644 index 00000000000..d9ca742ecd2 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + public interface ProgressRequestListener { + void onRequestProgress(long bytesWritten, long contentLength, boolean done); + } + + private final RequestBody requestBody; + + private final ProgressRequestListener progressListener; + + private BufferedSink bufferedSink; + + public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { + this.requestBody = requestBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (bufferedSink == null) { + bufferedSink = Okio.buffer(sink(sink)); + } + + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java new file mode 100644 index 00000000000..f8af685999d --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -0,0 +1,88 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + public interface ProgressListener { + void update(long bytesRead, long contentLength, boolean done); + } + + private final ResponseBody responseBody; + private final ProgressListener progressListener; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { + this.responseBody = responseBody; + this.progressListener = progressListener; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() throws IOException { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} + + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/StringUtil.java diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..52dce361e2a --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,353 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'string' is set + if (string == null) { + throw new ApiException("Missing the required parameter 'string' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param string None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumQueryParameters */ + private com.squareup.okhttp.Call testEnumQueryParametersCall(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (enumQueryString != null) + localVarFormParams.put("enum_query_string", enumQueryString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumQueryParameters(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumQueryParametersWithHttpInfo(enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum query parameters + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumQueryParametersWithHttpInfo(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum query parameters (asynchronously) + * + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumQueryParametersAsync(String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumQueryParametersCall(enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..2039a8842c1 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,935 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..0768744c263 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,482 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..1c4fc3101a1 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,907 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/ApiKeyAuth.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/Authentication.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 59% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 592648b2bba..4eb2300b69d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,44 +27,40 @@ package io.swagger.client.auth; import io.swagger.client.Pair; -import com.migcomponents.migbase64.Base64; +import com.squareup.okhttp.Credentials; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; - public class HttpBasicAuth implements Authentication { - private String username; - private String password; + 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; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - if (username == null && password == null) { - return; + public String getUsername() { + return username; } - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); } - } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuth.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuthFlow.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/auth/OAuthFlow.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 1e2d40891a2..1943e013fa1 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,10 +39,10 @@ import java.util.Map; */ public class AdditionalPropertiesClass { - @JsonProperty("map_property") + @SerializedName("map_property") private Map mapProperty = new HashMap(); - @JsonProperty("map_of_map_property") + @SerializedName("map_of_map_property") private Map> mapOfMapProperty = new HashMap>(); public AdditionalPropertiesClass mapProperty(Map mapProperty) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 3ed2c6d9660..ba3806dc875 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ import io.swagger.annotations.ApiModelProperty; */ public class Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; public Animal className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java similarity index 100% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/AnimalFarm.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 4d0dc41ee70..5446c2c439b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ import java.util.List; */ public class ArrayOfArrayOfNumberOnly { - @JsonProperty("ArrayArrayNumber") + @SerializedName("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index bd3f05a2ad4..c9257a5d3ee 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,7 +39,7 @@ import java.util.List; */ public class ArrayOfNumberOnly { - @JsonProperty("ArrayNumber") + @SerializedName("ArrayNumber") private List arrayNumber = new ArrayList(); public ArrayOfNumberOnly arrayNumber(List arrayNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java index 900b8375eb0..8d58870bcdc 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.ReadOnlyFirst; @@ -39,13 +39,13 @@ import java.util.List; */ public class ArrayTest { - @JsonProperty("array_of_string") + @SerializedName("array_of_string") private List arrayOfString = new ArrayList(); - @JsonProperty("array_array_of_integer") + @SerializedName("array_array_of_integer") private List> arrayArrayOfInteger = new ArrayList>(); - @JsonProperty("array_array_of_model") + @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); public ArrayTest arrayOfString(List arrayOfString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java index f39b159f0b4..21ed0f4c26b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Cat.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ import io.swagger.client.model.Animal; */ public class Cat extends Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; - @JsonProperty("declawed") + @SerializedName("declawed") private Boolean declawed = null; public Cat className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java index c9bbbf525c5..2178a866f62 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Category.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ import io.swagger.annotations.ApiModelProperty; */ public class Category { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; public Category id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java index dbcd1a7207b..4ba5804553f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Dog.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -37,13 +37,13 @@ import io.swagger.client.model.Animal; */ public class Dog extends Animal { - @JsonProperty("className") + @SerializedName("className") private String className = null; - @JsonProperty("color") + @SerializedName("color") private String color = "red"; - @JsonProperty("breed") + @SerializedName("breed") private String breed = null; public Dog className(String className) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java similarity index 91% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java index 4433dca5f48..73484907229 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumClass.java @@ -26,6 +26,7 @@ package io.swagger.client.model; import java.util.Objects; +import com.google.gson.annotations.SerializedName; /** @@ -33,10 +34,13 @@ import java.util.Objects; */ public enum EnumClass { + @SerializedName("_abc") _ABC("_abc"), + @SerializedName("-efg") _EFG("-efg"), + @SerializedName("(xyz)") _XYZ_("(xyz)"); private String value; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java similarity index 93% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index de36ef40ed4..9aad1223215 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -40,8 +40,10 @@ public class EnumTest { * Gets or Sets enumString */ public enum EnumStringEnum { + @SerializedName("UPPER") UPPER("UPPER"), + @SerializedName("lower") LOWER("lower"); private String value; @@ -56,15 +58,17 @@ public class EnumTest { } } - @JsonProperty("enum_string") + @SerializedName("enum_string") private EnumStringEnum enumString = null; /** * Gets or Sets enumInteger */ public enum EnumIntegerEnum { + @SerializedName("1") NUMBER_1(1), + @SerializedName("-1") NUMBER_MINUS_1(-1); private Integer value; @@ -79,15 +83,17 @@ public class EnumTest { } } - @JsonProperty("enum_integer") + @SerializedName("enum_integer") private EnumIntegerEnum enumInteger = null; /** * Gets or Sets enumNumber */ public enum EnumNumberEnum { + @SerializedName("1.1") NUMBER_1_DOT_1(1.1), + @SerializedName("-1.2") NUMBER_MINUS_1_DOT_2(-1.2); private Double value; @@ -102,7 +108,7 @@ public class EnumTest { } } - @JsonProperty("enum_number") + @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; public EnumTest enumString(EnumStringEnum enumString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index 9e17949ebc8..91109681509 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -39,43 +39,43 @@ import org.joda.time.LocalDate; */ public class FormatTest { - @JsonProperty("integer") + @SerializedName("integer") private Integer integer = null; - @JsonProperty("int32") + @SerializedName("int32") private Integer int32 = null; - @JsonProperty("int64") + @SerializedName("int64") private Long int64 = null; - @JsonProperty("number") + @SerializedName("number") private BigDecimal number = null; - @JsonProperty("float") + @SerializedName("float") private Float _float = null; - @JsonProperty("double") + @SerializedName("double") private Double _double = null; - @JsonProperty("string") + @SerializedName("string") private String string = null; - @JsonProperty("byte") + @SerializedName("byte") private byte[] _byte = null; - @JsonProperty("binary") + @SerializedName("binary") private byte[] binary = null; - @JsonProperty("date") + @SerializedName("date") private LocalDate date = null; - @JsonProperty("dateTime") + @SerializedName("dateTime") private DateTime dateTime = null; - @JsonProperty("uuid") + @SerializedName("uuid") private String uuid = null; - @JsonProperty("password") + @SerializedName("password") private String password = null; public FormatTest integer(Integer integer) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index a3d01218197..d77fc7ac36b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ import io.swagger.annotations.ApiModelProperty; */ public class HasOnlyReadOnly { - @JsonProperty("bar") + @SerializedName("bar") private String bar = null; - @JsonProperty("foo") + @SerializedName("foo") private String foo = null; /** diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java index 6c0fc91ac41..61bdb6b2c65 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; @@ -39,15 +39,17 @@ import java.util.Map; */ public class MapTest { - @JsonProperty("map_map_of_string") + @SerializedName("map_map_of_string") private Map> mapMapOfString = new HashMap>(); /** * Gets or Sets inner */ public enum InnerEnum { + @SerializedName("UPPER") UPPER("UPPER"), + @SerializedName("lower") LOWER("lower"); private String value; @@ -62,7 +64,7 @@ public class MapTest { } } - @JsonProperty("map_of_enum_string") + @SerializedName("map_of_enum_string") private Map mapOfEnumString = new HashMap(); public MapTest mapMapOfString(Map> mapMapOfString) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c37d141f972..6e587b1bf97 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; @@ -41,13 +41,13 @@ import org.joda.time.DateTime; */ public class MixedPropertiesAndAdditionalPropertiesClass { - @JsonProperty("uuid") + @SerializedName("uuid") private String uuid = null; - @JsonProperty("dateTime") + @SerializedName("dateTime") private DateTime dateTime = null; - @JsonProperty("map") + @SerializedName("map") private Map map = new HashMap(); public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java index 3f4edf12daa..d8da58aca9c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Model200Response.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,10 +37,10 @@ import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "Model for testing model name starting with number") public class Model200Response { - @JsonProperty("name") + @SerializedName("name") private Integer name = null; - @JsonProperty("class") + @SerializedName("class") private String PropertyClass = null; public Model200Response name(Integer name) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java index 7b86d07a148..2a823298323 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,13 +36,13 @@ import io.swagger.annotations.ApiModelProperty; */ public class ModelApiResponse { - @JsonProperty("code") + @SerializedName("code") private Integer code = null; - @JsonProperty("type") + @SerializedName("type") private String type = null; - @JsonProperty("message") + @SerializedName("message") private String message = null; public ModelApiResponse code(Integer code) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java index e8762f850db..024a9c0df1c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ModelReturn.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,7 +37,7 @@ import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "Model for testing reserved words") public class ModelReturn { - @JsonProperty("return") + @SerializedName("return") private Integer _return = null; public ModelReturn _return(Integer _return) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java index de446cdf30d..318a2ddd50e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Name.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -37,16 +37,16 @@ import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "Model for testing model name same as property name") public class Name { - @JsonProperty("name") + @SerializedName("name") private Integer name = null; - @JsonProperty("snake_case") + @SerializedName("snake_case") private Integer snakeCase = null; - @JsonProperty("property") + @SerializedName("property") private String property = null; - @JsonProperty("123Number") + @SerializedName("123Number") private Integer _123Number = null; public Name name(Integer name) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java index 88c33f00f02..9b9ca048dfb 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/NumberOnly.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; @@ -37,7 +37,7 @@ import java.math.BigDecimal; */ public class NumberOnly { - @JsonProperty("JustNumber") + @SerializedName("JustNumber") private BigDecimal justNumber = null; public NumberOnly justNumber(BigDecimal justNumber) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java similarity index 94% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java index ddebd7f8e48..90cfd2f3892 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Order.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; @@ -37,26 +37,29 @@ import org.joda.time.DateTime; */ public class Order { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("petId") + @SerializedName("petId") private Long petId = null; - @JsonProperty("quantity") + @SerializedName("quantity") private Integer quantity = null; - @JsonProperty("shipDate") + @SerializedName("shipDate") private DateTime shipDate = null; /** * Order Status */ public enum StatusEnum { + @SerializedName("placed") PLACED("placed"), + @SerializedName("approved") APPROVED("approved"), + @SerializedName("delivered") DELIVERED("delivered"); private String value; @@ -71,10 +74,10 @@ public class Order { } } - @JsonProperty("status") + @SerializedName("status") private StatusEnum status = null; - @JsonProperty("complete") + @SerializedName("complete") private Boolean complete = false; public Order id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java similarity index 94% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java index b468ebf1237..b80fdeaf923 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Pet.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Category; @@ -40,29 +40,32 @@ import java.util.List; */ public class Pet { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("category") + @SerializedName("category") private Category category = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; - @JsonProperty("photoUrls") + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); - @JsonProperty("tags") + @SerializedName("tags") private List tags = new ArrayList(); /** * pet status in the store */ public enum StatusEnum { + @SerializedName("available") AVAILABLE("available"), + @SerializedName("pending") PENDING("pending"), + @SerializedName("sold") SOLD("sold"); private String value; @@ -77,7 +80,7 @@ public class Pet { } } - @JsonProperty("status") + @SerializedName("status") private StatusEnum status = null; public Pet id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 7f56ef2ff35..13b729bb94d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ import io.swagger.annotations.ApiModelProperty; */ public class ReadOnlyFirst { - @JsonProperty("bar") + @SerializedName("bar") private String bar = null; - @JsonProperty("baz") + @SerializedName("baz") private String baz = null; /** diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java index bc4863f101a..b46b8367a01 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,7 +36,7 @@ import io.swagger.annotations.ApiModelProperty; */ public class SpecialModelName { - @JsonProperty("$special[property.name]") + @SerializedName("$special[property.name]") private Long specialPropertyName = null; public SpecialModelName specialPropertyName(Long specialPropertyName) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java similarity index 96% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java index f27e45ea2aa..e56eb535d1e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Tag.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,10 +36,10 @@ import io.swagger.annotations.ApiModelProperty; */ public class Tag { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("name") + @SerializedName("name") private String name = null; public Tag id(Long id) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java similarity index 95% rename from samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java index 7c0421fa09e..6c1ed6ceacc 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/User.java @@ -26,7 +26,7 @@ package io.swagger.client.model; import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -36,28 +36,28 @@ import io.swagger.annotations.ApiModelProperty; */ public class User { - @JsonProperty("id") + @SerializedName("id") private Long id = null; - @JsonProperty("username") + @SerializedName("username") private String username = null; - @JsonProperty("firstName") + @SerializedName("firstName") private String firstName = null; - @JsonProperty("lastName") + @SerializedName("lastName") private String lastName = null; - @JsonProperty("email") + @SerializedName("email") private String email = null; - @JsonProperty("password") + @SerializedName("password") private String password = null; - @JsonProperty("phone") + @SerializedName("phone") private String phone = null; - @JsonProperty("userStatus") + @SerializedName("userStatus") private Integer userStatus = null; public User id(Long id) { diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..5a7d2e5aa80 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,92 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import org.joda.time.LocalDate; +import org.joda.time.DateTime; +import java.math.BigDecimal; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String string = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + + // TODO: test validations + } + + /** + * To test enum query parameters + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumQueryParametersTest() throws ApiException { + String enumQueryString = null; + BigDecimal enumQueryInteger = null; + Double enumQueryDouble = null; + // api.testEnumQueryParameters(enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..373f7d287ad --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,180 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Pet; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet body = null; + // api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + // api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet body = null; + // api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + // api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..4bcdcbf8338 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,108 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + // api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..832748dbb45 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,174 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private final UserApi api = new UserApi(); + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + // api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + // api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + // api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + // api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + // api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + // api.updateUser(username, body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md index 2cd4b9d33f9..9feee16427f 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/ArrayTest.md @@ -7,13 +7,6 @@ Name | Type | Description | Notes **arrayOfString** | **List<String>** | | [optional] **arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] **arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] -**arrayOfEnum** | [**List<ArrayOfEnumEnum>**](#List<ArrayOfEnumEnum>) | | [optional] - - - -## Enum: List<ArrayOfEnumEnum> -Name | Value ----- | ----- diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index bb52256e6be..21a4db7c377 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,53 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection =end [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumQueryParameters**](FakeApi.md#testEnumQueryParameters) | **GET** /fake | To test enum query parameters - -# **testCodeInjectEnd** -> testCodeInjectEnd(testCodeInjectEnd) - -To test code injection =end - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeApi; - - -FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection =end -try { - apiInstance.testCodeInjectEnd(testCodeInjectEnd); -} catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection =end | [optional] - -### Return type - -null (empty response body) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json, */ =end'));(phpinfo(' - - **Accept**: application/json, */ end - # **testEndpointParameters** > testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 0204c5c96aa..b7b04e3e4c5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -812,6 +812,7 @@ public class ApiClient { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -1006,6 +1007,7 @@ public class ApiClient { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index a0b9c9c1cf0..540611eab9d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -103,6 +103,7 @@ public class JSON { * @param returnType The type to deserialize inot * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 6d956441b6f..52dce361e2a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -67,105 +67,6 @@ public class FakeApi { this.apiClient = apiClient; } - /* Build call for testCodeInjectEnd */ - private com.squareup.okhttp.Call testCodeInjectEndCall(String testCodeInjectEnd, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (testCodeInjectEnd != null) - localVarFormParams.put("test code inject */ =end", testCodeInjectEnd); - - final String[] localVarAccepts = { - "application/json", "*/ end" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "*/ =end'));(phpinfo('" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testCodeInjectEnd(String testCodeInjectEnd) throws ApiException { - testCodeInjectEndWithHttpInfo(testCodeInjectEnd); - } - - /** - * To test code injection =end - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testCodeInjectEndWithHttpInfo(String testCodeInjectEnd) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, null, null); - return apiClient.execute(call); - } - - /** - * To test code injection =end (asynchronously) - * - * @param testCodeInjectEnd To test code injection =end (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testCodeInjectEndAsync(String testCodeInjectEnd, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } /* Build call for testEndpointParameters */ private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String string, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, byte[] binary, LocalDate date, DateTime dateTime, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index b853a0b035a..8d58870bcdc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,31 +48,6 @@ public class ArrayTest { @SerializedName("array_array_of_model") private List> arrayArrayOfModel = new ArrayList>(); - /** - * Gets or Sets arrayOfEnum - */ - public enum ArrayOfEnumEnum { - @SerializedName("UPPER") - UPPER("UPPER"), - - @SerializedName("lower") - LOWER("lower"); - - private String value; - - ArrayOfEnumEnum(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - } - - @SerializedName("array_of_enum") - private List arrayOfEnum = new ArrayList(); - public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; return this; @@ -127,24 +102,6 @@ public class ArrayTest { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - return this; - } - - /** - * Get arrayOfEnum - * @return arrayOfEnum - **/ - @ApiModelProperty(example = "null", value = "") - public List getArrayOfEnum() { - return arrayOfEnum; - } - - public void setArrayOfEnum(List arrayOfEnum) { - this.arrayOfEnum = arrayOfEnum; - } - @Override public boolean equals(java.lang.Object o) { @@ -157,13 +114,12 @@ public class ArrayTest { ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel) && - Objects.equals(this.arrayOfEnum, arrayTest.arrayOfEnum); + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, arrayOfEnum); + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override @@ -174,7 +130,6 @@ public class ArrayTest { sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append(" arrayOfEnum: ").append(toIndentedString(arrayOfEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/typescript-node/npm/api.d.ts b/samples/client/petstore/typescript-node/npm/api.d.ts index 8d1bd4acbb5..2399bc3a4f5 100644 --- a/samples/client/petstore/typescript-node/npm/api.d.ts +++ b/samples/client/petstore/typescript-node/npm/api.d.ts @@ -82,8 +82,8 @@ export declare class PetApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean; @@ -132,8 +132,8 @@ export declare class StoreApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean; @@ -168,8 +168,8 @@ export declare class UserApi { protected _useQuerystring: boolean; protected authentications: { 'default': Authentication; - 'petstore_auth': OAuth; 'api_key': ApiKeyAuth; + 'petstore_auth': OAuth; }; constructor(basePath?: string); useQuerystring: boolean;