From 112a7ec8c1c80d187f4fbb0e7bafbe419fa1b3bf Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 3 Aug 2015 18:33:42 +0800 Subject: [PATCH 01/11] Java client: move form params handling to ApiClient --- .../main/resources/Java/ApiClient.mustache | 113 +++++++++--------- .../src/main/resources/Java/api.mustache | 35 +----- 2 files changed, 63 insertions(+), 85 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index fb4351d444de..7a52b0016848 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -11,7 +11,9 @@ import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.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; @@ -29,6 +31,7 @@ import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; +import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; @@ -398,7 +401,7 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -424,90 +427,90 @@ public class ApiClient { else builder = client.resource(basePath + path + querystring).accept(accept); - for(String key : headerParams.keySet()) { + for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } - for(String key : defaultHeaderMap.keySet()) { - if(!headerParams.containsKey(key)) { + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { builder = builder.header(key, defaultHeaderMap.get(key)); } } + String encodedFormParams = null; + 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.field(param.getKey(), file.getName()); + 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); + } + } + body = mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); + } + ClientResponse response = null; - if("GET".equals(method)) { + if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); - } - else if ("POST".equals(method)) { - if (contentType.startsWith("application/x-www-form-urlencoded")) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).post(ClientResponse.class, - encodedFormParams); + } else if ("POST".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); } else if (body == null) { response = builder.post(ClientResponse.class, null); - } else if(body instanceof FormDataMultiPart) { + } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); - } - else + } else { response = builder.type(contentType).post(ClientResponse.class, serialize(body)); - } - else if ("PUT".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).put(ClientResponse.class, - encodedFormParams); + } + } else if ("PUT".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); } else if(body == null) { response = builder.put(ClientResponse.class, serialize(body)); } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + response = builder.type(contentType).put(ClientResponse.class, serialize(body)); } - } - else if ("DELETE".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).delete(ClientResponse.class, - encodedFormParams); + } else if ("DELETE".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); } else if(body == null) { response = builder.delete(ClientResponse.class); } else { response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); } - } - else { + } else { throw new ApiException(500, "unknown method type " + method); } - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (response.hasEntity()) { return (String) response.getEntity(String.class); - } - else { + } else { return ""; } - } - else { + } else { String message = "error"; String respBody = null; - if(response.hasEntity()) { - try{ + if (response.hasEntity()) { + try { respBody = String.valueOf(response.getEntity(String.class)); message = respBody; - } - catch (RuntimeException e) { + } catch (RuntimeException e) { // e.printStackTrace(); } } throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); } } @@ -527,15 +530,14 @@ public class ApiClient { /** * Encode the given form parameters as request body. */ - private String getXWWWFormUrlencodedParams(Map formParams) { + private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); - for (Entry param : formParams.entrySet()) { - String keyStr = parameterToString(param.getKey()); + for (Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) .append("=") .append(URLEncoder.encode(valueStr, "utf8")); formParamBuilder.append("&"); @@ -543,11 +545,12 @@ public class ApiClient { // move on to next } } + String encodedFormParams = formParamBuilder.toString(); if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, - encodedFormParams.length() - 1); + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); } + return encodedFormParams; } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 39b71dbff9a5..29a56119e768 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -12,11 +12,6 @@ import java.util.*; {{#imports}}import {{import}}; {{/imports}} -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; @@ -64,7 +59,7 @@ public class {{classname}} { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); {{#queryParams}} queryParams.addAll(apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); @@ -74,6 +69,10 @@ public class {{classname}} { headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) + formParams.put("{{baseName}}", {{paramName}}); + {{/formParams}} + final String[] accepts = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; @@ -84,30 +83,6 @@ public class {{classname}} { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - {{#formParams}}{{#notFile}} - if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); - } - {{/notFile}}{{#isFile}} - if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", {{paramName}}.getName()); - mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); - } - {{/isFile}}{{/formParams}} - if(hasFields) - postBody = mp; - } - else { - {{#formParams}}{{#notFile}}if ({{paramName}} != null) - formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} - {{/formParams}} - } - try { String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); From bfb4629ab78542bb4566ee58922bfbf1f2a1a5ce Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 4 Aug 2015 15:47:55 +0800 Subject: [PATCH 02/11] Java client: decouple JSON handling --- .../codegen/languages/JavaClientCodegen.java | 5 +- .../main/resources/Java/ApiClient.mustache | 87 ++++++++----------- .../src/main/resources/Java/JSON.mustache | 51 +++++++++++ .../src/main/resources/Java/JsonUtil.mustache | 23 ----- .../src/main/resources/Java/TypeRef.mustache | 25 ++++++ .../src/main/resources/Java/api.mustache | 20 ++--- 6 files changed, 124 insertions(+), 87 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/JSON.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache 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 f272343a7955..88266aa76cc1 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 @@ -116,9 +116,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 7a52b0016848..b356dd365583 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,9 +1,7 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; @@ -48,6 +46,7 @@ public class ApiClient { private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "{{basePath}}"; + private JSON json = new JSON(); private Map authentications; @@ -340,50 +339,38 @@ public class ApiClient { } /** - * Deserialize the given JSON string to Java object. - * - * @param json The JSON string - * @param containerType The container type, one of "list", "array" or "" - * @param cls The type of the Java object - * @return The deserialized Java object + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). */ - public Object deserialize(String json, String containerType, Class cls) throws ApiException { - if(null != containerType) { - containerType = containerType.toLowerCase(); - } - try{ - if("list".equals(containerType) || "array".equals(containerType)) { - JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); - List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); - return response; - } - else if(String.class.equals(cls)) { - if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); - else - return json; - } - else { - return JsonUtil.getJsonMapper().readValue(json, cls); - } - } - catch (IOException e) { - throw new ApiException(500, e.getMessage(), null, json); + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return json.serialize(obj); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); } } /** - * Serialize the given Java object into JSON string. + * Deserialize response body to Java object according to the Content-Type. */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return JsonUtil.getJsonMapper().writeValueAsString(obj); - else - return null; - } - catch (Exception e) { - throw new ApiException(500, e.getMessage()); + public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = contentTypes.get(0); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.getEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); } } @@ -399,9 +386,10 @@ public class ApiClient { * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -465,15 +453,15 @@ public class ApiClient { } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body)); + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); } } else if ("PUT".equals(method)) { if (encodedFormParams != null) { response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body)); + response = builder.put(ClientResponse.class, serialize(body, contentType)); } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); } } else if ("DELETE".equals(method)) { if (encodedFormParams != null) { @@ -481,7 +469,7 @@ public class ApiClient { } else if(body == null) { response = builder.delete(ClientResponse.class); } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); } } else { throw new ApiException(500, "unknown method type " + method); @@ -490,11 +478,10 @@ public class ApiClient { if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if (response.hasEntity()) { - return (String) response.getEntity(String.class); - } else { - return ""; - } + if (returnType == null) + return null; + else + return deserialize(response, returnType); } else { String message = "error"; String respBody = null; diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache new file mode 100644 index 000000000000..842920f26621 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache @@ -0,0 +1,51 @@ +package {{invokerPackage}}; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache deleted file mode 100644 index 29d5f55eceea..000000000000 --- a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache +++ /dev/null @@ -1,23 +0,0 @@ -package {{invokerPackage}}; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.core.JsonGenerator.Feature; - -import com.fasterxml.jackson.datatype.joda.*; - -public class JsonUtil { - public static ObjectMapper mapper; - - static { - mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.registerModule(new JodaModule()); - } - - public static ObjectMapper getJsonMapper() { - return mapper; - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache new file mode 100644 index 000000000000..5de0b840aa73 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/TypeRef.mustache @@ -0,0 +1,25 @@ +package {{invokerPackage}}; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 29a56119e768..4168c3a173ab 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -4,6 +4,7 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; +import {{invokerPackage}}.TypeRef; import {{modelPackage}}.*; @@ -83,18 +84,13 @@ public class {{classname}} { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - try { - String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; - } - else { - return {{#returnType}}null{{/returnType}}; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + {{#returnType}} + TypeRef returnType = new TypeRef<{{{returnType}}}>() {}; + return apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + {{/returnType}}{{^returnType}} + apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + {{/returnType}} } {{/operation}} } From aff21e5e6b047e29ed99dff9a558a62afbab2869 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 4 Aug 2015 18:32:54 +0800 Subject: [PATCH 03/11] Add a "library" option to generate with sub-template --- .../java/io/swagger/codegen/cmd/Generate.java | 5 ++ .../io/swagger/codegen/AbstractGenerator.java | 4 ++ .../io/swagger/codegen/CodegenConfig.java | 7 +++ .../io/swagger/codegen/DefaultCodegen.java | 16 ++++++- .../io/swagger/codegen/DefaultGenerator.java | 48 ++++++++++++------- 5 files changed, 61 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 035fa1a21d35..1386ae469a9b 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -40,6 +40,10 @@ public class Generate implements Runnable { description = "client language to generate (maybe class name in classpath, required)") private String lang; + @Option(name = {"-L", "--library"}, title = "library", + description = "library template (sub-template) to use") + private String library; + @Option(name = {"-o", "--output"}, title = "output directory", description = "where to write the generated files (current dir by default)") private String output = ""; @@ -105,6 +109,7 @@ public class Generate implements Runnable { } CodegenConfig config = forName(lang); + config.setLibrary(library); config.setOutputDir(new File(output).getAbsolutePath()); if (null != templateDir) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index ac3771536252..0d530e7c959a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -60,6 +60,10 @@ public abstract class AbstractGenerator { throw new RuntimeException("can't load template " + name); } + public boolean templateExists(String name) { + return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; + } + public String getCPResourcePath(String name) { if (!"/".equals(File.separator)) { return name.replaceAll(Pattern.quote(File.separator), "/"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4ef8bb23e664..45c8cc5e9f83 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -108,4 +108,11 @@ public interface CodegenConfig { boolean isSkipOverwrite(); void setSkipOverwrite(boolean skipOverwrite); + + void setLibrary(String library); + + /** + * Library template (sub-template). + */ + String getLibrary(); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 0e3c3a34ef9b..aaf62b4a11b9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -81,6 +81,7 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance = false; + protected String library = null; public List cliOptions() { return cliOptions; @@ -1287,7 +1288,7 @@ public class DefaultCodegen { m.emptyVars = true; } } - + /** * Remove characters not suitable for variable or method name from the input and camelize it @@ -1308,7 +1309,7 @@ public class DefaultCodegen { name = name.substring(0, 1).toLowerCase() + name.substring(1); } return name; - } + } public static String camelize(String word) { return camelize(word, false); @@ -1387,4 +1388,15 @@ public class DefaultCodegen { public void setSkipOverwrite(boolean skipOverwrite) { this.skipOverwrite = skipOverwrite; } + + public void setLibrary(String library) { + this.library = library; + } + + /** + * Library template (sub-template). + */ + public String getLibrary() { + return library; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index d48238c24895..4feb75acf4ea 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -125,7 +125,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map definitions = swagger.getDefinitions(); if (definitions != null) { List sortedModelKeys = sortModelsByInheritance(definitions); - + for (String name : sortedModelKeys) { Model model = definitions.get(name); Map modelMap = new HashMap(); @@ -264,8 +264,22 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { continue; } - if (support.templateFile.endsWith("mustache")) { - String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + String templateFile = null; + String library = config.getLibrary(); + if (library != null) { + String libTemplateFile = config.templateDir() + File.separator + + "libraries" + File.separator + library + File.separator + + support.templateFile; + if (templateExists(libTemplateFile)) { + templateFile = libTemplateFile; + } + } + if (templateFile == null) { + templateFile = config.templateDir() + File.separator + support.templateFile; + } + + if (templateFile.endsWith("mustache")) { + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { public Reader getTemplate(String name) { @@ -281,12 +295,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { InputStream in = null; try { - in = new FileInputStream(config.templateDir() + File.separator + support.templateFile); + in = new FileInputStream(templateFile); } catch (Exception e) { // continue } if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(config.templateDir() + File.separator + support.templateFile)); + in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); } File outputFile = new File(outputFilename); OutputStream out = new FileOutputStream(outputFile, false); @@ -295,7 +309,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { IOUtils.copy(in, out); } else { if (in == null) { - System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input"); + System.out.println("can't open " + templateFile + " for input"); } if (out == null) { System.out.println("can't open " + outputFile + " for output"); @@ -333,7 +347,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put(flagFieldName, true); } } - + private List sortModelsByInheritance(final Map definitions) { List sortedModelKeys = new ArrayList(definitions.keySet()); Comparator cmp = new Comparator() { @@ -341,10 +355,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { public int compare(String o1, String o2) { Model model1 = definitions.get(o1); Model model2 = definitions.get(o2); - + int model1InheritanceDepth = getInheritanceDepth(model1); int model2InheritanceDepth = getInheritanceDepth(model2); - + if (model1InheritanceDepth == model2InheritanceDepth) { return 0; } else if (model1InheritanceDepth > model2InheritanceDepth) { @@ -353,30 +367,30 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return -1; } } - + private int getInheritanceDepth(Model model) { int inheritanceDepth = 0; Model parent = getParent(model); - + while (parent != null) { inheritanceDepth++; parent = getParent(parent); } - + return inheritanceDepth; } - + private Model getParent(Model model) { if (model instanceof ComposedModel) { return definitions.get(((ComposedModel) model).getParent().getReference()); } - + return null; } }; - + Collections.sort(sortedModelKeys, cmp); - + return sortedModelKeys; } @@ -445,7 +459,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } authMethods.put(securityName, oauth2Operation); } else { - authMethods.put(securityName, securityDefinition); + authMethods.put(securityName, securityDefinition); } } } From 7c16dfcf135272b5c617ac37ca898a6dd8ef9ba9 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 4 Aug 2015 18:36:03 +0800 Subject: [PATCH 04/11] Rebuild Java petstore sample --- .../java/io/swagger/client/ApiClient.java | 194 ++++++------ .../src/main/java/io/swagger/client/JSON.java | 51 +++ .../main/java/io/swagger/client/JsonUtil.java | 23 -- .../main/java/io/swagger/client/TypeRef.java | 25 ++ .../java/io/swagger/client/api/PetApi.java | 293 ++++-------------- .../java/io/swagger/client/api/StoreApi.java | 133 ++------ .../java/io/swagger/client/api/UserApi.java | 256 ++++----------- .../java/io/swagger/client/model/Pet.java | 2 +- 8 files changed, 328 insertions(+), 649 deletions(-) create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java delete mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 87ecc8312514..305f91ce7207 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -1,9 +1,7 @@ package io.swagger.client; -import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; @@ -11,7 +9,9 @@ import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.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; @@ -29,6 +29,7 @@ import java.util.TimeZone; import java.net.URLEncoder; import java.io.IOException; +import java.io.File; import java.io.UnsupportedEncodingException; import java.text.DateFormat; @@ -45,6 +46,7 @@ public class ApiClient { private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; + private JSON json = new JSON(); private Map authentications; @@ -336,50 +338,38 @@ public class ApiClient { } /** - * Deserialize the given JSON string to Java object. - * - * @param json The JSON string - * @param containerType The container type, one of "list", "array" or "" - * @param cls The type of the Java object - * @return The deserialized Java object + * Serialize the given Java object into string according the given + * Content-Type (only JSON is supported for now). */ - public Object deserialize(String json, String containerType, Class cls) throws ApiException { - if(null != containerType) { - containerType = containerType.toLowerCase(); - } - try{ - if("list".equals(containerType) || "array".equals(containerType)) { - JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); - List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); - return response; - } - else if(String.class.equals(cls)) { - if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); - else - return json; - } - else { - return JsonUtil.getJsonMapper().readValue(json, cls); - } - } - catch (IOException e) { - throw new ApiException(500, e.getMessage(), null, json); + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return json.serialize(obj); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); } } /** - * Serialize the given Java object into JSON string. + * Deserialize response body to Java object according to the Content-Type. */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return JsonUtil.getJsonMapper().writeValueAsString(obj); - else - return null; - } - catch (Exception e) { - throw new ApiException(500, e.getMessage()); + public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = contentTypes.get(0); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.getEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); } } @@ -395,9 +385,10 @@ public class ApiClient { * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response * @return The response body in type of string */ - public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -423,90 +414,89 @@ public class ApiClient { else builder = client.resource(basePath + path + querystring).accept(accept); - for(String key : headerParams.keySet()) { + for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } - for(String key : defaultHeaderMap.keySet()) { - if(!headerParams.containsKey(key)) { + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { builder = builder.header(key, defaultHeaderMap.get(key)); } } + String encodedFormParams = null; + 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.field(param.getKey(), file.getName()); + 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); + } + } + body = mp; + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); + } + ClientResponse response = null; - if("GET".equals(method)) { + if ("GET".equals(method)) { response = (ClientResponse) builder.get(ClientResponse.class); - } - else if ("POST".equals(method)) { - if (contentType.startsWith("application/x-www-form-urlencoded")) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).post(ClientResponse.class, - encodedFormParams); + } else if ("POST".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); } else if (body == null) { response = builder.post(ClientResponse.class, null); - } else if(body instanceof FormDataMultiPart) { + } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); - } - else - response = builder.type(contentType).post(ClientResponse.class, serialize(body)); - } - else if ("PUT".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).put(ClientResponse.class, - encodedFormParams); - } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body)); } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); } - } - else if ("DELETE".equals(method)) { - if ("application/x-www-form-urlencoded".equals(contentType)) { - String encodedFormParams = this - .getXWWWFormUrlencodedParams(formParams); - response = builder.type(contentType).delete(ClientResponse.class, - encodedFormParams); + } else if ("PUT".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); + } else if(body == null) { + response = builder.put(ClientResponse.class, serialize(body, contentType)); + } else { + response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + if (encodedFormParams != null) { + response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); } else if(body == null) { response = builder.delete(ClientResponse.class); } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); + response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); } - } - else { + } else { throw new ApiException(500, "unknown method type " + method); } - if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; - } - else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if(response.hasEntity()) { - return (String) response.getEntity(String.class); - } - else { - return ""; - } - } - else { + } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { String message = "error"; String respBody = null; - if(response.hasEntity()) { - try{ + if (response.hasEntity()) { + try { respBody = String.valueOf(response.getEntity(String.class)); message = respBody; - } - catch (RuntimeException e) { + } catch (RuntimeException e) { // e.printStackTrace(); } } throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); + response.getStatusInfo().getStatusCode(), + message, + response.getHeaders(), + respBody); } } @@ -526,15 +516,14 @@ public class ApiClient { /** * Encode the given form parameters as request body. */ - private String getXWWWFormUrlencodedParams(Map formParams) { + private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); - for (Entry param : formParams.entrySet()) { - String keyStr = parameterToString(param.getKey()); + for (Entry param : formParams.entrySet()) { + String keyStr = param.getKey(); String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) + formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) .append("=") .append(URLEncoder.encode(valueStr, "utf8")); formParamBuilder.append("&"); @@ -542,11 +531,12 @@ public class ApiClient { // move on to next } } + String encodedFormParams = formParamBuilder.toString(); if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, - encodedFormParams.length() - 1); + encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); } + return encodedFormParams; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..4c1fa53430b2 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java deleted file mode 100644 index 8e7e686dd0ce..000000000000 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.core.JsonGenerator.Feature; - -import com.fasterxml.jackson.datatype.joda.*; - -public class JsonUtil { - public static ObjectMapper mapper; - - static { - mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.registerModule(new JodaModule()); - } - - public static ObjectMapper getJsonMapper() { - return mapper; - } -} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java new file mode 100644 index 000000000000..6081df1082fa --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java @@ -0,0 +1,25 @@ +package io.swagger.client; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index c9b7a2a917a6..c1657233fdc1 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,11 +13,6 @@ import java.util.*; import io.swagger.client.model.Pet; import java.io.File; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; @@ -57,7 +53,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -73,29 +71,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -114,7 +93,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -130,29 +111,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -171,7 +133,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -179,6 +141,8 @@ public class PetApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -189,29 +153,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (List) apiClient.deserialize(response, "array", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -230,7 +176,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -238,6 +184,8 @@ public class PetApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -248,29 +196,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (List) apiClient.deserialize(response, "array", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -295,7 +225,9 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -311,29 +243,11 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key", "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Pet) apiClient.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth", "api_key" }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -360,12 +274,18 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + final String[] accepts = { "application/json", "application/xml" }; @@ -376,43 +296,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (name != null) { - hasFields = true; - mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (status != null) { - hasFields = true; - mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if(hasFields) - postBody = mp; - } - else { - if (name != null) - formParams.put("name", apiClient.parameterToString(name)); - if (status != null) - formParams.put("status", apiClient.parameterToString(status)); - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -438,7 +325,7 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); @@ -446,6 +333,8 @@ public class PetApi { headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + final String[] accepts = { "application/json", "application/xml" }; @@ -456,29 +345,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -505,12 +375,18 @@ public class PetApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + final String[] accepts = { "application/json", "application/xml" }; @@ -521,43 +397,10 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (additionalMetadata != null) { - hasFields = true; - mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (file != null) { - hasFields = true; - mp.field("file", file.getName()); - mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } - - if(hasFields) - postBody = mp; - } - else { - if (additionalMetadata != null) - formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata)); - - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java index 498b6d4a6b89..6a0c014f266d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,11 +13,6 @@ import java.util.*; import java.util.Map; import io.swagger.client.model.Order; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; @@ -56,7 +52,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -72,29 +70,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Map) apiClient.deserialize(response, "map", Map.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { "api_key" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -113,7 +93,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -129,29 +111,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Order) apiClient.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -176,7 +140,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -192,29 +158,11 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Order) apiClient.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -239,7 +187,9 @@ public class StoreApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -255,29 +205,10 @@ public class StoreApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index 3bff204ac02b..0d408637cea8 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; import io.swagger.client.Pair; +import io.swagger.client.TypeRef; import io.swagger.client.model.*; @@ -12,11 +13,6 @@ import java.util.*; import io.swagger.client.model.User; import java.util.*; -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.MediaType; - import java.io.File; import java.util.Map; import java.util.HashMap; @@ -57,7 +53,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -73,29 +71,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -114,7 +93,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -130,29 +111,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -171,7 +133,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -187,29 +151,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -229,7 +174,7 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -239,6 +184,8 @@ public class UserApi { + + final String[] accepts = { "application/json", "application/xml" }; @@ -249,29 +196,11 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (String) apiClient.deserialize(response, "", String.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -289,7 +218,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -305,29 +236,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -352,7 +264,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -368,29 +282,11 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (User) apiClient.deserialize(response, "", User.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + } /** @@ -416,7 +312,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -432,29 +330,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } /** @@ -479,7 +358,9 @@ public class UserApi { // query params List queryParams = new ArrayList(); Map headerParams = new HashMap(); - Map formParams = new HashMap(); + Map formParams = new HashMap(); + + @@ -495,29 +376,10 @@ public class UserApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index d7c2038dead8..f5cdc5fb71f0 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; From d88ec847ae250ce74bb4e40f318216a065cf2958 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 5 Aug 2015 09:43:15 +0800 Subject: [PATCH 05/11] Remave unused imports --- .../src/main/resources/Java/ApiClient.mustache | 3 --- .../swagger-codegen/src/main/resources/Java/pom.mustache | 6 +++++- samples/client/petstore/java/pom.xml | 6 +++++- .../java/src/main/java/io/swagger/client/ApiClient.java | 3 --- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index b356dd365583..5e87f9e1a5af 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -1,8 +1,5 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; - import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 592edeec0518..315ea9e5b924 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -112,6 +112,8 @@ swagger-annotations ${swagger-annotations-version} + + com.sun.jersey jersey-client @@ -122,6 +124,8 @@ jersey-multipart ${jersey-version} + + com.fasterxml.jackson.core jackson-core @@ -141,7 +145,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda 2.1.5 - + joda-time joda-time diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 058733e08fcd..3cef1c564c91 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/pom.xml @@ -112,6 +112,8 @@ swagger-annotations ${swagger-annotations-version} + + com.sun.jersey jersey-client @@ -122,6 +124,8 @@ jersey-multipart ${jersey-version} + + com.fasterxml.jackson.core jackson-core @@ -141,7 +145,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda 2.1.5 - + joda-time joda-time diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 305f91ce7207..c02c9877df4b 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -1,8 +1,5 @@ package io.swagger.client; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; - import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.config.ClientConfig; From 4ba521a5c081996139bdb91c7838ede21e20a8db Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 5 Aug 2015 15:37:26 +0800 Subject: [PATCH 06/11] Add jersey2 library template for Java client --- .../Java/libraries/jersey2/ApiClient.mustache | 533 ++++++++++++++++++ .../Java/libraries/jersey2/pom.mustache | 171 ++++++ 2 files changed, 704 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache new file mode 100644 index 000000000000..35a1cf242427 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -0,0 +1,533 @@ +package {{invokerPackage}}; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; + +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.IOException; +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; + +public class ApiClient { + private Map hostMap = new HashMap(); + private Map defaultHeaderMap = new HashMap(); + private boolean debugging = false; + private String basePath = "{{basePath}}"; + private JSON json = new JSON(); + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * 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!"); + } + + /** + * 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; + 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 getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + 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; + } + + /** + * 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; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + 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"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + 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 entity according the given + * Content-Type (only JSON is supported for now). + */ + public Entity serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return Entity.json(json.serialize(obj)); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(Response response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.readEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + } + } + + /** + * 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 + * @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 + * @param returnType The return type into which to deserialize the response + * @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, TypeRef returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + Client client = ClientBuilder.newClient(clientConfig); + + WebTarget target = client.target(this.basePath).path(path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity formEntity = null; + + if (contentType.startsWith("multipart/form-data")) { + MultiPart multipart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + + multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.post(formEntity); + } else if (body == null) { + response = invocationBuilder.post(null); + } else { + response = invocationBuilder.post(serialize(body, contentType)); + } + } else if ("PUT".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.put(formEntity); + } else if (body == null) { + response = invocationBuilder.put(null); + } else { + response = invocationBuilder.put(serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + Map> responseHeaders = new HashMap>(); + for (String key: response.getHeaders().keySet()) { + List values = response.getHeaders().get(key); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(key, headers); + } + throw new ApiException( + response.getStatus(), + message, + responseHeaders, + 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); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache new file mode 100644 index 000000000000..e2d0f73d408e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -0,0 +1,171 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 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 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.6 + 2.4.2 + 2.3 + 1.0.0 + 4.8.1 + + From 07f10a8abc7204594df2369bee77513a507f955b Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 5 Aug 2015 16:37:08 +0800 Subject: [PATCH 07/11] Add command to display all library templates supported for a specific language --- README.md | 23 +++++++- .../io/swagger/codegen/SwaggerCodegen.java | 4 +- .../java/io/swagger/codegen/cmd/Generate.java | 3 +- .../io/swagger/codegen/cmd/LibraryHelp.java | 55 +++++++++++++++++++ .../io/swagger/codegen/CodegenConfig.java | 2 + .../io/swagger/codegen/DefaultCodegen.java | 10 ++++ .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../codegen/languages/JavaClientCodegen.java | 3 + 8 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java diff --git a/README.md b/README.md index f52c4097347c..72daf8612512 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,10 @@ OPTIONS client language to generate (maybe class name in classpath, required) + -L , --library + Library template (sub-template) to use. Run library-help -l {lang} + command for a list of supported libraries. + -o , --output where to write the generated files (current dir by default) @@ -128,7 +132,7 @@ OPTIONS -s , --skip-overwrite specifies if the existing files should be overwritten during the generation - ``` +``` You can then compile and run the client, as well as unit tests against it: @@ -144,6 +148,23 @@ Other languages have petstore samples, too: ./bin/objc-petstore.sh ``` +Various library templates (sub-templates) might be available for a specific language. Running `library-help -l {lang}` will show all library templates supported. + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar library-help -l java +``` + +Output + +``` +LIBRARY OPTIONS + + HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 + + jersey2 + HTTP client: Jersey client 2.6 +``` + ### Generating libraries from your server It's just as easy--just use the `-i` flag to point to either a server or file. diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 3cdc01fe3f5a..2dec1fe26daa 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -5,6 +5,7 @@ import io.airlift.airline.Help; import io.swagger.codegen.cmd.ConfigHelp; import io.swagger.codegen.cmd.Generate; import io.swagger.codegen.cmd.Langs; +import io.swagger.codegen.cmd.LibraryHelp; import io.swagger.codegen.cmd.Meta; /** @@ -29,7 +30,8 @@ public class SwaggerCodegen { Meta.class, Langs.class, Help.class, - ConfigHelp.class + ConfigHelp.class, + LibraryHelp.class ); builder.build().parse(args).run(); diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 1386ae469a9b..99f597740d9d 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -41,7 +41,8 @@ public class Generate implements Runnable { private String lang; @Option(name = {"-L", "--library"}, title = "library", - description = "library template (sub-template) to use") + description = "Library template (sub-template) to use. Run library-help -l {lang} " + + "command for a list of supported libraries.") private String library; @Option(name = {"-o", "--output"}, title = "output directory", diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java new file mode 100644 index 000000000000..480286f90f7c --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java @@ -0,0 +1,55 @@ +package io.swagger.codegen.cmd; + +import io.airlift.airline.Command; +import io.airlift.airline.Option; +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; + +import java.util.ServiceLoader; + +import static java.util.ServiceLoader.load; + +@Command(name = "library-help", description = "Library help for chosen lang") +public class LibraryHelp implements Runnable { + + @Option(name = {"-l", "--lang"}, title = "language", required = true, + description = "language to get library help for") + private String lang; + + /** + * Tries to load config class with SPI first, then with class name directly from classpath + * + * @param name name of config, or full qualified class name in classpath + * @return config class + */ + private static CodegenConfig forName(String name) { + ServiceLoader loader = load(CodegenConfig.class); + for (CodegenConfig config : loader) { + if (config.getName().equals(name)) { + return config; + } + } + + // else try to load directly + try { + return (CodegenConfig) Class.forName(name).newInstance(); + } catch (Exception e) { + throw new RuntimeException("Can't load config class with name ".concat(name), e); + } + } + + @Override + public void run() { + System.out.println(); + CodegenConfig config = forName(lang); + System.out.println("LIBRARY OPTIONS"); + for (String library : config.supportedLibraries().keySet()) { + String description = config.supportedLibraries().get(library); + if ("".equals(library)) + library = ""; + System.out.println("\t" + library); + System.out.println("\t " + description); + System.out.println(); + } + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 45c8cc5e9f83..9cbf32a154c7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -109,6 +109,8 @@ public interface CodegenConfig { void setSkipOverwrite(boolean skipOverwrite); + Map supportedLibraries(); + void setLibrary(String library); /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index aaf62b4a11b9..641fa43b6d4b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -81,6 +81,7 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance = false; + protected Map supportedLibraries = new HashMap(); protected String library = null; public List cliOptions() { @@ -1389,7 +1390,16 @@ public class DefaultCodegen { this.skipOverwrite = skipOverwrite; } + /** + * All library templates supported. + */ + public Map supportedLibraries() { + return supportedLibraries; + } + public void setLibrary(String library) { + if (library != null && !supportedLibraries.containsKey(library)) + throw new RuntimeException("unknown library: " + library); this.library = library; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 4feb75acf4ea..50b549dd6f60 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -266,7 +266,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { String templateFile = null; String library = config.getLibrary(); - if (library != null) { + if (library != null && !"".equals(library)) { String libTemplateFile = config.templateDir() + File.separator + "libraries" + File.separator + library + File.separator + support.templateFile; 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 88266aa76cc1..4df04fc9a1c8 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 @@ -61,6 +61,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + + supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); } public CodegenType getTag() { From 4321339d4f88493787127707290eb0b3a167551d Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 5 Aug 2015 17:28:45 +0800 Subject: [PATCH 08/11] Java petstore sample: move to "default" sub-folder, add jersey2 --- bin/all-petstore.sh | 1 + bin/java-petstore-jersey2.json | 1 + bin/java-petstore-jersey2.sh | 31 + bin/java-petstore.sh | 2 +- pom.xml | 17 +- .../client/petstore/java/default/hello.txt | 1 + .../petstore/java/{ => default}/pom.xml | 0 .../java/io/swagger/client/ApiClient.java | 0 .../java/io/swagger/client/ApiException.java | 0 .../java/io/swagger/client/Configuration.java | 0 .../src/main/java/io/swagger/client/JSON.java | 0 .../src/main/java/io/swagger/client/Pair.java | 0 .../java/io/swagger/client/StringUtil.java | 0 .../main/java/io/swagger/client/TypeRef.java | 0 .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/api/StoreApi.java | 0 .../java/io/swagger/client/api/UserApi.java | 0 .../io/swagger/client/auth/ApiKeyAuth.java | 0 .../swagger/client/auth/Authentication.java | 0 .../io/swagger/client/auth/HttpBasicAuth.java | 0 .../java/io/swagger/client/auth/OAuth.java | 0 .../io/swagger/client/model/Category.java | 0 .../java/io/swagger/client/model/Order.java | 0 .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/Tag.java | 0 .../java/io/swagger/client/model/User.java | 0 .../java/io/swagger/client/ApiClientTest.java | 0 .../io/swagger/client/ConfigurationTest.java | 0 .../io/swagger/client/StringUtilTest.java | 0 .../swagger/client/auth/ApiKeyAuthTest.java | 0 .../client/auth/HttpBasicAuthTest.java | 0 .../io/swagger/petstore/test/PetApiTest.java | 0 .../swagger/petstore/test/StoreApiTest.java | 0 .../io/swagger/petstore/test/UserApiTest.java | 0 .../client/petstore/java/jersey2/hello.txt | 1 + samples/client/petstore/java/jersey2/pom.xml | 171 ++++++ .../java/io/swagger/client/ApiClient.java | 532 ++++++++++++++++++ .../java/io/swagger/client/ApiException.java | 47 ++ .../java/io/swagger/client/Configuration.java | 21 + .../src/main/java/io/swagger/client/JSON.java | 51 ++ .../src/main/java/io/swagger/client/Pair.java | 38 ++ .../java/io/swagger/client/StringUtil.java | 41 ++ .../main/java/io/swagger/client/TypeRef.java | 25 + .../java/io/swagger/client/api/PetApi.java | 406 +++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 214 +++++++ .../java/io/swagger/client/api/UserApi.java | 385 +++++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 58 ++ .../swagger/client/auth/Authentication.java | 11 + .../io/swagger/client/auth/HttpBasicAuth.java | 40 ++ .../java/io/swagger/client/auth/OAuth.java | 13 + .../io/swagger/client/model/Category.java | 50 ++ .../java/io/swagger/client/model/Order.java | 111 ++++ .../java/io/swagger/client/model/Pet.java | 113 ++++ .../java/io/swagger/client/model/Tag.java | 50 ++ .../java/io/swagger/client/model/User.java | 135 +++++ .../java/io/swagger/client/ApiClientTest.java | 193 +++++++ .../io/swagger/client/ConfigurationTest.java | 15 + .../io/swagger/client/StringUtilTest.java | 33 ++ .../swagger/client/auth/ApiKeyAuthTest.java | 47 ++ .../client/auth/HttpBasicAuthTest.java | 52 ++ .../io/swagger/petstore/test/PetApiTest.java | 192 +++++++ .../swagger/petstore/test/StoreApiTest.java | 72 +++ .../io/swagger/petstore/test/UserApiTest.java | 86 +++ 63 files changed, 3255 insertions(+), 5 deletions(-) create mode 100644 bin/java-petstore-jersey2.json create mode 100755 bin/java-petstore-jersey2.sh create mode 100644 samples/client/petstore/java/default/hello.txt rename samples/client/petstore/java/{ => default}/pom.xml (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/ApiClient.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/ApiException.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/Configuration.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/JSON.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/Pair.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/StringUtil.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/TypeRef.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/api/PetApi.java (99%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/api/StoreApi.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/api/UserApi.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/auth/ApiKeyAuth.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/auth/Authentication.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/auth/HttpBasicAuth.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/auth/OAuth.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/model/Category.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/model/Order.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/model/Pet.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/model/Tag.java (100%) rename samples/client/petstore/java/{ => default}/src/main/java/io/swagger/client/model/User.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/client/ApiClientTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/client/ConfigurationTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/client/StringUtilTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/petstore/test/PetApiTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/petstore/test/StoreApiTest.java (100%) rename samples/client/petstore/java/{ => default}/src/test/java/io/swagger/petstore/test/UserApiTest.java (100%) create mode 100644 samples/client/petstore/java/jersey2/hello.txt create mode 100644 samples/client/petstore/java/jersey2/pom.xml create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java create mode 100644 samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 7a47662a7c7c..23c2935ed2ae 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -24,6 +24,7 @@ cd $APP_DIR ./bin/dynamic-html.sh ./bin/html-petstore.sh ./bin/java-petstore.sh +./bin/java-petstore-jersey2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/java-petstore-jersey2.json b/bin/java-petstore-jersey2.json new file mode 100644 index 000000000000..1ba121afe219 --- /dev/null +++ b/bin/java-petstore-jersey2.json @@ -0,0 +1 @@ +{"artifactId": "swagger-petstore-jersey2"} \ No newline at end of file diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh new file mode 100755 index 000000000000..94f16422d1af --- /dev/null +++ b/bin/java-petstore-jersey2.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java --library jersey2 -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index 3beff2f07cec..f842d9ca3b0e 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java/default" java $JAVA_OPTS -jar $executable $ags diff --git a/pom.xml b/pom.xml index 45fba414722a..f476f7aae011 100644 --- a/pom.xml +++ b/pom.xml @@ -292,7 +292,19 @@ - samples/client/petstore/java + samples/client/petstore/java/default + + + + java-client-jersey2 + + + env + java + + + + samples/client/petstore/java/jersey2 @@ -377,7 +389,8 @@ samples/client/petstore/android-java - samples/client/petstore/java + samples/client/petstore/java/default + samples/client/petstore/java/jersey2 samples/client/petstore/scala samples/server/petstore/jaxrs samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/java/default/hello.txt b/samples/client/petstore/java/default/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/default/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/default/pom.xml similarity index 100% rename from samples/client/petstore/java/pom.xml rename to samples/client/petstore/java/default/pom.xml diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/JSON.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/TypeRef.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java similarity index 99% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index c1657233fdc1..d1aee33af002 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -243,7 +243,7 @@ public class PetApi { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index f5cdc5fb71f0..d7c2038dead8 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java similarity index 100% rename from samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/ConfigurationTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/StringUtilTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/StringUtilTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/PetApiTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java similarity index 100% rename from samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml new file mode 100644 index 000000000000..eee88cd24293 --- /dev/null +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -0,0 +1,171 @@ + + 4.0.0 + io.swagger + swagger-petstore-jersey2 + jar + swagger-petstore-jersey2 + 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 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.6 + 2.4.2 + 2.3 + 1.0.0 + 4.8.1 + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 000000000000..52ce291a7684 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,532 @@ +package io.swagger.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; + +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.IOException; +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +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 hostMap = new HashMap(); + private Map defaultHeaderMap = new HashMap(); + private boolean debugging = false; + private String basePath = "http://petstore.swagger.io/v2"; + private JSON json = new JSON(); + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // 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); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * 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!"); + } + + /** + * 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; + 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 getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + 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; + } + + /** + * 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; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + 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"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + 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 entity according the given + * Content-Type (only JSON is supported for now). + */ + public Entity serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + return Entity.json(json.serialize(obj)); + } else { + throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + */ + public T deserialize(Response response, TypeRef returnType) throws ApiException { + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + String body; + if (response.hasEntity()) + body = (String) response.readEntity(String.class); + else + body = ""; + + if (contentType.startsWith("application/json")) { + return json.deserialize(body, returnType); + } else { + throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + } + } + + /** + * 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 + * @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 + * @param returnType The return type into which to deserialize the response + * @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, TypeRef returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + Client client = ClientBuilder.newClient(clientConfig); + + WebTarget target = client.target(this.basePath).path(path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + + for (String key : headerParams.keySet()) { + String value = headerParams.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + + for (String key : defaultHeaderMap.keySet()) { + if (!headerParams.containsKey(key)) { + String value = defaultHeaderMap.get(key); + if (value != null) { + invocationBuilder = invocationBuilder.header(key, value); + } + } + } + + Entity formEntity = null; + + if (contentType.startsWith("multipart/form-data")) { + MultiPart multipart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), file.getName())); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + + multipart.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataMultiPart mp = new FormDataMultiPart(); + mp.bodyPart(new FormDataBodyPart(param.getKey(), parameterToString(param.getValue()))); + multipart.bodyPart(mp, MediaType.MULTIPART_FORM_DATA_TYPE); + } + } + formEntity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } + + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.post(formEntity); + } else if (body == null) { + response = invocationBuilder.post(null); + } else { + response = invocationBuilder.post(serialize(body, contentType)); + } + } else if ("PUT".equals(method)) { + if (formEntity != null) { + response = invocationBuilder.put(formEntity); + } else if (body == null) { + response = invocationBuilder.put(null); + } else { + response = invocationBuilder.put(serialize(body, contentType)); + } + } else if ("DELETE".equals(method)) { + response = invocationBuilder.delete(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + Map> responseHeaders = new HashMap>(); + for (String key: response.getHeaders().keySet()) { + List values = response.getHeaders().get(key); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(key, headers); + } + throw new ApiException( + response.getStatus(), + message, + responseHeaders, + 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); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 000000000000..a39785eb47ec --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,47 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.List; + +public class ApiException extends Exception { + private int code = 0; + private String message = null; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(int code, String message) { + this.code = code; + this.message = message; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 000000000000..04899a110f63 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,21 @@ +package io.swagger.client; + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..4c1fa53430b2 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.datatype.joda.*; + +import java.io.IOException; + +public class JSON { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return mapper.writeValueAsString(obj); + else + return null; + } catch (Exception e) { + throw new ApiException(400, e.getMessage()); + } + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, TypeRef returnType) throws ApiException { + JavaType javaType = mapper.constructType(returnType.getType()); + try { + return mapper.readValue(body, javaType); + } catch (IOException e) { + if (returnType.getType().equals(String.class)) + return (T) body; + else + throw new ApiException(500, e.getMessage(), null, body); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 000000000000..4b7112f6db65 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,38 @@ +package io.swagger.client; + +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..5b5af2d5ce03 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,41 @@ +package io.swagger.client; + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java new file mode 100644 index 000000000000..6081df1082fa --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java @@ -0,0 +1,25 @@ +package io.swagger.client; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public class TypeRef { + private final Type type; + + public TypeRef() { + this.type = getGenericType(getClass()); + } + + private static Type getGenericType(Class klass) { + Type superclass = klass.getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("No type parameter provided"); + } + ParameterizedType parameterized = (ParameterizedType) superclass; + return parameterized.getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..d1aee33af002 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,406 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +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; + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void updatePet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + */ + public void addPet (Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return List + */ + public List findPetsByStatus (List status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return List + */ + public List findPetsByTags (List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + public Pet getPetById (Long petId) throws ApiException { + Object postBody = 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 path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key", "petstore_auth" }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + public void updatePetWithForm (String petId, String name, String status) throws ApiException { + Object postBody = 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 path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return void + */ + public void deletePet (Long petId, String apiKey) throws ApiException { + Object postBody = 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 path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return void + */ + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = 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 path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "multipart/form-data" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "petstore_auth" }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..6a0c014f266d --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,214 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +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; + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + public Map getInventory () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { "api_key" }; + + TypeRef returnType = new TypeRef>() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + public Order placeOrder (Order body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * 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 + * @return Order + */ + public Order getOrderById (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * 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 + * @return void + */ + public void deleteOrder (String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..0d408637cea8 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,385 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.TypeRef; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +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 + * @return void + */ + public void createUser (User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithArrayInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + public void createUsersWithListInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + public String loginUser (String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); + + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Logs out current logged in user session + * + * @return void + */ + public void logoutUser () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + TypeRef returnType = new TypeRef() {}; + return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + */ + public void updateUser (String username, User body) throws ApiException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + public void deleteUser (String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + // query params + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + String[] authNames = new String[] { }; + + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } + +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..0e5ca9c7c538 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,58 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 000000000000..98b1a6900b93 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,11 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..980b24311bea --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,40 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +public class HttpBasicAuth implements Authentication { + 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) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 000000000000..39fba5498c0e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,13 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..d43f6a9758fb --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..25864d8c9cc8 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,111 @@ +package io.swagger.client.model; + +import java.util.Date; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..d7c2038dead8 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,113 @@ +package io.swagger.client.model; + +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.*; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + public enum StatusEnum { + available, pending, sold, + }; + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("category") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" category: ").append(category).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..63a2ca3b7390 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Tag { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..0ace5b7e30a3 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,135 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("username") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("password") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); + sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..802c0cae3b97 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,193 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +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 testSelectHeaderAccept() { + String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"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[]{"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"}; + assertEquals("application/json", 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) { + } + } + + @Test + public void testSetUsername() { + try { + apiClient.setUsername("my-username"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + apiClient.setPassword("my-password"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key"); + 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/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..b95eb74605ea --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +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/jersey2/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +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/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +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/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +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/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 000000000000..b6ad5fb05275 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,192 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; + +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 org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @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 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(String.valueOf(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())); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.available); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 000000000000..508764b8c2db --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,72 @@ +package io.swagger.petstore.test; + +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.util.Map; + +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"); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.placed); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 000000000000..26e46bfa6024 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +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("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + 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("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + 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(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} From a41361c959cd5b56f3b34d813c32a02952a224db Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 7 Aug 2015 22:16:32 +0800 Subject: [PATCH 09/11] Change the "--library" option into a config option --- README.md | 26 ++++--------------- bin/java-petstore-jersey2.json | 5 +++- bin/java-petstore-jersey2.sh | 2 +- .../io/swagger/codegen/cmd/ConfigHelp.java | 2 +- .../java/io/swagger/codegen/cmd/Generate.java | 15 +++++------ .../io/swagger/codegen/DefaultCodegen.java | 12 ++++++++- .../codegen/languages/JavaClientCodegen.java | 3 ++- 7 files changed, 31 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 72daf8612512..a7f7f4e45d9b 100644 --- a/README.md +++ b/README.md @@ -116,10 +116,6 @@ OPTIONS client language to generate (maybe class name in classpath, required) - -L , --library - Library template (sub-template) to use. Run library-help -l {lang} - command for a list of supported libraries. - -o , --output where to write the generated files (current dir by default) @@ -148,23 +144,6 @@ Other languages have petstore samples, too: ./bin/objc-petstore.sh ``` -Various library templates (sub-templates) might be available for a specific language. Running `library-help -l {lang}` will show all library templates supported. - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar library-help -l java -``` - -Output - -``` -LIBRARY OPTIONS - - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 - - jersey2 - HTTP client: Jersey client 2.6 -``` - ### Generating libraries from your server It's just as easy--just use the `-i` flag to point to either a server or file. @@ -270,6 +249,11 @@ CONFIG OPTIONS sourceFolder source folder for generated code + + library + library template (sub-template) to use: + - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 + jersey2 - HTTP client: Jersey client 2.6 ``` Your config file for java can look like diff --git a/bin/java-petstore-jersey2.json b/bin/java-petstore-jersey2.json index 1ba121afe219..af343e1d6b88 100644 --- a/bin/java-petstore-jersey2.json +++ b/bin/java-petstore-jersey2.json @@ -1 +1,4 @@ -{"artifactId": "swagger-petstore-jersey2"} \ No newline at end of file +{ + "library": "jersey2", + "artifactId": "swagger-petstore-jersey2" +} \ No newline at end of file diff --git a/bin/java-petstore-jersey2.sh b/bin/java-petstore-jersey2.sh index 94f16422d1af..cb51c1e1a8d4 100755 --- a/bin/java-petstore-jersey2.sh +++ b/bin/java-petstore-jersey2.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java --library jersey2 -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-jersey2.json -o samples/client/petstore/java/jersey2" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java index 6b34a4bf56df..78e4b9bd6baf 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -45,7 +45,7 @@ public class ConfigHelp implements Runnable { System.out.println("CONFIG OPTIONS"); for (CliOption langCliOption : config.cliOptions()) { System.out.println("\t" + langCliOption.getOpt()); - System.out.println("\t " + langCliOption.getDescription()); + System.out.println("\t " + langCliOption.getDescription().replaceAll("\n", "\n\t ")); System.out.println(); } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 99f597740d9d..cf22ae91b629 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -40,11 +40,6 @@ public class Generate implements Runnable { description = "client language to generate (maybe class name in classpath, required)") private String lang; - @Option(name = {"-L", "--library"}, title = "library", - description = "Library template (sub-template) to use. Run library-help -l {lang} " + - "command for a list of supported libraries.") - private String library; - @Option(name = {"-o", "--output"}, title = "output directory", description = "where to write the generated files (current dir by default)") private String output = ""; @@ -110,7 +105,6 @@ public class Generate implements Runnable { } CodegenConfig config = forName(lang); - config.setLibrary(library); config.setOutputDir(new File(output).getAbsolutePath()); if (null != templateDir) { @@ -121,8 +115,13 @@ public class Generate implements Runnable { Config genConfig = ConfigParser.read(configFile); if (null != genConfig) { for (CliOption langCliOption : config.cliOptions()) { - if (genConfig.hasOption(langCliOption.getOpt())) { - config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + String opt = langCliOption.getOpt(); + if (genConfig.hasOption(opt)) { + config.additionalProperties().put(opt, genConfig.getOption(opt)); + // the "library" config option is for library template (sub-template) + if ("library".equals(opt)) { + config.setLibrary(genConfig.getOption(opt)); + } } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 641fa43b6d4b..179387a0b370 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -55,6 +55,7 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -81,7 +82,7 @@ public class DefaultCodegen { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean supportsInheritance = false; - protected Map supportedLibraries = new HashMap(); + protected Map supportedLibraries = new LinkedHashMap(); protected String library = null; public List cliOptions() { @@ -1392,6 +1393,7 @@ public class DefaultCodegen { /** * All library templates supported. + * (key: library name, value: library description) */ public Map supportedLibraries() { return supportedLibraries; @@ -1409,4 +1411,12 @@ public class DefaultCodegen { public String getLibrary() { return library; } + + protected CliOption buildLibraryCliOption(Map supportedLibraries) { + StringBuilder sb = new StringBuilder("library template (sub-template) to use:"); + for (String lib : supportedLibraries.keySet()) { + sb.append("\n").append(lib).append(" - ").append(supportedLibraries.get(lib)); + } + return new CliOption("library", sb.toString()); + } } 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 4df04fc9a1c8..e5437f2fcb82 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 @@ -62,8 +62,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); + cliOptions.add(buildLibraryCliOption(supportedLibraries)); } public CodegenType getTag() { From b686b532590bf04b1e15ea78fe834a6008af65d2 Mon Sep 17 00:00:00 2001 From: xhh Date: Sat, 8 Aug 2015 11:14:06 +0800 Subject: [PATCH 10/11] Support overriding API/model templates with library template --- .../io/swagger/codegen/AbstractGenerator.java | 17 ++++++++++++++++ .../io/swagger/codegen/DefaultGenerator.java | 20 +++++-------------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 0d530e7c959a..2c90f4255ece 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -60,6 +60,23 @@ public abstract class AbstractGenerator { throw new RuntimeException("can't load template " + name); } + /** + * Get the template file path with template dir prepended, and use the + * library template if exists. + */ + public String getFullTemplateFile(CodegenConfig config, String templateFile) { + String library = config.getLibrary(); + if (library != null && !"".equals(library)) { + String libTemplateFile = config.templateDir() + File.separator + + "libraries" + File.separator + library + File.separator + + templateFile; + if (templateExists(libTemplateFile)) { + return libTemplateFile; + } + } + return config.templateDir() + File.separator + templateFile; + } + public boolean templateExists(String name) { return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 535c9baec72c..37d654734879 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -139,7 +139,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (!config.shouldOverwrite(filename)) { continue; } - String template = readTemplate(config.templateDir() + File.separator + templateName); + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { public Reader getTemplate(String name) { @@ -191,7 +192,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { continue; } - String template = readTemplate(config.templateDir() + File.separator + templateName); + String templateFile = getFullTemplateFile(config, templateName); + String template = readTemplate(templateFile); Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { public Reader getTemplate(String name) { @@ -262,19 +264,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { continue; } - String templateFile = null; - String library = config.getLibrary(); - if (library != null && !"".equals(library)) { - String libTemplateFile = config.templateDir() + File.separator + - "libraries" + File.separator + library + File.separator + - support.templateFile; - if (templateExists(libTemplateFile)) { - templateFile = libTemplateFile; - } - } - if (templateFile == null) { - templateFile = config.templateDir() + File.separator + support.templateFile; - } + String templateFile = getFullTemplateFile(config, support.templateFile); if (templateFile.endsWith("mustache")) { String template = readTemplate(templateFile); From 569082743f126aaabfe0d6edd37183c03b9fd9f4 Mon Sep 17 00:00:00 2001 From: xhh Date: Sat, 22 Aug 2015 22:05:43 +0800 Subject: [PATCH 11/11] Remove the unused LibraryHelp command --- .../io/swagger/codegen/SwaggerCodegen.java | 4 +- .../io/swagger/codegen/cmd/LibraryHelp.java | 55 ------------------- 2 files changed, 1 insertion(+), 58 deletions(-) delete mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 2dec1fe26daa..3cdc01fe3f5a 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -5,7 +5,6 @@ import io.airlift.airline.Help; import io.swagger.codegen.cmd.ConfigHelp; import io.swagger.codegen.cmd.Generate; import io.swagger.codegen.cmd.Langs; -import io.swagger.codegen.cmd.LibraryHelp; import io.swagger.codegen.cmd.Meta; /** @@ -30,8 +29,7 @@ public class SwaggerCodegen { Meta.class, Langs.class, Help.class, - ConfigHelp.class, - LibraryHelp.class + ConfigHelp.class ); builder.build().parse(args).run(); diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java deleted file mode 100644 index 480286f90f7c..000000000000 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/LibraryHelp.java +++ /dev/null @@ -1,55 +0,0 @@ -package io.swagger.codegen.cmd; - -import io.airlift.airline.Command; -import io.airlift.airline.Option; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConfig; - -import java.util.ServiceLoader; - -import static java.util.ServiceLoader.load; - -@Command(name = "library-help", description = "Library help for chosen lang") -public class LibraryHelp implements Runnable { - - @Option(name = {"-l", "--lang"}, title = "language", required = true, - description = "language to get library help for") - private String lang; - - /** - * Tries to load config class with SPI first, then with class name directly from classpath - * - * @param name name of config, or full qualified class name in classpath - * @return config class - */ - private static CodegenConfig forName(String name) { - ServiceLoader loader = load(CodegenConfig.class); - for (CodegenConfig config : loader) { - if (config.getName().equals(name)) { - return config; - } - } - - // else try to load directly - try { - return (CodegenConfig) Class.forName(name).newInstance(); - } catch (Exception e) { - throw new RuntimeException("Can't load config class with name ".concat(name), e); - } - } - - @Override - public void run() { - System.out.println(); - CodegenConfig config = forName(lang); - System.out.println("LIBRARY OPTIONS"); - for (String library : config.supportedLibraries().keySet()) { - String description = config.supportedLibraries().get(library); - if ("".equals(library)) - library = ""; - System.out.println("\t" + library); - System.out.println("\t " + description); - System.out.println(); - } - } -}