forked from loafle/openapi-generator-original
Merge remote-tracking branch 'origin/master' into 2.3.0
This commit is contained in:
commit
6fe38e8383
@ -13,6 +13,7 @@ import java.io.Writer;
|
|||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -63,6 +64,10 @@ public abstract class AbstractGenerator {
|
|||||||
throw new RuntimeException("can't load template " + name);
|
throw new RuntimeException("can't load template " + name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String buildLibraryFilePath(String dir, String library, String file) {
|
||||||
|
return dir + File.separator + "libraries" + File.separator + library + File.separator + file;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the template file path with template dir prepended, and use the
|
* Get the template file path with template dir prepended, and use the
|
||||||
* library template if exists.
|
* library template if exists.
|
||||||
@ -72,23 +77,38 @@ public abstract class AbstractGenerator {
|
|||||||
* @return String Full template file path
|
* @return String Full template file path
|
||||||
*/
|
*/
|
||||||
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
|
public String getFullTemplateFile(CodegenConfig config, String templateFile) {
|
||||||
String template = config.templateDir() + File.separator + templateFile;
|
//1st the code will check if there's a <template folder>/libraries/<library> folder containing the file
|
||||||
|
//2nd it will check for the file in the specified <template folder> folder
|
||||||
|
//3rd it will check if there's an <embedded template>/libraries/<library> folder containing the file
|
||||||
|
//4th and last it will assume the file is in <embedded template> folder.
|
||||||
|
|
||||||
|
//check the supplied template library folder for the file
|
||||||
|
final String library = config.getLibrary();
|
||||||
|
if (StringUtils.isNotEmpty(library)) {
|
||||||
|
//look for the file in the library subfolder of the supplied template
|
||||||
|
final String libTemplateFile = buildLibraryFilePath(config.templateDir(), library, templateFile);
|
||||||
|
if (new File(libTemplateFile).exists()) {
|
||||||
|
return libTemplateFile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//check the supplied template main folder for the file
|
||||||
|
final String template = config.templateDir() + File.separator + templateFile;
|
||||||
if (new File(template).exists()) {
|
if (new File(template).exists()) {
|
||||||
return template;
|
return template;
|
||||||
} else {
|
|
||||||
String library = config.getLibrary();
|
|
||||||
if (library != null && !"".equals(library)) {
|
|
||||||
String libTemplateFile = config.embeddedTemplateDir() + File.separator +
|
|
||||||
"libraries" + File.separator + library + File.separator +
|
|
||||||
templateFile;
|
|
||||||
if (embeddedTemplateExists(libTemplateFile)) {
|
|
||||||
// Fall back to the template file embedded/packaged in the JAR file...
|
|
||||||
return libTemplateFile;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Fall back to the template file embedded/packaged in the JAR file...
|
|
||||||
return config.embeddedTemplateDir() + File.separator + templateFile;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//try the embedded template library folder next
|
||||||
|
if (StringUtils.isNotEmpty(library)) {
|
||||||
|
final String embeddedLibTemplateFile = buildLibraryFilePath(config.embeddedTemplateDir(), library, templateFile);
|
||||||
|
if (embeddedTemplateExists(embeddedLibTemplateFile)) {
|
||||||
|
// Fall back to the template file embedded/packaged in the JAR file library folder...
|
||||||
|
return embeddedLibTemplateFile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to the template file embedded/packaged in the JAR file...
|
||||||
|
return config.embeddedTemplateDir() + File.separator + templateFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String readResourceContents(String resourceFilePath) {
|
public String readResourceContents(String resourceFilePath) {
|
||||||
|
@ -4,18 +4,22 @@ import io.swagger.codegen.languages.JavaClientCodegen;
|
|||||||
import io.swagger.models.Swagger;
|
import io.swagger.models.Swagger;
|
||||||
import io.swagger.parser.SwaggerParser;
|
import io.swagger.parser.SwaggerParser;
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.junit.rules.TemporaryFolder;
|
import org.junit.rules.TemporaryFolder;
|
||||||
import org.testng.annotations.AfterMethod;
|
import org.testng.annotations.AfterMethod;
|
||||||
import org.testng.annotations.BeforeMethod;
|
import org.testng.annotations.BeforeMethod;
|
||||||
import org.testng.annotations.Test;
|
import org.testng.annotations.Test;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static io.swagger.codegen.CodegenConstants.TEMPLATE_DIR;
|
||||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
import static org.testng.Assert.*;
|
import static org.testng.Assert.*;
|
||||||
@ -28,6 +32,11 @@ public class DefaultGeneratorTest {
|
|||||||
private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite";
|
private static final String TEST_SKIP_OVERWRITE = "testSkipOverwrite";
|
||||||
private static final String POM_FILE = "pom.xml";
|
private static final String POM_FILE = "pom.xml";
|
||||||
private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java";
|
private static final String MODEL_ORDER_FILE = "/src/main/java/io/swagger/client/model/Order.java";
|
||||||
|
private static final String API_CLIENT_FILE = "/src/main/java/io/swagger/client/ApiClient.java";
|
||||||
|
private static final String BUILD_GRADLE_FILE = "build.gradle";
|
||||||
|
|
||||||
|
private static final String LIBRARY_COMMENT = "//overloaded template file within library folder to add this comment";
|
||||||
|
private static final String TEMPLATE_COMMENT = "//overloaded main template file to add this comment";
|
||||||
|
|
||||||
public TemporaryFolder folder = new TemporaryFolder();
|
public TemporaryFolder folder = new TemporaryFolder();
|
||||||
|
|
||||||
@ -198,6 +207,56 @@ public class DefaultGeneratorTest {
|
|||||||
// assertTrue(pom.exists());
|
// assertTrue(pom.exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean containsOverloadedComments(File file, String ...search) throws IOException {
|
||||||
|
for (String line : Files.readAllLines(file.toPath(), Charset.defaultCharset())) {
|
||||||
|
if (StringUtils.containsAny(line, search)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOverloadingTemplateFiles() throws Exception {
|
||||||
|
final File output = folder.getRoot();
|
||||||
|
|
||||||
|
final Swagger swagger = new SwaggerParser().read("src/test/resources/petstore.json");
|
||||||
|
CodegenConfig codegenConfig = new JavaClientCodegen();
|
||||||
|
codegenConfig.setLibrary("jersey2");
|
||||||
|
codegenConfig.setOutputDir(output.getAbsolutePath());
|
||||||
|
|
||||||
|
ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);
|
||||||
|
//generate content first time without specifying an overloaded template file, so the default mustache files are used instead
|
||||||
|
new DefaultGenerator().opts(clientOptInput).generate();
|
||||||
|
|
||||||
|
final File order = new File(output, MODEL_ORDER_FILE);
|
||||||
|
assertTrue(order.exists());
|
||||||
|
assertFalse(containsOverloadedComments(order, TEMPLATE_COMMENT, LIBRARY_COMMENT));
|
||||||
|
|
||||||
|
final File gradle = new File(output, BUILD_GRADLE_FILE);
|
||||||
|
assertTrue(gradle.exists());
|
||||||
|
assertFalse(containsOverloadedComments(gradle, TEMPLATE_COMMENT, LIBRARY_COMMENT));
|
||||||
|
|
||||||
|
final File apiClient = new File(output, API_CLIENT_FILE);
|
||||||
|
assertTrue(apiClient.exists());
|
||||||
|
assertFalse(containsOverloadedComments(apiClient, TEMPLATE_COMMENT, LIBRARY_COMMENT));
|
||||||
|
|
||||||
|
codegenConfig.additionalProperties().put(TEMPLATE_DIR, "src/test/resources/2_0/templates/Java");
|
||||||
|
//generate content second time while specifying a template folder, so the files from the template are used instead
|
||||||
|
new DefaultGenerator().opts(clientOptInput).generate();
|
||||||
|
|
||||||
|
//this file won't contain the library comment because Jersey2 doesn't override the model template
|
||||||
|
assertTrue(order.exists());
|
||||||
|
assertTrue(containsOverloadedComments(order, TEMPLATE_COMMENT));
|
||||||
|
|
||||||
|
assertTrue(gradle.exists());
|
||||||
|
assertTrue(containsOverloadedComments(gradle, LIBRARY_COMMENT));
|
||||||
|
|
||||||
|
assertTrue(apiClient.exists());
|
||||||
|
assertTrue(containsOverloadedComments(apiClient, LIBRARY_COMMENT));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGenerateUniqueOperationIds() {
|
public void testGenerateUniqueOperationIds() {
|
||||||
final File output = folder.getRoot();
|
final File output = folder.getRoot();
|
||||||
|
@ -0,0 +1,725 @@
|
|||||||
|
//overloaded main template file to add this comment
|
||||||
|
|
||||||
|
{{>licenseInfo}}
|
||||||
|
package {{invokerPackage}};
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.*;
|
||||||
|
import com.fasterxml.jackson.databind.*;
|
||||||
|
{{#java8}}
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.*;
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
import com.fasterxml.jackson.datatype.joda.*;
|
||||||
|
{{/java8}}
|
||||||
|
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
|
||||||
|
|
||||||
|
import com.sun.jersey.api.client.Client;
|
||||||
|
import com.sun.jersey.api.client.ClientResponse;
|
||||||
|
import com.sun.jersey.api.client.GenericType;
|
||||||
|
import com.sun.jersey.api.client.config.DefaultClientConfig;
|
||||||
|
import com.sun.jersey.api.client.filter.LoggingFilter;
|
||||||
|
import com.sun.jersey.api.client.WebResource.Builder;
|
||||||
|
|
||||||
|
import com.sun.jersey.multipart.FormDataMultiPart;
|
||||||
|
import com.sun.jersey.multipart.file.FileDataBodyPart;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.Response.Status.Family;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
|
||||||
|
import {{invokerPackage}}.auth.Authentication;
|
||||||
|
import {{invokerPackage}}.auth.HttpBasicAuth;
|
||||||
|
import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||||
|
import {{invokerPackage}}.auth.OAuth;
|
||||||
|
|
||||||
|
{{>generatedAnnotation}}
|
||||||
|
public class ApiClient {
|
||||||
|
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||||
|
private String basePath = "{{basePath}}";
|
||||||
|
private boolean debugging = false;
|
||||||
|
private int connectionTimeout = 0;
|
||||||
|
|
||||||
|
private Client httpClient;
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private Map<String, Authentication> authentications;
|
||||||
|
|
||||||
|
private int statusCode;
|
||||||
|
private Map<String, List<String>> responseHeaders;
|
||||||
|
|
||||||
|
private DateFormat dateFormat;
|
||||||
|
|
||||||
|
public ApiClient() {
|
||||||
|
objectMapper = new ObjectMapper();
|
||||||
|
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||||
|
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
|
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
||||||
|
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
||||||
|
{{#java8}}
|
||||||
|
objectMapper.registerModule(new JavaTimeModule());
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
objectMapper.registerModule(new JodaModule());
|
||||||
|
{{/java8}}
|
||||||
|
objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat());
|
||||||
|
|
||||||
|
dateFormat = ApiClient.buildDefaultDateFormat();
|
||||||
|
|
||||||
|
// Set default User-Agent.
|
||||||
|
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
|
||||||
|
|
||||||
|
// Setup authentications (key: authentication name, value: authentication).
|
||||||
|
authentications = new HashMap<String, Authentication>();{{#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);
|
||||||
|
|
||||||
|
rebuildHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DateFormat buildDefaultDateFormat() {
|
||||||
|
return new RFC3339DateFormat();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the Client used to make HTTP requests with the latest settings,
|
||||||
|
* i.e. objectMapper and debugging.
|
||||||
|
* TODO: better to use the Builder Pattern?
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient rebuildHttpClient() {
|
||||||
|
// Add the JSON serialization support to Jersey
|
||||||
|
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
|
||||||
|
DefaultClientConfig conf = new DefaultClientConfig();
|
||||||
|
conf.getSingletons().add(jsonProvider);
|
||||||
|
Client client = Client.create(conf);
|
||||||
|
if (debugging) {
|
||||||
|
client.addFilter(new LoggingFilter());
|
||||||
|
}
|
||||||
|
this.httpClient = client;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the current object mapper used for JSON serialization/deserialization.
|
||||||
|
* <p>
|
||||||
|
* Note: If you make changes to the object mapper, remember to set it back via
|
||||||
|
* <code>setObjectMapper</code> in order to trigger HTTP client rebuilding.
|
||||||
|
* </p>
|
||||||
|
* @return Object mapper
|
||||||
|
*/
|
||||||
|
public ObjectMapper getObjectMapper() {
|
||||||
|
return objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient setObjectMapper(ObjectMapper objectMapper) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
// Need to rebuild the Client as it depends on object mapper.
|
||||||
|
rebuildHttpClient();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Client getHttpClient() {
|
||||||
|
return httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient setHttpClient(Client httpClient) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBasePath() {
|
||||||
|
return basePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient setBasePath(String basePath) {
|
||||||
|
this.basePath = basePath;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the status code of the previous request
|
||||||
|
* @return Status code
|
||||||
|
*/
|
||||||
|
public int getStatusCode() {
|
||||||
|
return statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the response headers of the previous request
|
||||||
|
* @return Response headers
|
||||||
|
*/
|
||||||
|
public Map<String, List<String>> getResponseHeaders() {
|
||||||
|
return responseHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get authentications (key: authentication name, value: authentication).
|
||||||
|
* @return Map of authentication
|
||||||
|
*/
|
||||||
|
public Map<String, Authentication> getAuthentications() {
|
||||||
|
return authentications;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get authentication for the given name.
|
||||||
|
*
|
||||||
|
* @param authName The authentication name
|
||||||
|
* @return The authentication, null if not found
|
||||||
|
*/
|
||||||
|
public Authentication getAuthentication(String authName) {
|
||||||
|
return authentications.get(authName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set username for the first HTTP basic authentication.
|
||||||
|
* @param username Username
|
||||||
|
*/
|
||||||
|
public void setUsername(String username) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof HttpBasicAuth) {
|
||||||
|
((HttpBasicAuth) auth).setUsername(username);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set password for the first HTTP basic authentication.
|
||||||
|
* @param password Password
|
||||||
|
*/
|
||||||
|
public void setPassword(String password) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof HttpBasicAuth) {
|
||||||
|
((HttpBasicAuth) auth).setPassword(password);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set API key value for the first API key authentication.
|
||||||
|
* @param apiKey API key
|
||||||
|
*/
|
||||||
|
public void setApiKey(String apiKey) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof ApiKeyAuth) {
|
||||||
|
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No API key authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set API key prefix for the first API key authentication.
|
||||||
|
* @param apiKeyPrefix API key prefix
|
||||||
|
*/
|
||||||
|
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof ApiKeyAuth) {
|
||||||
|
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No API key authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set access token for the first OAuth2 authentication.
|
||||||
|
* @param accessToken Access token
|
||||||
|
*/
|
||||||
|
public void setAccessToken(String accessToken) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof OAuth) {
|
||||||
|
((OAuth) auth).setAccessToken(accessToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No OAuth2 authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the User-Agent header's value (by adding to the default header map).
|
||||||
|
* @param userAgent User agent
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setUserAgent(String userAgent) {
|
||||||
|
addDefaultHeader("User-Agent", userAgent);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a default header.
|
||||||
|
*
|
||||||
|
* @param key The header's key
|
||||||
|
* @param value The header's value
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient addDefaultHeader(String key, String value) {
|
||||||
|
defaultHeaderMap.put(key, value);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check that whether debugging is enabled for this API client.
|
||||||
|
* @return True if debugging is on
|
||||||
|
*/
|
||||||
|
public boolean isDebugging() {
|
||||||
|
return debugging;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable/disable debugging for this API client.
|
||||||
|
*
|
||||||
|
* @param debugging To enable (true) or disable (false) debugging
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setDebugging(boolean debugging) {
|
||||||
|
this.debugging = debugging;
|
||||||
|
// Need to rebuild the Client as it depends on the value of debugging.
|
||||||
|
rebuildHttpClient();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect timeout (in milliseconds).
|
||||||
|
* @return Connection timeout
|
||||||
|
*/
|
||||||
|
public int getConnectTimeout() {
|
||||||
|
return connectionTimeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the connect timeout (in milliseconds).
|
||||||
|
* A value of 0 means no timeout, otherwise values must be between 1 and
|
||||||
|
* {@link Integer#MAX_VALUE}.
|
||||||
|
* @param connectionTimeout Connection timeout in milliseconds
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setConnectTimeout(int connectionTimeout) {
|
||||||
|
this.connectionTimeout = connectionTimeout;
|
||||||
|
httpClient.setConnectTimeout(connectionTimeout);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the date format used to parse/format date parameters.
|
||||||
|
* @return Date format
|
||||||
|
*/
|
||||||
|
public DateFormat getDateFormat() {
|
||||||
|
return dateFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the date format used to parse/format date parameters.
|
||||||
|
* @param dateFormat Date format
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setDateFormat(DateFormat dateFormat) {
|
||||||
|
this.dateFormat = dateFormat;
|
||||||
|
// Also set the date format for model (de)serialization with Date properties.
|
||||||
|
this.objectMapper.setDateFormat((DateFormat) dateFormat.clone());
|
||||||
|
// Need to rebuild the Client as objectMapper changes.
|
||||||
|
rebuildHttpClient();
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse the given string into Date object.
|
||||||
|
* @param str String
|
||||||
|
* @return Date
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
* @param date Date
|
||||||
|
* @return Date in string format
|
||||||
|
*/
|
||||||
|
public String formatDate(Date date) {
|
||||||
|
return dateFormat.format(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format the given parameter object into string.
|
||||||
|
* @param param Object
|
||||||
|
* @return Object in string format
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
* @param collectionFormat Collection format
|
||||||
|
* @param name Name
|
||||||
|
* @param value Value
|
||||||
|
* @return List of pair
|
||||||
|
*/
|
||||||
|
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||||
|
List<Pair> params = new ArrayList<Pair>();
|
||||||
|
|
||||||
|
// preconditions
|
||||||
|
if (name == null || name.isEmpty() || value == null) return params;
|
||||||
|
|
||||||
|
Collection<?> valueCollection;
|
||||||
|
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
|
||||||
|
String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
|
||||||
|
|
||||||
|
// create the params based on the collection format
|
||||||
|
if ("multi".equals(format)) {
|
||||||
|
for (Object item : valueCollection) {
|
||||||
|
params.add(new Pair(name, parameterToString(item)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
String delimiter = ",";
|
||||||
|
|
||||||
|
if ("csv".equals(format)) {
|
||||||
|
delimiter = ",";
|
||||||
|
} else if ("ssv".equals(format)) {
|
||||||
|
delimiter = " ";
|
||||||
|
} else if ("tsv".equals(format)) {
|
||||||
|
delimiter = "\t";
|
||||||
|
} else if ("pipes".equals(format)) {
|
||||||
|
delimiter = "|";
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder() ;
|
||||||
|
for (Object item : valueCollection) {
|
||||||
|
sb.append(delimiter);
|
||||||
|
sb.append(parameterToString(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
params.add(new Pair(name, sb.substring(1)));
|
||||||
|
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the given MIME is a JSON MIME.
|
||||||
|
* JSON MIME examples:
|
||||||
|
* application/json
|
||||||
|
* application/json; charset=UTF8
|
||||||
|
* APPLICATION/JSON
|
||||||
|
* @param mime MIME
|
||||||
|
* @return True if MIME type is boolean
|
||||||
|
*/
|
||||||
|
public boolean isJsonMime(String mime) {
|
||||||
|
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select the Accept header's value from the given accepts array:
|
||||||
|
* if JSON exists in the given array, use it;
|
||||||
|
* otherwise use all of them (joining into a string)
|
||||||
|
*
|
||||||
|
* @param accepts The accepts array to select from
|
||||||
|
* @return The Accept header to use. If the given array is empty,
|
||||||
|
* null will be returned (not to set the Accept header explicitly).
|
||||||
|
*/
|
||||||
|
public String selectHeaderAccept(String[] accepts) {
|
||||||
|
if (accepts.length == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (String accept : accepts) {
|
||||||
|
if (isJsonMime(accept)) {
|
||||||
|
return accept;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return StringUtil.join(accepts, ",");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select the Content-Type header's value from the given array:
|
||||||
|
* if JSON exists in the given array, use it;
|
||||||
|
* otherwise use the first one of the array.
|
||||||
|
*
|
||||||
|
* @param contentTypes The Content-Type array to select from
|
||||||
|
* @return The Content-Type header to use. If the given array is empty,
|
||||||
|
* JSON will be used.
|
||||||
|
*/
|
||||||
|
public String selectHeaderContentType(String[] contentTypes) {
|
||||||
|
if (contentTypes.length == 0) {
|
||||||
|
return "application/json";
|
||||||
|
}
|
||||||
|
for (String contentType : contentTypes) {
|
||||||
|
if (isJsonMime(contentType)) {
|
||||||
|
return contentType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return contentTypes[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape the given string to be used as URL query value.
|
||||||
|
* @param str String
|
||||||
|
* @return Escaped string
|
||||||
|
*/
|
||||||
|
public String escapeString(String str) {
|
||||||
|
try {
|
||||||
|
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
|
||||||
|
} catch (UnsupportedEncodingException e) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialize the given Java object into string according the given
|
||||||
|
* Content-Type (only JSON is supported for now).
|
||||||
|
* @param obj Object
|
||||||
|
* @param contentType Content type
|
||||||
|
* @param formParams Form parameters
|
||||||
|
* @return Object
|
||||||
|
* @throws ApiException API exception
|
||||||
|
*/
|
||||||
|
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
|
||||||
|
if (contentType.startsWith("multipart/form-data")) {
|
||||||
|
FormDataMultiPart mp = new FormDataMultiPart();
|
||||||
|
for (Entry<String, Object> param: formParams.entrySet()) {
|
||||||
|
if( param.getValue() instanceof List && !( ( List ) param.getValue() ).isEmpty()
|
||||||
|
&& ( ( List ) param.getValue() ).get( 0 ) instanceof File ) {
|
||||||
|
@SuppressWarnings( "unchecked" )
|
||||||
|
List<File> files = ( List<File> ) param.getValue();
|
||||||
|
for( File file : files ) {
|
||||||
|
mp.bodyPart( new FileDataBodyPart( param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE ) );
|
||||||
|
}
|
||||||
|
} else if (param.getValue() instanceof File) {
|
||||||
|
File file = (File) param.getValue();
|
||||||
|
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
|
||||||
|
} else {
|
||||||
|
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mp;
|
||||||
|
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
|
||||||
|
return this.getXWWWFormUrlencodedParams(formParams);
|
||||||
|
} else {
|
||||||
|
// We let Jersey attempt to serialize the body
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build full URL by concatenating base path, the given sub path and query parameters.
|
||||||
|
*
|
||||||
|
* @param path The sub path
|
||||||
|
* @param queryParams The query parameters
|
||||||
|
* @return The full URL
|
||||||
|
*/
|
||||||
|
private String buildUrl(String path, List<Pair> queryParams) {
|
||||||
|
final StringBuilder url = new StringBuilder();
|
||||||
|
url.append(basePath).append(path);
|
||||||
|
|
||||||
|
if (queryParams != null && !queryParams.isEmpty()) {
|
||||||
|
// support (constant) query string in `path`, e.g. "/posts?draft=1"
|
||||||
|
String prefix = path.contains("?") ? "&" : "?";
|
||||||
|
for (Pair param : queryParams) {
|
||||||
|
if (param.getValue() != null) {
|
||||||
|
if (prefix != null) {
|
||||||
|
url.append(prefix);
|
||||||
|
prefix = null;
|
||||||
|
} else {
|
||||||
|
url.append("&");
|
||||||
|
}
|
||||||
|
String value = parameterToString(param.getValue());
|
||||||
|
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
|
||||||
|
if (body != null && !formParams.isEmpty()) {
|
||||||
|
throw new ApiException(500, "Cannot have body and form params");
|
||||||
|
}
|
||||||
|
|
||||||
|
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||||
|
|
||||||
|
final String url = buildUrl(path, queryParams);
|
||||||
|
Builder builder;
|
||||||
|
if (accept == null) {
|
||||||
|
builder = httpClient.resource(url).getRequestBuilder();
|
||||||
|
} else {
|
||||||
|
builder = httpClient.resource(url).accept(accept);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String key : headerParams.keySet()) {
|
||||||
|
builder = builder.header(key, headerParams.get(key));
|
||||||
|
}
|
||||||
|
for (String key : defaultHeaderMap.keySet()) {
|
||||||
|
if (!headerParams.containsKey(key)) {
|
||||||
|
builder = builder.header(key, defaultHeaderMap.get(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientResponse response = null;
|
||||||
|
|
||||||
|
if ("GET".equals(method)) {
|
||||||
|
response = (ClientResponse) builder.get(ClientResponse.class);
|
||||||
|
} else if ("POST".equals(method)) {
|
||||||
|
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
|
||||||
|
} else if ("PUT".equals(method)) {
|
||||||
|
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
|
||||||
|
} else if ("DELETE".equals(method)) {
|
||||||
|
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
|
||||||
|
} else if ("PATCH".equals(method)) {
|
||||||
|
response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new ApiException(500, "unknown method type " + method);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke API by sending HTTP request with the given options.
|
||||||
|
*
|
||||||
|
* @param <T> Type
|
||||||
|
* @param path The sub-path of the HTTP URL
|
||||||
|
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
|
||||||
|
* @param queryParams The query parameters
|
||||||
|
* @param body The request body object - if it is not binary, otherwise null
|
||||||
|
* @param headerParams The header parameters
|
||||||
|
* @param formParams The form parameters
|
||||||
|
* @param accept The request's Accept header
|
||||||
|
* @param contentType The request's Content-Type header
|
||||||
|
* @param authNames The authentications to apply
|
||||||
|
* @param returnType Return type
|
||||||
|
* @return The response body in type of string
|
||||||
|
* @throws ApiException API exception
|
||||||
|
*/
|
||||||
|
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
|
||||||
|
|
||||||
|
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
|
||||||
|
|
||||||
|
statusCode = response.getStatusInfo().getStatusCode();
|
||||||
|
responseHeaders = response.getHeaders();
|
||||||
|
|
||||||
|
if(response.getStatusInfo().getStatusCode() == ClientResponse.Status.NO_CONTENT.getStatusCode()) {
|
||||||
|
return null;
|
||||||
|
} else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
|
||||||
|
if (returnType == null)
|
||||||
|
return null;
|
||||||
|
else
|
||||||
|
return response.getEntity(returnType);
|
||||||
|
} else {
|
||||||
|
String message = "error";
|
||||||
|
String respBody = null;
|
||||||
|
if (response.hasEntity()) {
|
||||||
|
try {
|
||||||
|
respBody = response.getEntity(String.class);
|
||||||
|
message = respBody;
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
// e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new ApiException(
|
||||||
|
response.getStatusInfo().getStatusCode(),
|
||||||
|
message,
|
||||||
|
response.getHeaders(),
|
||||||
|
respBody);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update query and header parameters based on authentication settings.
|
||||||
|
*
|
||||||
|
* @param authNames The authentications to apply
|
||||||
|
* @param queryParams Query parameters
|
||||||
|
* @param headerParams Header parameters
|
||||||
|
*/
|
||||||
|
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
|
||||||
|
for (String authName : authNames) {
|
||||||
|
Authentication auth = authentications.get(authName);
|
||||||
|
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||||
|
auth.applyToParams(queryParams, headerParams);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encode the given form parameters as request body.
|
||||||
|
* @param formParams Form parameters
|
||||||
|
* @return HTTP form encoded parameters
|
||||||
|
*/
|
||||||
|
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
|
||||||
|
StringBuilder formParamBuilder = new StringBuilder();
|
||||||
|
|
||||||
|
for (Entry<String, Object> param : formParams.entrySet()) {
|
||||||
|
String valueStr = parameterToString(param.getValue());
|
||||||
|
try {
|
||||||
|
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
|
||||||
|
.append("=")
|
||||||
|
.append(URLEncoder.encode(valueStr, "utf8"));
|
||||||
|
formParamBuilder.append("&");
|
||||||
|
} catch (UnsupportedEncodingException e) {
|
||||||
|
// move on to next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String encodedFormParams = formParamBuilder.toString();
|
||||||
|
if (encodedFormParams.endsWith("&")) {
|
||||||
|
encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return encodedFormParams;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,770 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
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.GenericType;
|
||||||
|
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.client.ClientProperties;
|
||||||
|
import org.glassfish.jersey.filter.LoggingFilter;
|
||||||
|
import org.glassfish.jersey.jackson.JacksonFeature;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
|
||||||
|
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||||
|
import org.glassfish.jersey.media.multipart.MultiPart;
|
||||||
|
import org.glassfish.jersey.media.multipart.MultiPartFeature;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
{{^supportJava6}}
|
||||||
|
import java.nio.file.Files;
|
||||||
|
{{/supportJava6}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
{{/supportJava6}}
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import {{invokerPackage}}.auth.Authentication;
|
||||||
|
import {{invokerPackage}}.auth.HttpBasicAuth;
|
||||||
|
import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||||
|
import {{invokerPackage}}.auth.OAuth;
|
||||||
|
|
||||||
|
{{>generatedAnnotation}}
|
||||||
|
public class ApiClient {
|
||||||
|
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||||
|
private String basePath = "{{{basePath}}}";
|
||||||
|
private boolean debugging = false;
|
||||||
|
private int connectionTimeout = 0;
|
||||||
|
|
||||||
|
private Client httpClient;
|
||||||
|
private JSON json;
|
||||||
|
private String tempFolderPath = null;
|
||||||
|
|
||||||
|
private Map<String, Authentication> authentications;
|
||||||
|
|
||||||
|
private int statusCode;
|
||||||
|
private Map<String, List<String>> responseHeaders;
|
||||||
|
|
||||||
|
private DateFormat dateFormat;
|
||||||
|
|
||||||
|
public ApiClient() {
|
||||||
|
json = new JSON();
|
||||||
|
httpClient = buildHttpClient(debugging);
|
||||||
|
|
||||||
|
this.dateFormat = new RFC3339DateFormat();
|
||||||
|
|
||||||
|
// Set default User-Agent.
|
||||||
|
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
|
||||||
|
|
||||||
|
// Setup authentications (key: authentication name, value: authentication).
|
||||||
|
authentications = new HashMap<String, Authentication>();{{#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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the JSON instance to do JSON serialization and deserialization.
|
||||||
|
* @return JSON
|
||||||
|
*/
|
||||||
|
public JSON getJSON() {
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Client getHttpClient() {
|
||||||
|
return httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient setHttpClient(Client httpClient) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBasePath() {
|
||||||
|
return basePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient setBasePath(String basePath) {
|
||||||
|
this.basePath = basePath;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the status code of the previous request
|
||||||
|
* @return Status code
|
||||||
|
*/
|
||||||
|
public int getStatusCode() {
|
||||||
|
return statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the response headers of the previous request
|
||||||
|
* @return Response headers
|
||||||
|
*/
|
||||||
|
public Map<String, List<String>> getResponseHeaders() {
|
||||||
|
return responseHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get authentications (key: authentication name, value: authentication).
|
||||||
|
* @return Map of authentication object
|
||||||
|
*/
|
||||||
|
public Map<String, Authentication> getAuthentications() {
|
||||||
|
return authentications;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get authentication for the given name.
|
||||||
|
*
|
||||||
|
* @param authName The authentication name
|
||||||
|
* @return The authentication, null if not found
|
||||||
|
*/
|
||||||
|
public Authentication getAuthentication(String authName) {
|
||||||
|
return authentications.get(authName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set username for the first HTTP basic authentication.
|
||||||
|
* @param username Username
|
||||||
|
*/
|
||||||
|
public void setUsername(String username) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof HttpBasicAuth) {
|
||||||
|
((HttpBasicAuth) auth).setUsername(username);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set password for the first HTTP basic authentication.
|
||||||
|
* @param password Password
|
||||||
|
*/
|
||||||
|
public void setPassword(String password) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof HttpBasicAuth) {
|
||||||
|
((HttpBasicAuth) auth).setPassword(password);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set API key value for the first API key authentication.
|
||||||
|
* @param apiKey API key
|
||||||
|
*/
|
||||||
|
public void setApiKey(String apiKey) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof ApiKeyAuth) {
|
||||||
|
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No API key authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set API key prefix for the first API key authentication.
|
||||||
|
* @param apiKeyPrefix API key prefix
|
||||||
|
*/
|
||||||
|
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof ApiKeyAuth) {
|
||||||
|
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No API key authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to set access token for the first OAuth2 authentication.
|
||||||
|
* @param accessToken Access token
|
||||||
|
*/
|
||||||
|
public void setAccessToken(String accessToken) {
|
||||||
|
for (Authentication auth : authentications.values()) {
|
||||||
|
if (auth instanceof OAuth) {
|
||||||
|
((OAuth) auth).setAccessToken(accessToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("No OAuth2 authentication configured!");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the User-Agent header's value (by adding to the default header map).
|
||||||
|
* @param userAgent Http user agent
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setUserAgent(String userAgent) {
|
||||||
|
addDefaultHeader("User-Agent", userAgent);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a default header.
|
||||||
|
*
|
||||||
|
* @param key The header's key
|
||||||
|
* @param value The header's value
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient addDefaultHeader(String key, String value) {
|
||||||
|
defaultHeaderMap.put(key, value);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check that whether debugging is enabled for this API client.
|
||||||
|
* @return True if debugging is switched on
|
||||||
|
*/
|
||||||
|
public boolean isDebugging() {
|
||||||
|
return debugging;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable/disable debugging for this API client.
|
||||||
|
*
|
||||||
|
* @param debugging To enable (true) or disable (false) debugging
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setDebugging(boolean debugging) {
|
||||||
|
this.debugging = debugging;
|
||||||
|
// Rebuild HTTP Client according to the new "debugging" value.
|
||||||
|
this.httpClient = buildHttpClient(debugging);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The path of temporary folder used to store downloaded files from endpoints
|
||||||
|
* with file response. The default value is <code>null</code>, i.e. using
|
||||||
|
* the system's default tempopary folder.
|
||||||
|
*
|
||||||
|
* @return Temp folder path
|
||||||
|
*/
|
||||||
|
public String getTempFolderPath() {
|
||||||
|
return tempFolderPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set temp folder path
|
||||||
|
* @param tempFolderPath Temp folder path
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setTempFolderPath(String tempFolderPath) {
|
||||||
|
this.tempFolderPath = tempFolderPath;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect timeout (in milliseconds).
|
||||||
|
* @return Connection timeout
|
||||||
|
*/
|
||||||
|
public int getConnectTimeout() {
|
||||||
|
return connectionTimeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the connect timeout (in milliseconds).
|
||||||
|
* A value of 0 means no timeout, otherwise values must be between 1 and
|
||||||
|
* {@link Integer#MAX_VALUE}.
|
||||||
|
* @param connectionTimeout Connection timeout in milliseconds
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setConnectTimeout(int connectionTimeout) {
|
||||||
|
this.connectionTimeout = connectionTimeout;
|
||||||
|
httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the date format used to parse/format date parameters.
|
||||||
|
* @return Date format
|
||||||
|
*/
|
||||||
|
public DateFormat getDateFormat() {
|
||||||
|
return dateFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the date format used to parse/format date parameters.
|
||||||
|
* @param dateFormat Date format
|
||||||
|
* @return API client
|
||||||
|
*/
|
||||||
|
public ApiClient setDateFormat(DateFormat dateFormat) {
|
||||||
|
this.dateFormat = dateFormat;
|
||||||
|
// also set the date format for model (de)serialization with Date properties
|
||||||
|
this.json.setDateFormat((DateFormat) dateFormat.clone());
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse the given string into Date object.
|
||||||
|
* @param str String
|
||||||
|
* @return Date
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
* @param date Date
|
||||||
|
* @return Date in string format
|
||||||
|
*/
|
||||||
|
public String formatDate(Date date) {
|
||||||
|
return dateFormat.format(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format the given parameter object into string.
|
||||||
|
* @param param Object
|
||||||
|
* @return Object in string format
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
* @param collectionFormat Collection format
|
||||||
|
* @param name Name
|
||||||
|
* @param value Value
|
||||||
|
* @return List of pairs
|
||||||
|
*/
|
||||||
|
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||||
|
List<Pair> params = new ArrayList<Pair>();
|
||||||
|
|
||||||
|
// preconditions
|
||||||
|
if (name == null || name.isEmpty() || value == null) return params;
|
||||||
|
|
||||||
|
Collection valueCollection;
|
||||||
|
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 (default: csv)
|
||||||
|
String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat);
|
||||||
|
|
||||||
|
// create the params based on the collection format
|
||||||
|
if ("multi".equals(format)) {
|
||||||
|
for (Object item : valueCollection) {
|
||||||
|
params.add(new Pair(name, parameterToString(item)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
String delimiter = ",";
|
||||||
|
|
||||||
|
if ("csv".equals(format)) {
|
||||||
|
delimiter = ",";
|
||||||
|
} else if ("ssv".equals(format)) {
|
||||||
|
delimiter = " ";
|
||||||
|
} else if ("tsv".equals(format)) {
|
||||||
|
delimiter = "\t";
|
||||||
|
} else if ("pipes".equals(format)) {
|
||||||
|
delimiter = "|";
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder() ;
|
||||||
|
for (Object item : valueCollection) {
|
||||||
|
sb.append(delimiter);
|
||||||
|
sb.append(parameterToString(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
params.add(new Pair(name, sb.substring(1)));
|
||||||
|
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the given MIME is a JSON MIME.
|
||||||
|
* JSON MIME examples:
|
||||||
|
* application/json
|
||||||
|
* application/json; charset=UTF8
|
||||||
|
* APPLICATION/JSON
|
||||||
|
* @param mime MIME
|
||||||
|
* @return True if the MIME type is JSON
|
||||||
|
*/
|
||||||
|
public boolean isJsonMime(String mime) {
|
||||||
|
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select the Accept header's value from the given accepts array:
|
||||||
|
* if JSON exists in the given array, use it;
|
||||||
|
* otherwise use all of them (joining into a string)
|
||||||
|
*
|
||||||
|
* @param accepts The accepts array to select from
|
||||||
|
* @return The Accept header to use. If the given array is empty,
|
||||||
|
* null will be returned (not to set the Accept header explicitly).
|
||||||
|
*/
|
||||||
|
public String selectHeaderAccept(String[] accepts) {
|
||||||
|
if (accepts.length == 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (String accept : accepts) {
|
||||||
|
if (isJsonMime(accept)) {
|
||||||
|
return accept;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return StringUtil.join(accepts, ",");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select the Content-Type header's value from the given array:
|
||||||
|
* if JSON exists in the given array, use it;
|
||||||
|
* otherwise use the first one of the array.
|
||||||
|
*
|
||||||
|
* @param contentTypes The Content-Type array to select from
|
||||||
|
* @return The Content-Type header to use. If the given array is empty,
|
||||||
|
* JSON will be used.
|
||||||
|
*/
|
||||||
|
public String selectHeaderContentType(String[] contentTypes) {
|
||||||
|
if (contentTypes.length == 0) {
|
||||||
|
return "application/json";
|
||||||
|
}
|
||||||
|
for (String contentType : contentTypes) {
|
||||||
|
if (isJsonMime(contentType)) {
|
||||||
|
return contentType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return contentTypes[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape the given string to be used as URL query value.
|
||||||
|
* @param str String
|
||||||
|
* @return Escaped string
|
||||||
|
*/
|
||||||
|
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).
|
||||||
|
* @param obj Object
|
||||||
|
* @param formParams Form parameters
|
||||||
|
* @param contentType Context type
|
||||||
|
* @return Entity
|
||||||
|
* @throws ApiException API exception
|
||||||
|
*/
|
||||||
|
public Entity<?> serialize(Object obj, Map<String, Object> formParams, String contentType) throws ApiException {
|
||||||
|
Entity<?> entity;
|
||||||
|
if (contentType.startsWith("multipart/form-data")) {
|
||||||
|
MultiPart multiPart = new MultiPart();
|
||||||
|
for (Entry<String, Object> param: formParams.entrySet()) {
|
||||||
|
if (param.getValue() instanceof File) {
|
||||||
|
File file = (File) param.getValue();
|
||||||
|
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey())
|
||||||
|
.fileName(file.getName()).size(file.length()).build();
|
||||||
|
multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
|
||||||
|
} else {
|
||||||
|
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build();
|
||||||
|
multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE);
|
||||||
|
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
|
||||||
|
Form form = new Form();
|
||||||
|
for (Entry<String, Object> param: formParams.entrySet()) {
|
||||||
|
form.param(param.getKey(), parameterToString(param.getValue()));
|
||||||
|
}
|
||||||
|
entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||||
|
} else {
|
||||||
|
// We let jersey handle the serialization
|
||||||
|
entity = Entity.entity(obj, contentType);
|
||||||
|
}
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deserialize response body to Java object according to the Content-Type.
|
||||||
|
* @param <T> Type
|
||||||
|
* @param response Response
|
||||||
|
* @param returnType Return type
|
||||||
|
* @return Deserialize object
|
||||||
|
* @throws ApiException API exception
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T> T deserialize(Response response, GenericType<T> returnType) throws ApiException {
|
||||||
|
if (response == null || returnType == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("byte[]".equals(returnType.toString())) {
|
||||||
|
// Handle binary response (byte array).
|
||||||
|
return (T) response.readEntity(byte[].class);
|
||||||
|
} else if (returnType.getRawType() == File.class) {
|
||||||
|
// Handle file downloading.
|
||||||
|
T file = (T) downloadFileFromResponse(response);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentType = null;
|
||||||
|
List<Object> 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");
|
||||||
|
|
||||||
|
return response.readEntity(returnType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Download file from the given response.
|
||||||
|
* @param response Response
|
||||||
|
* @return File
|
||||||
|
* @throws ApiException If fail to read file content from response and write to disk
|
||||||
|
*/
|
||||||
|
public File downloadFileFromResponse(Response response) throws ApiException {
|
||||||
|
try {
|
||||||
|
File file = prepareDownloadFile(response);
|
||||||
|
{{^supportJava6}}
|
||||||
|
Files.copy(response.readEntity(InputStream.class), file.toPath());
|
||||||
|
{{/supportJava6}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
// Java6 falls back to commons.io for file copying
|
||||||
|
FileUtils.copyToFile(response.readEntity(InputStream.class), file);
|
||||||
|
{{/supportJava6}}
|
||||||
|
return file;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new ApiException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public File prepareDownloadFile(Response response) throws IOException {
|
||||||
|
String filename = null;
|
||||||
|
String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition");
|
||||||
|
if (contentDisposition != null && !"".equals(contentDisposition)) {
|
||||||
|
// Get filename from the Content-Disposition header.
|
||||||
|
Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
|
||||||
|
Matcher matcher = pattern.matcher(contentDisposition);
|
||||||
|
if (matcher.find())
|
||||||
|
filename = matcher.group(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
String prefix;
|
||||||
|
String suffix = null;
|
||||||
|
if (filename == null) {
|
||||||
|
prefix = "download-";
|
||||||
|
suffix = "";
|
||||||
|
} else {
|
||||||
|
int pos = filename.lastIndexOf('.');
|
||||||
|
if (pos == -1) {
|
||||||
|
prefix = filename + "-";
|
||||||
|
} else {
|
||||||
|
prefix = filename.substring(0, pos) + "-";
|
||||||
|
suffix = filename.substring(pos);
|
||||||
|
}
|
||||||
|
// File.createTempFile requires the prefix to be at least three characters long
|
||||||
|
if (prefix.length() < 3)
|
||||||
|
prefix = "download-";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tempFolderPath == null)
|
||||||
|
return File.createTempFile(prefix, suffix);
|
||||||
|
else
|
||||||
|
return File.createTempFile(prefix, suffix, new File(tempFolderPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke API by sending HTTP request with the given options.
|
||||||
|
*
|
||||||
|
* @param <T> Type
|
||||||
|
* @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
|
||||||
|
* @throws ApiException API exception
|
||||||
|
*/
|
||||||
|
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
|
||||||
|
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||||
|
|
||||||
|
// Not using `.target(this.basePath).path(path)` below,
|
||||||
|
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
|
||||||
|
WebTarget target = httpClient.target(this.basePath + path);
|
||||||
|
|
||||||
|
if (queryParams != null) {
|
||||||
|
for (Pair queryParam : queryParams) {
|
||||||
|
if (queryParam.getValue() != null) {
|
||||||
|
target = target.queryParam(queryParam.getName(), queryParam.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Invocation.Builder invocationBuilder = target.request().accept(accept);
|
||||||
|
|
||||||
|
for (Entry<String, String> entry : headerParams.entrySet()) {
|
||||||
|
String value = entry.getValue();
|
||||||
|
if (value != null) {
|
||||||
|
invocationBuilder = invocationBuilder.header(entry.getKey(), value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Entry<String, String> entry : defaultHeaderMap.entrySet()) {
|
||||||
|
String key = entry.getKey();
|
||||||
|
if (!headerParams.containsKey(key)) {
|
||||||
|
String value = entry.getValue();
|
||||||
|
if (value != null) {
|
||||||
|
invocationBuilder = invocationBuilder.header(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Entity<?> entity = serialize(body, formParams, contentType);
|
||||||
|
|
||||||
|
Response response;
|
||||||
|
|
||||||
|
if ("GET".equals(method)) {
|
||||||
|
response = invocationBuilder.get();
|
||||||
|
} else if ("POST".equals(method)) {
|
||||||
|
response = invocationBuilder.post(entity);
|
||||||
|
} else if ("PUT".equals(method)) {
|
||||||
|
response = invocationBuilder.put(entity);
|
||||||
|
} else if ("DELETE".equals(method)) {
|
||||||
|
response = invocationBuilder.delete();
|
||||||
|
} else if ("PATCH".equals(method)) {
|
||||||
|
response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity);
|
||||||
|
} else {
|
||||||
|
throw new ApiException(500, "unknown method type " + method);
|
||||||
|
}
|
||||||
|
|
||||||
|
statusCode = response.getStatusInfo().getStatusCode();
|
||||||
|
responseHeaders = buildResponseHeaders(response);
|
||||||
|
|
||||||
|
if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) {
|
||||||
|
return null;
|
||||||
|
} else if (response.getStatusInfo().getFamily() == 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new ApiException(
|
||||||
|
response.getStatus(),
|
||||||
|
message,
|
||||||
|
buildResponseHeaders(response),
|
||||||
|
respBody);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the Client used to make HTTP requests.
|
||||||
|
* @param debugging Debug setting
|
||||||
|
* @return Client
|
||||||
|
*/
|
||||||
|
private Client buildHttpClient(boolean debugging) {
|
||||||
|
final ClientConfig clientConfig = new ClientConfig();
|
||||||
|
clientConfig.register(MultiPartFeature.class);
|
||||||
|
clientConfig.register(json);
|
||||||
|
clientConfig.register(JacksonFeature.class);
|
||||||
|
if (debugging) {
|
||||||
|
clientConfig.register(LoggingFilter.class);
|
||||||
|
}
|
||||||
|
return ClientBuilder.newClient(clientConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, List<String>> buildResponseHeaders(Response response) {
|
||||||
|
Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
|
||||||
|
for (Entry<String, List<Object>> entry: response.getHeaders().entrySet()) {
|
||||||
|
List<Object> values = entry.getValue();
|
||||||
|
List<String> headers = new ArrayList<String>();
|
||||||
|
for (Object o : values) {
|
||||||
|
headers.add(String.valueOf(o));
|
||||||
|
}
|
||||||
|
responseHeaders.put(entry.getKey(), headers);
|
||||||
|
}
|
||||||
|
return responseHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update query and header parameters based on authentication settings.
|
||||||
|
*
|
||||||
|
* @param authNames The authentications to apply
|
||||||
|
*/
|
||||||
|
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
|
||||||
|
for (String authName : authNames) {
|
||||||
|
Authentication auth = authentications.get(authName);
|
||||||
|
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||||
|
auth.applyToParams(queryParams, headerParams);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,50 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
package {{invokerPackage}};
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.*;
|
||||||
|
import com.fasterxml.jackson.databind.*;
|
||||||
|
{{#java8}}
|
||||||
|
import com.fasterxml.jackson.datatype.jsr310.*;
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
import com.fasterxml.jackson.datatype.joda.*;
|
||||||
|
{{/java8}}
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
|
||||||
|
import javax.ws.rs.ext.ContextResolver;
|
||||||
|
|
||||||
|
{{>generatedAnnotation}}
|
||||||
|
public class JSON implements ContextResolver<ObjectMapper> {
|
||||||
|
private ObjectMapper mapper;
|
||||||
|
|
||||||
|
public JSON() {
|
||||||
|
mapper = new ObjectMapper();
|
||||||
|
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||||
|
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||||
|
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||||
|
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
||||||
|
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
||||||
|
mapper.setDateFormat(new RFC3339DateFormat());
|
||||||
|
{{#java8}}
|
||||||
|
mapper.registerModule(new JavaTimeModule());
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
mapper.registerModule(new JodaModule());
|
||||||
|
{{/java8}}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the date format for JSON (de)serialization with Date properties.
|
||||||
|
* @param dateFormat Date format
|
||||||
|
*/
|
||||||
|
public void setDateFormat(DateFormat dateFormat) {
|
||||||
|
mapper.setDateFormat(dateFormat);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ObjectMapper getContext(Class<?> type) {
|
||||||
|
return mapper;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,105 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
package {{package}};
|
||||||
|
|
||||||
|
import {{invokerPackage}}.ApiException;
|
||||||
|
import {{invokerPackage}}.ApiClient;
|
||||||
|
import {{invokerPackage}}.Configuration;
|
||||||
|
import {{invokerPackage}}.Pair;
|
||||||
|
|
||||||
|
import javax.ws.rs.core.GenericType;
|
||||||
|
|
||||||
|
{{#imports}}import {{import}};
|
||||||
|
{{/imports}}
|
||||||
|
|
||||||
|
{{^fullJavaUtil}}
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
{{/fullJavaUtil}}
|
||||||
|
|
||||||
|
{{>generatedAnnotation}}
|
||||||
|
{{#operations}}
|
||||||
|
public class {{classname}} {
|
||||||
|
private ApiClient {{localVariablePrefix}}apiClient;
|
||||||
|
|
||||||
|
public {{classname}}() {
|
||||||
|
this(Configuration.getDefaultApiClient());
|
||||||
|
}
|
||||||
|
|
||||||
|
public {{classname}}(ApiClient apiClient) {
|
||||||
|
this.{{localVariablePrefix}}apiClient = apiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiClient getApiClient() {
|
||||||
|
return {{localVariablePrefix}}apiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setApiClient(ApiClient apiClient) {
|
||||||
|
this.{{localVariablePrefix}}apiClient = apiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
{{#operation}}
|
||||||
|
/**
|
||||||
|
* {{summary}}
|
||||||
|
* {{notes}}
|
||||||
|
{{#allParams}}
|
||||||
|
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
|
||||||
|
{{/allParams}}
|
||||||
|
{{#returnType}}
|
||||||
|
* @return {{returnType}}
|
||||||
|
{{/returnType}}
|
||||||
|
* @throws ApiException if fails to make API call
|
||||||
|
*/
|
||||||
|
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
|
||||||
|
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
|
||||||
|
{{#allParams}}{{#required}}
|
||||||
|
// verify the required parameter '{{paramName}}' is set
|
||||||
|
if ({{paramName}} == null) {
|
||||||
|
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{operationId}}");
|
||||||
|
}
|
||||||
|
{{/required}}{{/allParams}}
|
||||||
|
// create path and map variables
|
||||||
|
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
|
||||||
|
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
|
||||||
|
|
||||||
|
// query params
|
||||||
|
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
|
||||||
|
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
|
||||||
|
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
|
||||||
|
|
||||||
|
{{#queryParams}}
|
||||||
|
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
|
||||||
|
{{/queryParams}}
|
||||||
|
|
||||||
|
{{#headerParams}}if ({{paramName}} != null)
|
||||||
|
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));
|
||||||
|
{{/headerParams}}
|
||||||
|
|
||||||
|
{{#formParams}}if ({{paramName}} != null)
|
||||||
|
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});
|
||||||
|
{{/formParams}}
|
||||||
|
|
||||||
|
final String[] {{localVariablePrefix}}localVarAccepts = {
|
||||||
|
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
|
||||||
|
};
|
||||||
|
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
|
||||||
|
|
||||||
|
final String[] {{localVariablePrefix}}localVarContentTypes = {
|
||||||
|
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
|
||||||
|
};
|
||||||
|
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
|
||||||
|
|
||||||
|
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
|
||||||
|
|
||||||
|
{{#returnType}}
|
||||||
|
GenericType<{{{returnType}}}> {{localVariablePrefix}}localVarReturnType = new GenericType<{{{returnType}}}>() {};
|
||||||
|
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, {{localVariablePrefix}}localVarReturnType);
|
||||||
|
{{/returnType}}{{^returnType}}
|
||||||
|
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAccept, {{localVariablePrefix}}localVarContentType, {{localVariablePrefix}}localVarAuthNames, null);
|
||||||
|
{{/returnType}}
|
||||||
|
}
|
||||||
|
{{/operation}}
|
||||||
|
}
|
||||||
|
{{/operations}}
|
@ -0,0 +1,144 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
apply plugin: 'idea'
|
||||||
|
apply plugin: 'eclipse'
|
||||||
|
|
||||||
|
group = '{{groupId}}'
|
||||||
|
version = '{{artifactVersion}}'
|
||||||
|
|
||||||
|
buildscript {
|
||||||
|
repositories {
|
||||||
|
jcenter()
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
classpath 'com.android.tools.build:gradle:1.5.+'
|
||||||
|
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
jcenter()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if(hasProperty('target') && target == 'android') {
|
||||||
|
|
||||||
|
apply plugin: 'com.android.library'
|
||||||
|
apply plugin: 'com.github.dcendents.android-maven'
|
||||||
|
|
||||||
|
android {
|
||||||
|
compileSdkVersion 23
|
||||||
|
buildToolsVersion '23.0.2'
|
||||||
|
defaultConfig {
|
||||||
|
minSdkVersion 14
|
||||||
|
targetSdkVersion 23
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
{{#java8}}
|
||||||
|
sourceCompatibility JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility JavaVersion.VERSION_1_8
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
sourceCompatibility JavaVersion.VERSION_1_7
|
||||||
|
targetCompatibility JavaVersion.VERSION_1_7
|
||||||
|
{{/java8}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename the aar correctly
|
||||||
|
libraryVariants.all { variant ->
|
||||||
|
variant.outputs.each { output ->
|
||||||
|
def outputFile = output.outputFile
|
||||||
|
if (outputFile != null && outputFile.name.endsWith('.aar')) {
|
||||||
|
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
|
||||||
|
output.outputFile = new File(outputFile.parent, fileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
provided 'javax.annotation:jsr250-api:1.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEvaluate {
|
||||||
|
android.libraryVariants.all { variant ->
|
||||||
|
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
|
||||||
|
task.description = "Create jar artifact for ${variant.name}"
|
||||||
|
task.dependsOn variant.javaCompile
|
||||||
|
task.from variant.javaCompile.destinationDir
|
||||||
|
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
|
||||||
|
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
|
||||||
|
artifacts.add('archives', task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
task sourcesJar(type: Jar) {
|
||||||
|
from android.sourceSets.main.java.srcDirs
|
||||||
|
classifier = 'sources'
|
||||||
|
}
|
||||||
|
|
||||||
|
artifacts {
|
||||||
|
archives sourcesJar
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
|
||||||
|
apply plugin: 'java'
|
||||||
|
apply plugin: 'maven'
|
||||||
|
{{#java8}}
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_7
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_7
|
||||||
|
{{/java8}}
|
||||||
|
|
||||||
|
install {
|
||||||
|
repositories.mavenInstaller {
|
||||||
|
pom.artifactId = '{{artifactId}}'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
task execute(type:JavaExec) {
|
||||||
|
main = System.getProperty('mainClass')
|
||||||
|
classpath = sourceSets.main.runtimeClasspath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ext {
|
||||||
|
swagger_annotations_version = "1.5.8"
|
||||||
|
jackson_version = "2.7.5"
|
||||||
|
jersey_version = "2.22.2"
|
||||||
|
{{^java8}}
|
||||||
|
jodatime_version = "2.9.4"
|
||||||
|
{{/java8}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
commons_io_version=2.5
|
||||||
|
commons_lang3_version=3.5
|
||||||
|
{{/supportJava6}}
|
||||||
|
junit_version = "4.12"
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
|
||||||
|
compile "org.glassfish.jersey.core:jersey-client:$jersey_version"
|
||||||
|
compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version"
|
||||||
|
compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version"
|
||||||
|
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
|
||||||
|
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
|
||||||
|
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
|
||||||
|
{{#java8}}
|
||||||
|
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
|
||||||
|
compile "joda-time:joda-time:$jodatime_version"
|
||||||
|
{{/java8}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
compile "commons-io:commons-io:$commons_io_version"
|
||||||
|
compile "org.apache.commons:commons-lang3:$commons_lang3_version"
|
||||||
|
{{/supportJava6}}
|
||||||
|
compile "com.brsanthu:migbase64:2.2"
|
||||||
|
testCompile "junit:junit:$junit_version"
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
lazy val root = (project in file(".")).
|
||||||
|
settings(
|
||||||
|
organization := "{{groupId}}",
|
||||||
|
name := "{{artifactId}}",
|
||||||
|
version := "{{artifactVersion}}",
|
||||||
|
scalaVersion := "2.11.4",
|
||||||
|
scalacOptions ++= Seq("-feature"),
|
||||||
|
javacOptions in compile ++= Seq("-Xlint:deprecation"),
|
||||||
|
publishArtifact in (Compile, packageDoc) := false,
|
||||||
|
resolvers += Resolver.mavenLocal,
|
||||||
|
libraryDependencies ++= Seq(
|
||||||
|
"io.swagger" % "swagger-annotations" % "1.5.8",
|
||||||
|
"org.glassfish.jersey.core" % "jersey-client" % "2.22.2",
|
||||||
|
"org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2",
|
||||||
|
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2",
|
||||||
|
"com.fasterxml.jackson.core" % "jackson-core" % "2.7.5",
|
||||||
|
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5",
|
||||||
|
"com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5",
|
||||||
|
{{#java8}}
|
||||||
|
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5",
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5",
|
||||||
|
"joda-time" % "joda-time" % "2.9.4",
|
||||||
|
{{/java8}}
|
||||||
|
"com.brsanthu" % "migbase64" % "2.2",
|
||||||
|
{{#supportJava6}}
|
||||||
|
"org.apache.commons" % "commons-lang3" % "3.5",
|
||||||
|
"commons-io" % "commons-io" % "2.5",
|
||||||
|
{{/supportJava6}}
|
||||||
|
"junit" % "junit" % "4.12" % "test",
|
||||||
|
"com.novocode" % "junit-interface" % "0.10" % "test"
|
||||||
|
)
|
||||||
|
)
|
@ -0,0 +1,289 @@
|
|||||||
|
//overloaded template file within library folder to add this comment
|
||||||
|
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>{{groupId}}</groupId>
|
||||||
|
<artifactId>{{artifactId}}</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>{{artifactId}}</name>
|
||||||
|
<version>{{artifactVersion}}</version>
|
||||||
|
<url>{{artifactUrl}}</url>
|
||||||
|
<description>{{artifactDescription}}</description>
|
||||||
|
<scm>
|
||||||
|
<connection>{{scmConnection}}</connection>
|
||||||
|
<developerConnection>{{scmDeveloperConnection}}</developerConnection>
|
||||||
|
<url>{{scmUrl}}</url>
|
||||||
|
</scm>
|
||||||
|
<prerequisites>
|
||||||
|
<maven>2.2.0</maven>
|
||||||
|
</prerequisites>
|
||||||
|
|
||||||
|
<licenses>
|
||||||
|
<license>
|
||||||
|
<name>{{licenseName}}</name>
|
||||||
|
<url>{{licenseUrl}}</url>
|
||||||
|
<distribution>repo</distribution>
|
||||||
|
</license>
|
||||||
|
</licenses>
|
||||||
|
|
||||||
|
<developers>
|
||||||
|
<developer>
|
||||||
|
<name>{{developerName}}</name>
|
||||||
|
<email>{{developerEmail}}</email>
|
||||||
|
<organization>{{developerOrganization}}</organization>
|
||||||
|
<organizationUrl>{{developerOrganizationUrl}}</organizationUrl>
|
||||||
|
</developer>
|
||||||
|
</developers>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.12</version>
|
||||||
|
<configuration>
|
||||||
|
<systemProperties>
|
||||||
|
<property>
|
||||||
|
<name>loggerPath</name>
|
||||||
|
<value>conf/log4j.properties</value>
|
||||||
|
</property>
|
||||||
|
</systemProperties>
|
||||||
|
<argLine>-Xms512m -Xmx1500m</argLine>
|
||||||
|
<parallel>methods</parallel>
|
||||||
|
<forkMode>pertest</forkMode>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-dependencies</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<!-- attach test jar -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<version>2.6</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
<goal>test-jar</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>build-helper-maven-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>add_sources</id>
|
||||||
|
<phase>generate-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>add-source</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sources>
|
||||||
|
<source>src/main/java</source>
|
||||||
|
</sources>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>add_test_sources</id>
|
||||||
|
<phase>generate-test-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>add-test-source</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sources>
|
||||||
|
<source>src/test/java</source>
|
||||||
|
</sources>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>2.5.1</version>
|
||||||
|
<configuration>
|
||||||
|
{{#java8}}
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
<source>1.7</source>
|
||||||
|
<target>1.7</target>
|
||||||
|
{{/java8}}
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
|
<version>2.10.4</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>attach-javadocs</id>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-source-plugin</artifactId>
|
||||||
|
<version>2.2.1</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>attach-sources</id>
|
||||||
|
<goals>
|
||||||
|
<goal>jar-no-fork</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>sign-artifacts</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-gpg-plugin</artifactId>
|
||||||
|
<version>1.5</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>sign-artifacts</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>sign</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.swagger</groupId>
|
||||||
|
<artifactId>swagger-annotations</artifactId>
|
||||||
|
<version>${swagger-core-version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- HTTP client: jersey-client -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jersey.core</groupId>
|
||||||
|
<artifactId>jersey-client</artifactId>
|
||||||
|
<version>${jersey-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jersey.media</groupId>
|
||||||
|
<artifactId>jersey-media-multipart</artifactId>
|
||||||
|
<version>${jersey-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.glassfish.jersey.media</groupId>
|
||||||
|
<artifactId>jersey-media-json-jackson</artifactId>
|
||||||
|
<version>${jersey-version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- JSON processing: jackson -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-core</artifactId>
|
||||||
|
<version>${jackson-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-annotations</artifactId>
|
||||||
|
<version>${jackson-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>${jackson-version}</version>
|
||||||
|
</dependency>
|
||||||
|
{{#java8}}
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||||
|
<version>${jackson-version}</version>
|
||||||
|
</dependency>
|
||||||
|
{{/java8}}
|
||||||
|
{{^java8}}
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||||
|
<artifactId>jackson-datatype-joda</artifactId>
|
||||||
|
<version>${jackson-version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>joda-time</groupId>
|
||||||
|
<artifactId>joda-time</artifactId>
|
||||||
|
<version>${jodatime-version}</version>
|
||||||
|
</dependency>
|
||||||
|
{{/java8}}
|
||||||
|
|
||||||
|
<!-- Base64 encoding that works in both JVM and Android -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.brsanthu</groupId>
|
||||||
|
<artifactId>migbase64</artifactId>
|
||||||
|
<version>2.2</version>
|
||||||
|
</dependency>
|
||||||
|
{{#supportJava6}}
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons_lang3_version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>${commons_io_version}</version>
|
||||||
|
</dependency>
|
||||||
|
{{/supportJava6}}
|
||||||
|
|
||||||
|
<!-- test dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit-version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<properties>
|
||||||
|
<swagger-core-version>1.5.9</swagger-core-version>
|
||||||
|
<jersey-version>2.22.2</jersey-version>
|
||||||
|
<jackson-version>2.7.5</jackson-version>
|
||||||
|
{{^java8}}
|
||||||
|
<jodatime-version>2.9.4</jodatime-version>
|
||||||
|
{{/java8}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
<commons_io_version>2.5</commons_io_version>
|
||||||
|
<commons_lang3_version>3.5</commons_lang3_version>
|
||||||
|
{{/supportJava6}}
|
||||||
|
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||||
|
<junit-version>4.12</junit-version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
@ -0,0 +1,31 @@
|
|||||||
|
//overloaded main template file to add this comment
|
||||||
|
|
||||||
|
{{>licenseInfo}}
|
||||||
|
|
||||||
|
package {{package}};
|
||||||
|
|
||||||
|
{{^supportJava6}}
|
||||||
|
import java.util.Objects;
|
||||||
|
{{/supportJava6}}
|
||||||
|
{{#supportJava6}}
|
||||||
|
import org.apache.commons.lang3.ObjectUtils;
|
||||||
|
{{/supportJava6}}
|
||||||
|
{{#imports}}
|
||||||
|
import {{import}};
|
||||||
|
{{/imports}}
|
||||||
|
{{#serializableModel}}
|
||||||
|
import java.io.Serializable;
|
||||||
|
{{/serializableModel}}
|
||||||
|
{{#parcelableModel}}
|
||||||
|
import android.os.Parcelable;
|
||||||
|
import android.os.Parcel;
|
||||||
|
{{/parcelableModel}}
|
||||||
|
{{#useBeanValidation}}
|
||||||
|
import javax.validation.constraints.*;
|
||||||
|
{{/useBeanValidation}}
|
||||||
|
|
||||||
|
{{#models}}
|
||||||
|
{{#model}}
|
||||||
|
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
|
||||||
|
{{/model}}
|
||||||
|
{{/models}}
|
Loading…
x
Reference in New Issue
Block a user