Merge branch 'master' into typescript-angular2-build-to-dist-folder

This commit is contained in:
wing328
2016-12-15 21:40:48 +08:00
committed by GitHub
332 changed files with 17764 additions and 6336 deletions

View File

@@ -32,6 +32,7 @@ Code change should conform to the programming style guide of the respective lang
- Android: https://source.android.com/source/code-style.html
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- C++: https://google.github.io/styleguide/cppguide.html
- Clojure: https://github.com/bbatsov/clojure-style-guide
- Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md
- Java: https://google.github.io/styleguide/javaguide.html
- JavaScript: https://github.com/airbnb/javascript/tree/master/es5

View File

@@ -799,6 +799,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Plexxi](http://www.plexxi.com)
- [Pixoneye](http://www.pixoneye.com/)
- [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Prill Tecnologia](http://www.prill.com.br)
- [QAdept](http://qadept.com/)
- [QuantiModo](https://quantimo.do/)
- [Rapid7](https://rapid7.com/)
@@ -809,12 +810,15 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html)
- [Saritasa](https://www.saritasa.com/)
- [SCOOP Software GmbH](http://www.scoop-software.de)
- [Shine Solutions](https://shinesolutions.com/)
- [Skurt](http://www.skurt.com)
- [SmartRecruiters](https://www.smartrecruiters.com/)
- [SRC](https://www.src.si/)
- [StyleRecipe](http://stylerecipe.co.jp)
- [Svenska Spel AB](https://www.svenskaspel.se/)
- [TaskData](http://www.taskdata.com/)
- [ThoughtWorks](https://www.thoughtworks.com)
- [Upwork](http://upwork.com/)
- [uShip](https://www.uship.com/)
- [VMware](https://vmware.com/)
- [W.UP](http://wup.hu/?siteLang=en)

View File

@@ -18,6 +18,8 @@ install:
- cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g
- cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5
- cmd: dir/w
# - cmd: RMDIR "C:\projects\swagger-codegen\swagger-samples" /S /Q
- git clone https://github.com/wing328/swagger-samples
- ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs"
build_script:
@@ -37,6 +39,6 @@ test_script:
# generate all petstore clients
- .\bin\windows\run-all-petstore.cmd
cache:
#cache:
# - C:\maven\
# - C:\Users\appveyor\.m2

View File

@@ -9,3 +9,4 @@
./bin/java-petstore-retrofit2.sh
./bin/java-petstore-retrofit2rx.sh
./bin/java8-petstore-jersey2.sh
./bin/java-petstore-retrofit2-play24.sh

View File

@@ -0,0 +1 @@
{"useBeanValidation":"true","enableBuilderSupport":"true","library":"retrofit2", "usePlay24WS":"true"}

View File

@@ -0,0 +1,34 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2-play24.json -o samples/client/petstore/java/retrofit2-play24 -DhideGenerationTimestamp=true"
echo "Removing files and folders under samples/client/petstore/java/retrofit2-play24/src/main"
rm -rf samples/client/petstore/java/retrofit2-play24/src/main
find samples/client/petstore/java/retrofit2-play24 -maxdepth 1 -type f ! -name "README.md" -exec rm {} +
java $JAVA_OPTS -jar $executable $ags

44
circle.yml Normal file
View File

@@ -0,0 +1,44 @@
# work in progress: the goal is to move all the existing tests
# handled by travis-ci to circle CI so that travis-ci can test
# objc/swift API client instead
machine:
environment:
_JAVA_OPTIONS: "-Xms512m -Xmx1024m"
java:
# TODO we also need to test oraclejdk8
version: oraclejdk7
node:
version: 5.0.0
services:
- docker
# Override /etc/hosts
hosts:
petstore.swagger.io: 127.0.0.1
dependencies:
cache_directories:
- ~/.jspm
- ~/.npm
- ~/builder
- ~/.m2
pre:
- export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"
- gem install bundler
- npm install -g typescript
- sudo pip install virtualenv
# to run petstore server locally via docker
- docker pull swaggerapi/petstore
- docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore
- docker ps -a
# show host table to confirm petstore.swagger.io is mapped to localhost
- cat /etc/hosts
override:
#- rvm --default use 2.1.0
#- ruby -v
test:
override:
- mvn verify -Psamples
#- mvn -q clean install
#- jdk_switcher use oraclejdk8
#- mvn -q clean install

View File

@@ -25,12 +25,18 @@ public class CodegenConstants {
public static final String ARTIFACT_VERSION = "artifactVersion";
public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml";
public static final String LICENSE_NAME = "licenseName";
public static final String LICENSE_NAME_DESC = "The name of the license";
public static final String LICENSE_URL = "licenseUrl";
public static final String LICENSE_URL_DESC = "The URL of the license";
public static final String SOURCE_FOLDER = "sourceFolder";
public static final String SOURCE_FOLDER_DESC = "source folder for generated code";
public static final String IMPL_FOLDER = "implFolder";
public static final String IMPL_FOLDER_DESC = "folder for generated implementation code";
public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix";
public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables";
@@ -48,13 +54,13 @@ public class CodegenConstants {
public static final String USE_DATETIME_OFFSET = "useDateTimeOffset";
public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties";
public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams";
public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not).";
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
public static final String PACKAGE_TITLE = "packageTitle";
public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_PRODUCTNAME = "packageProductName";
@@ -65,7 +71,7 @@ public class CodegenConstants {
public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String PACKAGE_COPYRIGHT = "packageCopyright";
public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.";
public static final String POD_VERSION = "podVersion";
public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument";
@@ -79,13 +85,13 @@ public class CodegenConstants {
public static final String RETURN_ICOLLECTION = "returnICollection";
public static final String RETURN_ICOLLECTION_DESC = "Return ICollection<T> instead of the concrete type.";
public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj.";
public static final String OPTIONAL_PROJECT_GUID = "packageGuid";
public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project";
public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming";
public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name";
@@ -132,5 +138,4 @@ public class CodegenConstants {
public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged";
public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events.";
}

View File

@@ -14,7 +14,7 @@ public class CodegenOperation {
public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams,
returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer,
isListContainer, isMultipart, hasMore = true,
isResponseBinary = false, hasReference = false,
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful;
public String path, operationId, returnType, httpMethod, returnBaseType,
@@ -217,6 +217,8 @@ public class CodegenOperation {
return false;
if (hasReference != that.hasReference)
return false;
if (isResponseFile != that.isResponseFile)
return false;
if (path != null ? !path.equals(that.path) : that.path != null)
return false;
if (operationId != null ? !operationId.equals(that.operationId) : that.operationId != null)
@@ -297,6 +299,7 @@ public class CodegenOperation {
result = 31 * result + (isMultipart ? 13:31);
result = 31 * result + (hasMore ? 13:31);
result = 31 * result + (isResponseBinary ? 13:31);
result = 31 * result + (isResponseFile ? 13:31);
result = 31 * result + (hasReference ? 13:31);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (operationId != null ? operationId.hashCode() : 0);

View File

@@ -37,7 +37,7 @@ public class CodegenProperty implements Cloneable {
public boolean hasMore, required, secondaryParam;
public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly
public boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime;
public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime;
public boolean isListContainer, isMapContainer;
public boolean isEnum;
public boolean isReadOnly = false;
@@ -108,6 +108,7 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((isDouble ? 13:31));
result = prime * result + ((isByteArray ? 13:31));
result = prime * result + ((isBinary ? 13:31));
result = prime * result + ((isFile ? 13:31));
result = prime * result + ((isBoolean ? 13:31));
result = prime * result + ((isDate ? 13:31));
result = prime * result + ((isDateTime ? 13:31));
@@ -264,6 +265,9 @@ public class CodegenProperty implements Cloneable {
if (this.isBinary != other.isBinary) {
return false;
}
if (this.isFile != other.isFile) {
return false;
}
if (this.isListContainer != other.isListContainer) {
return false;
}

View File

@@ -16,6 +16,7 @@ public class CodegenResponse {
public Boolean isMapContainer;
public Boolean isListContainer;
public Boolean isBinary = Boolean.FALSE;
public Boolean isFile = Boolean.FALSE;
public Object schema;
public String jsonSchema;
@@ -63,6 +64,8 @@ public class CodegenResponse {
return false;
if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null)
return false;
if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null)
return false;
if (schema != null ? !schema.equals(that.schema) : that.schema != null)
return false;
return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null;
@@ -85,6 +88,7 @@ public class CodegenResponse {
result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0);
result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0);
result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0);
result = 31 * result + (isFile != null ? isFile.hashCode() : 0);
result = 31 * result + (schema != null ? schema.hashCode() : 0);
result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0);
return result;

View File

@@ -36,6 +36,7 @@ import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
@@ -783,6 +784,7 @@ public class DefaultCodegen {
typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]");
typeMapping.put("binary", "byte[]");
typeMapping.put("file", "File");
instantiationTypes = new HashMap<String, String>();
@@ -1087,6 +1089,8 @@ public class DefaultCodegen {
datatype = "ByteArray";
} else if (p instanceof BinaryProperty) {
datatype = "binary";
} else if (p instanceof FileProperty) {
datatype = "file";
} else if (p instanceof BooleanProperty) {
datatype = "boolean";
} else if (p instanceof DateProperty) {
@@ -1566,6 +1570,9 @@ public class DefaultCodegen {
if (p instanceof BinaryProperty) {
property.isBinary = true;
}
if (p instanceof FileProperty) {
property.isFile = true;
}
if (p instanceof UUIDProperty) {
property.isString = true;
}
@@ -1994,6 +2001,9 @@ public class DefaultCodegen {
if (r.isBinary && r.isDefault){
op.isResponseBinary = Boolean.TRUE;
}
if (r.isFile && r.isDefault){
op.isResponseFile = Boolean.TRUE;
}
}
op.responses.get(op.responses.size() - 1).hasMore = false;
@@ -2193,6 +2203,7 @@ public class DefaultCodegen {
}
r.dataType = cm.datatype;
r.isBinary = isDataTypeBinary(cm.datatype);
r.isFile = isDataTypeFile(cm.datatype);
if (cm.isContainer) {
r.simpleType = false;
r.containerType = cm.containerType;
@@ -2382,6 +2393,7 @@ public class DefaultCodegen {
p.dataType = cp.datatype;
p.isPrimitiveType = cp.isPrimitiveType;
p.isBinary = isDataTypeBinary(cp.datatype);
p.isFile = isDataTypeFile(cp.datatype);
}
// set boolean flag (e.g. isString)
@@ -2474,6 +2486,8 @@ public class DefaultCodegen {
p.example = "BINARY_DATA_HERE";
} else if (Boolean.TRUE.equals(p.isByteArray)) {
p.example = "B";
} else if (Boolean.TRUE.equals(p.isFile)) {
p.example = "/path/to/file.txt";
} else if (Boolean.TRUE.equals(p.isDate)) {
p.example = "2013-10-20";
} else if (Boolean.TRUE.equals(p.isDateTime)) {
@@ -2494,6 +2508,10 @@ public class DefaultCodegen {
return dataType.toLowerCase().startsWith("byte");
}
public boolean isDataTypeFile(String dataType) {
return dataType.toLowerCase().equals("file");
}
/**
* Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects
*
@@ -3289,6 +3307,9 @@ public class DefaultCodegen {
} else if (Boolean.TRUE.equals(property.isBinary)) {
parameter.isByteArray = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isFile)) {
parameter.isFile = true;
parameter.isPrimitiveType = true;
} else if (Boolean.TRUE.equals(property.isDate)) {
parameter.isDate = true;
parameter.isPrimitiveType = true;

View File

@@ -113,7 +113,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
config.processOpts();
config.preprocessSwagger(swagger);
config.additionalProperties().put("generatedDate", DateTime.now().toString());
config.additionalProperties().put("generatorClass", config.getClass().toString());
config.additionalProperties().put("generatorClass", config.getClass().getName());
config.additionalProperties().put("inputSpec", config.getInputSpec());
if (swagger.getVendorExtensions() != null) {
config.vendorExtensions().putAll(swagger.getVendorExtensions());

View File

@@ -93,7 +93,7 @@ public class ExampleGenerator {
};
}
} else if (property instanceof DateProperty) {
return "2000-01-23T04:56:07.000+00:00";
return "2000-01-23";
} else if (property instanceof DateTimeProperty) {
return "2000-01-23T04:56:07.000+00:00";
} else if (property instanceof DecimalProperty) {

View File

@@ -180,7 +180,7 @@ public class XmlExampleGenerator {
if (property.getExample() != null) {
return property.getExample().toString();
} else {
return "2000-01-23T04:56:07.000Z";
return "2000-01-23";
}
} else if (property instanceof IntegerProperty) {
if (property.getExample() != null) {

View File

@@ -52,6 +52,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
protected String groupId = "io.swagger";
protected String artifactId = "swagger-java";
protected String artifactVersion = "1.0.0";
protected String licenseName = "Unlicense";
protected String licenseUrl = "http://unlicense.org";
protected String projectFolder = "src" + File.separator + "main";
protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
@@ -117,6 +119,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC));
cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
@@ -187,6 +191,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) {
this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME));
} else {
additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName);
}
if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) {
this.setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL));
} else {
additionalProperties.put(CodegenConstants.LICENSE_URL, licenseUrl);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
@@ -821,7 +837,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
op.path = sanitizePath(op.path);
return op;
}
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze
@@ -895,6 +911,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.artifactVersion = artifactVersion;
}
public void setLicenseName(String licenseName) {
this.licenseName = licenseName;
}
public void setLicenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
@@ -957,7 +981,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
}
return sb.toString();
}
public void setSupportJava6(boolean value) {
this.supportJava6 = value;
}

View File

@@ -26,6 +26,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
protected HashSet<String> languageGenericTypes;
public AbstractTypeScriptClientCodegen() {
super();
@@ -58,6 +59,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
"any",
"Error"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();

View File

@@ -390,7 +390,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL));
//make api and model doc path available in mustache template
additionalProperties.put( "apiDocPath", apiDocPath );

View File

@@ -21,6 +21,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
protected String packageVersion = "1.0.0";
protected String clientPackage = "IO.Swagger.Client";
protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
public CsharpDotNet2ClientCodegen() {
super();
@@ -35,6 +38,8 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
embeddedTemplateDir = templateDir = "CsharpDotNet2";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
setReservedWordsLowerCase(
Arrays.asList(
@@ -122,6 +127,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
additionalProperties.put(CLIENT_PACKAGE, clientPackage);
}
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("Configuration.mustache",
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
@@ -130,7 +138,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@@ -292,4 +300,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
}
@Override
public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar);
}
}

View File

@@ -2,7 +2,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.languages.features.BeanValidationFeatures;
import io.swagger.codegen.languages.features.PerformBeanValidationFeatures;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -12,13 +12,15 @@ import java.io.File;
import java.util.*;
import java.util.regex.Pattern;
public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures {
public class JavaClientCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, PerformBeanValidationFeatures {
static final String MEDIA_TYPE = "mediaType";
@SuppressWarnings("hiding")
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String USE_RX_JAVA = "useRxJava";
public static final String USE_PLAY24_WS = "usePlay24WS";
public static final String PARCELABLE_MODEL = "parcelableModel";
public static final String RETROFIT_1 = "retrofit";
@@ -26,8 +28,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean useRxJava = false;
protected boolean usePlay24WS = false;
protected boolean parcelableModel = false;
protected boolean useBeanValidation = false;
protected boolean performBeanValidation = false;
public JavaClientCodegen() {
super();
@@ -40,8 +44,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library."));
cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)"));
cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library."));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations"));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation"));
supportedLibraries.put("jersey1", "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0. Enable Java6 support using '-DsupportJava6=true'.");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
@@ -81,6 +87,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (additionalProperties.containsKey(USE_PLAY24_WS)) {
this.setUsePlay24WS(Boolean.valueOf(additionalProperties.get(USE_PLAY24_WS).toString()));
}
additionalProperties.put(USE_PLAY24_WS, usePlay24WS);
if (additionalProperties.containsKey(PARCELABLE_MODEL)) {
this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString()));
}
@@ -88,11 +99,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
additionalProperties.put(PARCELABLE_MODEL, parcelableModel);
if (additionalProperties.containsKey(USE_BEANVALIDATION)) {
boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString());
this.setUseBeanValidation(useBeanValidationProp);
this.setUseBeanValidation(convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION));
}
// write back as boolean
additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp);
if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) {
this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION));
}
final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/");
@@ -122,6 +133,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
if (performBeanValidation) {
supportingFiles.add(new SupportingFile("BeanValidationException.mustache", invokerFolder,
"BeanValidationException.java"));
}
//TODO: add doc to retrofit1 and feign
if ( "feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) ){
modelDocTemplateFiles.remove("model_doc.mustache");
@@ -159,6 +175,33 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
LOGGER.error("Unknown library option (-l/--library): " + getLibrary());
}
if (Boolean.TRUE.equals(additionalProperties.get(USE_PLAY24_WS))) {
// remove unsupported auth
Iterator<SupportingFile> iter = supportingFiles.iterator();
while (iter.hasNext()) {
SupportingFile sf = iter.next();
if (sf.templateFile.startsWith("auth/")) {
iter.remove();
}
}
// auth
supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
// api client
supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java"));
// adapters
supportingFiles
.add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java"));
supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder,
"Play24CallAdapterFactory.java"));
additionalProperties.put("jackson", "true");
additionalProperties.remove("gson");
}
if (additionalProperties.containsKey("jackson") ) {
supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java"));
}
@@ -294,6 +337,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useRxJava = useRxJava;
}
public void setUsePlay24WS(boolean usePlay24WS) {
this.usePlay24WS = usePlay24WS;
}
public void setParcelableModel(boolean parcelableModel) {
this.parcelableModel = parcelableModel;
}
@@ -302,6 +350,10 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida
this.useBeanValidation = useBeanValidation;
}
public void setPerformBeanValidation(boolean performBeanValidation) {
this.performBeanValidation = performBeanValidation;
}
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?");
final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?");

View File

@@ -132,7 +132,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType)) {
if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType;
}
return addModelPrefix(swaggerType);
@@ -146,15 +146,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
type = swaggerType;
}
if (!startsWithLanguageSpecificPrimitiv(type)) {
if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) {
type = "models." + swaggerType;
}
return type;
}
private boolean startsWithLanguageSpecificPrimitiv(String type) {
for (String langPrimitive:languageSpecificPrimitives) {
if (type.startsWith(langPrimitive)) {
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType: languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}

View File

@@ -1,5 +1,7 @@
package io.swagger.codegen.languages;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,6 +29,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
public TypeScriptNodeClientCodegen() {
super();
typeMapping.put("file", "Buffer");
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
@@ -92,6 +96,19 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library.";
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Buffer");
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof FileProperty) {
return "Buffer";
}
return super.getTypeDeclaration(p);
}
public void setNpmName(String npmName) {
this.npmName = npmName;

View File

@@ -0,0 +1,10 @@
package io.swagger.codegen.languages.features;
public interface PerformBeanValidationFeatures {
// Language supports performing BeanValidation
public static final String PERFORM_BEANVALIDATION = "performBeanValidation";
public void setPerformBeanValidation(boolean performBeanValidation);
}

View File

@@ -1,10 +0,0 @@
# Csharp-DotNet2
This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d.
## Dependencies
- Mono compiler
- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator.

View File

@@ -0,0 +1,153 @@
# {{packageName}} - the C# library for the {{appName}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project:
- API version: {{appVersion}}
- SDK version: {{packageVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
<a name="frameworks-supported"></a>
## Frameworks supported
{{^supportUWP}}
- .NET 2.0
{{/supportUWP}}
{{#supportUWP}}
- UWP
{{/supportUWP}}
<a name="dependencies"></a>
## Dependencies
- Mono compiler
- Newtonsoft.Json.7.0.1
- RestSharp.Net2.1.1.11
Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator
<a name="installation"></a>
## Installation
Run the following command to generate the DLL
- [Mac/Linux] `/bin/sh compile-mono.sh`
- [Windows] TODO
Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces:
```csharp
using {{packageName}}.{{apiPackage}};
using {{packageName}}.Client;
using {{packageName}}.{{modelPackage}};
```
<a name="getting-started"></a>
## Getting Started
```csharp
using System;
using System.Diagnostics;
using {{apiPackage}};
using {{packageName}}.Client;
using {{modelPackage}};
namespace Example
{
public class {{operationId}}Example
{
public void main()
{
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
Configuration.Default.Username = "YOUR_USERNAME";
Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}}
{{/hasAuthMethods}}
var apiInstance = new {{classname}}();
{{#allParams}}
{{#isPrimitiveType}}
var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{/allParams}}
try
{
{{#summary}}
// {{{.}}}
{{/summary}}
{{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
Debug.WriteLine(result);{{/returnType}}
}
catch (Exception e)
{
Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message );
}
}
}
}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
<a name="documentation-for-api-endpoints"></a>
## Documentation for API Endpoints
All URIs are relative to *{{{basePath}}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
<a name="documentation-for-models"></a>
## Documentation for Models
{{#modelPackage}}
{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{/model}}{{/models}}
{{/modelPackage}}
{{^modelPackage}}
No model defined in this package
{{/modelPackage}}
<a name="documentation-for-authorization"></a>
## Documentation for Authorization
{{^authMethods}}
All endpoints do not require authorization.
{{/authMethods}}
{{#authMethods}}
{{#last}}
Authentication schemes defined for the API:
{{/last}}
{{/authMethods}}
{{#authMethods}}
<a name="{{name}}"></a>
### {{name}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}

View File

@@ -0,0 +1,97 @@
# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{{basePath}}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
<a name="{{{operationIdLowerCase}}}"></a>
# **{{{operationId}}}**
> {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
### Example
```csharp
using System;
using System.Diagnostics;
using {{packageName}}.Api;
using {{packageName}}.Client;
using {{modelPackage}};
namespace Example
{
public class {{operationId}}Example
{
public void main()
{
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}
// Configure HTTP basic authorization: {{{name}}}
Configuration.Default.Username = "YOUR_USERNAME";
Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}}
{{/hasAuthMethods}}
var apiInstance = new {{classname}}();
{{#allParams}}
{{#isPrimitiveType}}
var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/isPrimitiveType}}
{{/allParams}}
try
{
{{#summary}}
// {{{.}}}
{{/summary}}
{{#returnType}}{{returnType}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
Debug.WriteLine(result);{{/returnType}}
}
catch (Exception e)
{
Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message );
}
}
}
}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
{{/operation}}
{{/operations}}

View File

@@ -0,0 +1,14 @@
{{#models}}
{{#model}}
# {{{packageName}}}.Model.{{{classname}}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
{{/vars}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{{/model}}
{{/models}}

View File

@@ -0,0 +1,27 @@
package {{invokerPackage}};
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
public class BeanValidationException extends ValidationException {
/**
*
*/
private static final long serialVersionUID = -5294733947409491364L;
Set<ConstraintViolation<Object>> violations;
public BeanValidationException(Set<ConstraintViolation<Object>> violations) {
this.violations = violations;
}
public Set<ConstraintViolation<Object>> getViolations() {
return violations;
}
public void setViolations(Set<ConstraintViolation<Object>> violations) {
this.violations = violations;
}
}

View File

@@ -1,43 +1,45 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
// {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
import org.junit.Ignore;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
@Ignore
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@@ -35,8 +35,18 @@
{{/maxItems}}
{{/minItems}}
{{#minimum}}
{{#isInteger}}
@Min({{minimum}})
{{/isInteger}}
{{#isLong}}
@Min({{minimum}})
{{/isLong}}
{{/minimum}}
{{#maximum}}
{{#isInteger}}
@Max({{maximum}})
{{/maximum}}
{{/isInteger}}
{{#isLong}}
@Max({{maximum}})
{{/isLong}}
{{/maximum}}

View File

@@ -0,0 +1 @@
{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}}/* @Min({{minimum}}) */{{/minimum}}{{#maximum}}/* @Max({{maximum}}) */{{/maximum}}

View File

@@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>

View File

@@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>

View File

@@ -1,165 +1,221 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiCallback;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiResponse;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ProgressRequestBody;
import {{invokerPackage}}.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
{{#imports}}import {{import}};
{{/imports}}
import java.lang.reflect.Type;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#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}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) 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("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#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);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{returnType}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
return {{localVariablePrefix}}call;
}
{{/operation}}
}
{{/operations}}
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiCallback;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiResponse;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ProgressRequestBody;
import {{invokerPackage}}.ProgressResponseBody;
{{#performBeanValidation}}
import {{invokerPackage}}.BeanValidationException;
{{/performBeanValidation}}
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
{{#useBeanValidation}}
import javax.validation.constraints.*;
{{/useBeanValidation}}
{{#performBeanValidation}}
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.util.Set;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
{{/performBeanValidation}}
{{#imports}}import {{import}};
{{/imports}}
import java.lang.reflect.Type;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#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}}
/* Build call for {{operationId}} */
private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// create path and map variables
String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#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);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
{{^performBeanValidation}}
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
return {{localVariablePrefix}}call;
{{/performBeanValidation}}
{{#performBeanValidation}}
try {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
ExecutableValidator executableValidator = factory.getValidator().forExecutables();
Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} };
Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}});
Set<ConstraintViolation<{{classname}}>> violations = executableValidator.validateParameters(this, method,
parameterValues);
if (violations.size() == 0) {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
return {{localVariablePrefix}}call;
} else {
throw new BeanValidationException((Set) violations);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
} catch (SecurityException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
}
{{/performBeanValidation}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{returnType}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
{{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return {{localVariablePrefix}}resp.getData();{{/returnType}}
}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @return ApiResponse&lt;{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
}
/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
return {{localVariablePrefix}}call;
}
{{/operation}}
}
{{/operations}}

View File

@@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@@ -131,7 +139,7 @@
<version>${jodatime-version}</version>
</dependency>
{{/java8}}
{{#useBeanValidation}}
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>
<groupId>javax.validation</groupId>
@@ -139,8 +147,20 @@
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{/useBeanValidation}}
{{#performBeanValidation}}
<!-- Bean Validation Impl. used to perform BeanValidation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
{{/performBeanValidation}}
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
@@ -161,4 +181,4 @@
<junit-version>4.12</junit-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
</project>

View File

@@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>

View File

@@ -18,6 +18,11 @@ import java.util.List;
import java.util.Map;
{{/fullJavaUtil}}
{{#usePlay24WS}}
import play.libs.F;
import retrofit2.Response;
{{/usePlay24WS}}
{{#operations}}
public interface {{classname}} {
{{#operation}}
@@ -39,7 +44,7 @@ public interface {{classname}} {
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{path}}")
{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{^usePlay24WS}}{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}{{/usePlay24WS}}{{#usePlay24WS}}F.Promise<Response{{/usePlay24WS}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>{{#usePlay24WS}}>{{/usePlay24WS}} {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}

View File

@@ -0,0 +1,136 @@
package {{invokerPackage}};
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.*;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import play.libs.Json;
import play.libs.ws.WSClient;
import {{invokerPackage}}.Play24CallAdapterFactory;
import {{invokerPackage}}.Play24CallFactory;
import okhttp3.Interceptor;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.Authentication;
/**
* API client
*/
public class ApiClient {
/** Underlying HTTP-client */
private WSClient wsClient;
/** Supported auths */
private Map<String, Authentication> authentications;
/** API base path */
private String basePath = "{{{basePath}}}";
public ApiClient(WSClient wsClient) {
this();
this.wsClient = wsClient;
}
public ApiClient() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}
// authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
// authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Creates a retrofit2 client for given API interface
*/
public <S> S createService(Class<S> serviceClass) {
if(!basePath.endsWith("/")) {
basePath = basePath + "/";
}
Map<String, String> extraHeaders = new HashMap<>();
List<Pair> extraQueryParams = new ArrayList<>();
for (String authName : authentications.keySet()) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(extraQueryParams, extraHeaders);
}
return new Retrofit.Builder()
.baseUrl(basePath)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(JacksonConverterFactory.create(Json.mapper()))
.callFactory(new Play24CallFactory(wsClient, extraHeaders, extraQueryParams))
.addCallAdapterFactory(new Play24CallAdapterFactory())
.build()
.create(serviceClass);
}
/**
* Helper method to set API base path
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Get authentications (key: authentication name, value: 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 API key value for the first API key authentication.
*/
public ApiClient setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return this;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public ApiClient setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return this;
}
}
throw new RuntimeException("No API key authentication configured!");
}
}

View File

@@ -0,0 +1,90 @@
package {{invokerPackage}};
import play.libs.F;
import retrofit2.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
/**
* Creates {@link CallAdapter} instances that convert {@link Call} into {@link play.libs.F.Promise}
*/
public class Play24CallAdapterFactory extends CallAdapter.Factory {
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (!(returnType instanceof ParameterizedType)) {
return null;
}
ParameterizedType type = (ParameterizedType) returnType;
if (type.getRawType() != F.Promise.class) {
return null;
}
return createAdapter((ParameterizedType) returnType);
}
private Type getTypeParam(ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (types.length != 1) {
throw new IllegalStateException("Must be exactly one type parameter");
}
Type paramType = types[0];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
private CallAdapter<F.Promise<?>> createAdapter(ParameterizedType returnType) {
Type parameterType = getTypeParam(returnType);
return new ValueAdapter(parameterType);
}
/**
* Adpater that coverts values returned by API interface into Play promises
*/
static final class ValueAdapter implements CallAdapter<F.Promise<?>> {
private final Type responseType;
ValueAdapter(Type responseType) {
this.responseType = responseType;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public <R> F.Promise<R> adapt(final Call<R> call) {
final F.RedeemablePromise<R> promise = F.RedeemablePromise.empty();
call.enqueue(new Callback<R>() {
@Override
public void onResponse(Call<R> call, Response<R> response) {
if (response.isSuccessful()) {
promise.success(response.body());
} else {
promise.failure(new Exception(response.errorBody().toString()));
}
}
@Override
public void onFailure(Call<R> call, Throwable t) {
promise.failure(t);
}
});
return promise;
}
}
}

View File

@@ -0,0 +1,210 @@
package {{invokerPackage}};
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import play.libs.F;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Creates {@link Call} instances that invoke underlying {@link WSClient}
*/
public class Play24CallFactory implements okhttp3.Call.Factory {
/** PlayWS http client */
private final WSClient wsClient;
/** Extra headers to add to request */
private Map<String, String> extraHeaders = new HashMap<>();
/** Extra query parameters to add to request */
private List<Pair> extraQueryParams = new ArrayList<>();
public Play24CallFactory(WSClient wsClient) {
this.wsClient = wsClient;
}
public Play24CallFactory(WSClient wsClient, Map<String, String> extraHeaders,
List<Pair> extraQueryParams) {
this.wsClient = wsClient;
this.extraHeaders.putAll(extraHeaders);
this.extraQueryParams.addAll(extraQueryParams);
}
@Override
public Call newCall(Request request) {
// add extra headers
Request.Builder rb = request.newBuilder();
for (Map.Entry<String, String> header : this.extraHeaders.entrySet()) {
rb.addHeader(header.getKey(), header.getValue());
}
// add extra query params
if (!this.extraQueryParams.isEmpty()) {
String newQuery = request.url().uri().getQuery();
for (Pair queryParam : this.extraQueryParams) {
String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue());
if (newQuery == null) {
newQuery = param;
} else {
newQuery += "&" + param;
}
}
URI newUri;
try {
newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(),
request.url().uri().getPath(), newQuery, request.url().uri().getFragment());
rb.url(newUri.toURL());
} catch (MalformedURLException | URISyntaxException e) {
throw new RuntimeException("Error while updating an url", e);
}
}
return new PlayWSCall(wsClient, rb.build());
}
/**
* Call implementation that delegates to Play WS Client
*/
static class PlayWSCall implements Call {
private final WSClient wsClient;
private WSRequest wsRequest;
private final Request request;
public PlayWSCall(WSClient wsClient, Request request) {
this.wsClient = wsClient;
this.request = request;
}
@Override
public Request request() {
return request;
}
@Override
public void enqueue(final okhttp3.Callback responseCallback) {
final Call call = this;
final F.Promise<WSResponse> promise = executeAsync();
promise.onRedeem(new F.Callback<WSResponse>() {
@Override
public void invoke(WSResponse wsResponse) throws Throwable {
responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(wsResponse));
}
});
promise.onFailure(new F.Callback<Throwable>() {
@Override
public void invoke(Throwable throwable) throws Throwable {
if (throwable instanceof IOException) {
responseCallback.onFailure(call, (IOException) throwable);
} else {
responseCallback.onFailure(call, new IOException(throwable));
}
}
});
}
F.Promise<WSResponse> executeAsync() {
try {
wsRequest = wsClient.url(request.url().uri().toString());
addHeaders(wsRequest);
if (request.body() != null) {
addBody(wsRequest);
}
return wsRequest.execute(request.method());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private void addHeaders(WSRequest wsRequest) {
for(Map.Entry<String, List<String>> entry : request.headers().toMultimap().entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
wsRequest.setHeader(entry.getKey(), value);
}
}
}
private void addBody(WSRequest wsRequest) throws IOException {
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
wsRequest.setBody(buffer.inputStream());
wsRequest.setContentType(request.body().contentType().toString());
}
private Response toWSResponse(final WSResponse r) {
final Response.Builder builder = new Response.Builder();
builder.request(request)
.code(r.getStatus())
.body(new ResponseBody() {
@Override
public MediaType contentType() {
return MediaType.parse(r.getHeader("Content-Type"));
}
@Override
public long contentLength() {
return r.getBody().getBytes().length;
}
@Override
public BufferedSource source() {
return new Buffer().write(r.getBody().getBytes());
}
});
for (Map.Entry<String, List<String>> entry : r.getAllHeaders().entrySet()) {
for (String value : entry.getValue()) {
builder.addHeader(entry.getKey(), value);
}
}
builder.protocol(Protocol.HTTP_1_1);
return builder.build();
}
@Override
public Response execute() throws IOException {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void cancel() {
throw new UnsupportedOperationException("Not supported");
}
@Override
public boolean isExecuted() {
return false;
}
@Override
public boolean isCanceled() {
return false;
}
}
}

View File

@@ -0,0 +1,67 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
/**
* Holds ApiKey auth info
*/
{{>generatedAnnotation}}
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
}
}
}

View File

@@ -15,6 +15,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@@ -148,6 +156,40 @@
<version>${retrofit-version}</version>
</dependency>
{{/useRxJava}}
{{#usePlay24WS}}
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<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>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.play</groupId>
<artifactId>play-java-ws_2.10</artifactId>
<version>2.4.6</version>
</dependency>
{{/usePlay24WS}}
<!-- test dependencies -->
<dependency>
@@ -164,6 +206,9 @@
<maven.compiler.target>${java.version}</maven.compiler.target>
<swagger-core-version>1.5.9</swagger-core-version>
<retrofit-version>2.1.0</retrofit-version>
{{#usePlay24WS}}
<jackson-version>2.7.5</jackson-version>
{{/usePlay24WS}}
{{#useRxJava}}
<rxjava-version>1.1.6</rxjava-version>
{{/useRxJava}}

View File

@@ -11,6 +11,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<plugins>
<plugin>
@@ -194,7 +202,7 @@
<version>${commons_io_version}</version>
</dependency>
{{/supportJava6}}
{{#useBeanValidation}}
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>
<groupId>javax.validation</groupId>
@@ -202,7 +210,7 @@
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{/useBeanValidation}}
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@@ -14,6 +14,14 @@
<maven>2.2.0</maven>
</prerequisites>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<defaultGoal>install</defaultGoal>
<directory>target</directory>
@@ -117,4 +125,4 @@
<junit-version>4.8.2</junit-version>
<slf4j-version>1.6.3</slf4j-version>
</properties>
</project>
</project>

View File

@@ -37,7 +37,7 @@ public interface {{classname}} {
@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} })
{{/hasProduces}}
@ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} })
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
}
{{/operations}}

View File

@@ -28,7 +28,7 @@ import org.springframework.stereotype.Service;
public class {{classname}}ServiceImpl implements {{classname}} {
{{#operations}}
{{#operation}}
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
// TODO: Implement...
{{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}}

View File

@@ -103,7 +103,7 @@ public class {{classname}}Test {
{{#allParams}}
{{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}}{{#isFile}}org.apache.cxf.jaxrs.ext.multipart.Attachment {{paramName}} = null;{{/isFile}}
{{/allParams}}
//{{^vendorExtensions.x-java-is-response-void}}{{{returnType}}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
//{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{^vendorExtensions.x-java-is-response-void}}//assertNotNull(response);{{/vendorExtensions.x-java-is-response-void}}
// TODO: test validations

View File

@@ -0,0 +1 @@
{{#returnContainer}}{{#isMapContainer}}Map<String, {{{returnType}}}>{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}

View File

@@ -5,6 +5,15 @@
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>

View File

@@ -0,0 +1,7 @@
# {{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}

View File

@@ -2,38 +2,38 @@
package {{invokerPackage}};
public class Pair {
private String name = "";
private String value = "";
private String name = "";
private String value = "";
public Pair(String name, String value) {
setName(name);
setValue(value);
}
public Pair(String name, String value) {
setName(name);
setValue(value);
}
private void setName(String name) {
if (!isValidString(name)) return;
private void setName(String name) {
if (!isValidString(name)) return;
this.name = name;
}
this.name = name;
}
private void setValue(String value) {
if (!isValidString(value)) return;
private void setValue(String value) {
if (!isValidString(value)) return;
this.value = value;
}
this.value = value;
}
public String getName() {
return this.name;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public String getValue() {
return this.value;
}
private boolean isValidString(String arg) {
if (arg == null) return false;
if (arg.trim().isEmpty()) return false;
private boolean isValidString(String arg) {
if (arg == null) return false;
if (arg.trim().isEmpty()) return false;
return true;
}
return true;
}
}

View File

@@ -54,83 +54,89 @@ public class {{classname}} {
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}
{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}",
new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"));
}
{{/required}}{{/allParams}}
new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"));
}
{{/required}}
{{/allParams}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}
queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}
"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}
{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
{{#queryParams}}
queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
{{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}{{/formParams}}
{{#formParams}}
{{^isFile}}
if ({{paramName}} != null) {
localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/isFile}}
{{#isFile}}
if ({{paramName}} != null) {
localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}
{{/formParams}}
HttpEntity httpEntity = localVarBuilder.build();
postBody = httpEntity;
} else {
} else {
// normal form params
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}}
{{#formParams}}
{{^isFile}}
formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/isFile}}
{{/formParams}}
}
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
try {
String localVarResponse = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames);
if (localVarResponse != null) {
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(localVarResponse, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} else {
return {{#returnType}}null{{/returnType}};
}
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
try {
String localVarResponse = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(localVarResponse != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(localVarResponse, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} else {
return {{#returnType}}null{{/returnType}};
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if(ex.getCause() instanceof VolleyError) {
VolleyError volleyError = (VolleyError)ex.getCause();
if (volleyError.networkResponse != null) {
throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if (ex.getCause() instanceof VolleyError) {
VolleyError volleyError = (VolleyError)ex.getCause();
if (volleyError.networkResponse != null) {
throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
/**

View File

@@ -12,18 +12,38 @@ public class ApiException extends Exception {
this.message = message;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Set the HTTP status code.
*
* @param code HTTP status code.
*/
public void setCode(int code) {
this.code = code;
}
/**
* Get the error message.
*
* @return Error message.
*/
public String getMessage() {
return message;
}
/**
* Set the error messages.
*
* @param message Error message.
*/
public void setMessage(String message) {
this.message = message;
}

View File

@@ -179,48 +179,48 @@ public class ApiInvoker {
}
public static void initializeInstance() {
initializeInstance(null);
initializeInstance(null);
}
public static void initializeInstance(Cache cache) {
initializeInstance(cache, null, 0, null, 30);
initializeInstance(cache, null, 0, null, 30);
}
public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout);
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}");
INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout);
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}");
// Setup authentications (key: authentication name, value: authentication).
INSTANCE.authentications = new HashMap<String, Authentication>();
{{#authMethods}}
{{#isApiKey}}
INSTANCE.authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));
{{/isApiKey}}
{{#isBasic}}
INSTANCE.authentications.put("{{name}}", new HttpBasicAuth());
{{/isBasic}}
{{#isOAuth}}
// TODO: comment out below as OAuth does not exist
//INSTANCE.authentications.put("{{name}}", new OAuth());
{{/isOAuth}}
{{/authMethods}}
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
// Setup authentications (key: authentication name, value: authentication).
INSTANCE.authentications = new HashMap<String, Authentication>();
{{#authMethods}}
{{#isApiKey}}
INSTANCE.authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));
{{/isApiKey}}
{{#isBasic}}
INSTANCE.authentications.put("{{name}}", new HttpBasicAuth());
{{/isBasic}}
{{#isOAuth}}
// TODO: comment out below as OAuth does not exist
//INSTANCE.authentications.put("{{name}}", new OAuth());
{{/isOAuth}}
{{/authMethods}}
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
}
private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
if(cache == null) cache = new NoCache();
if(network == null) {
HttpStack stack = new HurlStack();
network = new BasicNetwork(stack);
}
if(cache == null) cache = new NoCache();
if(network == null) {
HttpStack stack = new HurlStack();
network = new BasicNetwork(stack);
}
if(delivery == null) {
initConnectionRequest(cache, network);
} else {
initConnectionRequest(cache, network, threadPoolSize, delivery);
}
this.connectionTimeout = connectionTimeout;
if(delivery == null) {
initConnectionRequest(cache, network);
} else {
initConnectionRequest(cache, network, threadPoolSize, delivery);
}
this.connectionTimeout = connectionTimeout;
}
public static ApiInvoker getInstance() {
@@ -273,25 +273,25 @@ public class ApiInvoker {
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
* Get authentications (key: authentication name, value: 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
*/
* 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.
*/
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
@@ -303,21 +303,21 @@ public class ApiInvoker {
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
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.
*/
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
@@ -329,8 +329,8 @@ public class ApiInvoker {
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
@@ -342,18 +342,18 @@ public class ApiInvoker {
}
public void setConnectionTimeout(int connectionTimeout){
this.connectionTimeout = connectionTimeout;
this.connectionTimeout = connectionTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
return connectionTimeout;
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
* 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);
@@ -363,17 +363,21 @@ public class ApiInvoker {
}
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException {
RequestFuture<String> future = RequestFuture.newFuture();
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
if(request != null) {
mRequestQueue.add(request);
return future.get(connectionTimeout, TimeUnit.SECONDS);
} else return "no data";
RequestFuture<String> future = RequestFuture.newFuture();
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
if(request != null) {
mRequestQueue.add(request);
return future.get(connectionTimeout, TimeUnit.SECONDS);
} else {
return "no data";
}
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
if (request != null) mRequestQueue.add(request);
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
if (request != null) {
mRequestQueue.add(request);
}
}
public Request<String> createRequest(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
@@ -503,16 +507,16 @@ public class ApiInvoker {
}
private void initConnectionRequest(Cache cache, Network network) {
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery);
mRequestQueue.start();
mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery);
mRequestQueue.start();
}
public void stopQueue() {
mRequestQueue.stop();
mRequestQueue.stop();
}
}

View File

@@ -46,7 +46,7 @@ public class ApiKeyAuth implements Authentication {
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
String value;
if (apiKey == null) {
return;
return;
}
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;

View File

@@ -9,28 +9,28 @@ import java.util.Map;
import java.util.List;
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
private String username;
private String password;
public String getUsername() {
return username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT));
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT));
}
}

View File

@@ -7,8 +7,8 @@ import java.util.Map;
import java.util.List;
public class OAuth implements Authentication {
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
// TODO stub
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
// TODO stub
}
}

View File

@@ -19,75 +19,75 @@ import java.util.Map;
public class DeleteRequest extends Request<String> {
HttpEntity entity;
HttpEntity entity;
private final Response.Listener<String> mListener;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.DELETE, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
String contentType;
Map<String, String> apiHeaders;
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.DELETE, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
return headers;
}
}

View File

@@ -19,75 +19,75 @@ import java.util.Map;
public class PatchRequest extends Request<String> {
HttpEntity entity;
HttpEntity entity;
private final Response.Listener<String> mListener;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PatchRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PATCH, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
String contentType;
Map<String, String> apiHeaders;
public PatchRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PATCH, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
return headers;
}
}

View File

@@ -19,75 +19,75 @@ import java.util.Map;
public class PostRequest extends Request<String> {
HttpEntity entity;
HttpEntity entity;
private final Response.Listener<String> mListener;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PostRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
String contentType;
Map<String, String> apiHeaders;
public PostRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
return headers;
}
}

View File

@@ -19,75 +19,75 @@ import java.util.Map;
public class PutRequest extends Request<String> {
HttpEntity entity;
HttpEntity entity;
private final Response.Listener<String> mListener;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PutRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PUT, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
String contentType;
Map<String, String> apiHeaders;
public PutRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PUT, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
@Override
public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
return headers;
}
}

View File

@@ -1,10 +1,10 @@
{{>licenseInfo}}
{{#operations}}/*
* {{classname}}.h
*
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
@@ -35,11 +35,11 @@ public:
{{#allParams}}/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>{{/allParams}}
pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
protected:
std::shared_ptr<ApiClient> m_ApiClient;
std::shared_ptr<ApiClient> m_ApiClient;
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}

View File

@@ -35,23 +35,24 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
throw ApiException(400, U("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"));
}
{{/isContainer}}{{/isPrimitiveType}}{{/required}}{{/allParams}}
std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t path = U("{{path}}");
{{#pathParams}}boost::replace_all(path, U("{") U("{{baseName}}") U("}"), ApiClient::parameterToString({{{paramName}}}));
{{/pathParams}}
std::map<utility::string_t, utility::string_t> queryParams;
std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> formParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams;
std::unordered_set<utility::string_t> responseHttpContentTypes;
{{#produces}}responseHttpContentTypes.insert( U("{{mediaType}}") );
{{#produces}}
responseHttpContentTypes.insert( U("{{mediaType}}") );
{{/produces}}
utility::string_t responseHttpContentType;
// use JSON if possible
if ( responseHttpContentTypes.size() == 0 )
{
@@ -67,13 +68,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
{
responseHttpContentType = U("application/json");
}
// multipart formdata
// multipart formdata
else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() )
{
responseHttpContentType = U("multipart/form-data");
}
{{#vendorExtensions.x-codegen-response.isString}}
// plain text
// plain text
else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() )
{
responseHttpContentType = U("text/plain");
@@ -90,41 +91,70 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
else
{
throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type"));
}
{{/vendorExtensions.x-codegen-response-ishttpcontent}}
headerParams[U("Accept")] = responseHttpContentType;
std::unordered_set<utility::string_t> consumeHttpContentTypes;
{{#consumes}}consumeHttpContentTypes.insert( U("{{mediaType}}") );
{{/consumes}}
{{#allParams}}{{^isBodyParam}}{{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}}
{
{{#isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isHeaderParam}}{{#isFormParam}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isFile}}{{/isFormParam}}{{/isContainer}}{{^isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isHeaderParam}}{{#isFormParam}}{{#isFile}}fileParams[ U("{{baseName}}") ] = {{paramName}};
{{/isFile}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}});
{{/isFile}}{{/isFormParam}}{{/isContainer}}
}
{{/isBodyParam}}{{/allParams}}
{{/vendorExtensions.x-codegen-response-ishttpcontent}}
headerParams[U("Accept")] = responseHttpContentType;
std::unordered_set<utility::string_t> consumeHttpContentTypes;
{{#consumes}}
consumeHttpContentTypes.insert( U("{{mediaType}}") );
{{/consumes}}
{{#allParams}}
{{^isBodyParam}}
{{^isPathParam}}
{{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}}
{
{{#isContainer}}
{{#isQueryParam}}
queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isQueryParam}}
{{#isHeaderParam}}
headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isHeaderParam}}
{{#isFormParam}}
{{^isFile}}
formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isFile}}
{{/isFormParam}}
{{/isContainer}}
{{^isContainer}}
{{#isQueryParam}}
queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isQueryParam}}
{{#isHeaderParam}}
headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isHeaderParam}}
{{#isFormParam}}
{{#isFile}}
fileParams[ U("{{baseName}}") ] = {{paramName}};
{{/isFile}}
{{^isFile}}
formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}});
{{/isFile}}
{{/isFormParam}}
{{/isContainer}}
}
{{/isPathParam}}
{{/isBodyParam}}
{{/allParams}}
std::shared_ptr<IHttpBody> httpBody;
utility::string_t requestHttpContentType;
// use JSON if possible
if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() )
{
requestHttpContentType = U("application/json");
{{#bodyParam}}
web::json::value json;
{{#isPrimitiveType}} json = ModelBase::toJson({{paramName}});
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}
{{#isPrimitiveType}}
json = ModelBase::toJson({{paramName}});
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isListContainer}}
{
std::vector<web::json::value> jsonArray;
for( auto& item : {{paramName}} )
@@ -137,22 +167,26 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
}
json = web::json::value::array(jsonArray);
}
{{/isListContainer}}{{^isListContainer}}json = ModelBase::toJson({{paramName}});
{{/isListContainer}}{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
json = ModelBase::toJson({{paramName}});
{{/isListContainer}}
{{/isPrimitiveType}}
httpBody = std::shared_ptr<IHttpBody>( new JsonBody( json ) );
{{/bodyParam}}
}
// multipart formdata
// multipart formdata
else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() )
{
requestHttpContentType = U("multipart/form-data");
{{#bodyParam}}
std::shared_ptr<MultipartFormData> multipart(new MultipartFormData);
{{#isPrimitiveType}} multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}}));
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}
{{#isPrimitiveType}}
multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}}));
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{#isListContainer}}
{
std::vector<web::json::value> jsonArray;
for( auto& item : {{paramName}} )
@@ -165,13 +199,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
}
multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), web::json::value::array(jsonArray), U("application/json")));
}
{{/isListContainer}}{{^isListContainer}}{{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}}));
{{/isString}}{{^isString}}
{{/isListContainer}}
{{^isListContainer}}
{{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}}));
{{/isString}}
{{^isString}}
if({{paramName}}.get())
{
{{paramName}}->toMultipart(multipart, U("{{paramName}}"));
}
{{/isString}}{{/isListContainer}}{{/isPrimitiveType}}
{{/isString}}
{{/isListContainer}}
{{/isPrimitiveType}}
httpBody = multipart;
requestHttpContentType += U("; boundary=") + multipart->getBoundary();
@@ -180,8 +219,11 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
else
{
throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type"));
}
}
//Set the request content type in the header.
headerParams[U("Content-Type")] = requestHttpContentType;
{{#authMethods}}
// authentication ({{name}}) required
{{#isApiKey}}
@@ -211,13 +253,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
// oauth2 authentication is added automatically as part of the http_client_config
{{/isOAuth}}
{{/authMethods}}
return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType)
.then([=](web::http::http_response response)
{
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (response.status_code() >= 400)
@@ -226,7 +268,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
, U("error calling {{operationId}}: ") + response.reason_phrase()
, std::make_shared<std::stringstream>(response.extract_utf8string(true).get()));
}
// check response content type
if(response.headers().has(U("Content-Type")))
{
@@ -238,7 +280,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
, std::make_shared<std::stringstream>(response.extract_utf8string(true).get()));
}
}
{{#vendorExtensions.x-codegen-response-ishttpcontent}}
return response.extract_vector();
})
@@ -254,21 +296,28 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
})
.then([=](utility::string_t response)
{
{{^returnType}}return void();
{{/returnType}}{{#returnType}}{{#returnContainer}}{{{returnType}}} result;
{{/returnContainer}}{{^returnContainer}}{{{returnType}}} result({{{defaultResponse}}});{{/returnContainer}}
{{^returnType}}
return void();
{{/returnType}}
{{#returnType}}
{{#returnContainer}}
{{{returnType}}} result;
{{/returnContainer}}
{{^returnContainer}}
{{{returnType}}} result({{{defaultResponse}}});
{{/returnContainer}}
if(responseHttpContentType == U("application/json"))
{
web::json::value json = web::json::value::parse(response);
{{#isListContainer}}for( auto& item : json.as_array() )
{
{{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item));
{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item));
{{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item));
{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item));
{{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}});
itemObj->fromJson(item);
result.push_back(itemObj);
result.push_back(itemObj);
{{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}
}
{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}for( auto& item : json.as_object() )
@@ -279,7 +328,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
itemObj->fromJson(item);
result[item.first] = itemObj;
{{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}
}
}
{{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json);
{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json);
{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}}
@@ -290,18 +339,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r
}{{/vendorExtensions.x-codegen-response.isString}}
// else if(responseHttpContentType == U("multipart/form-data"))
// {
// TODO multipart response parsing
// TODO multipart response parsing
// }
else
else
{
throw ApiException(500
, U("error calling findPetsByStatus: unsupported response type"));
}
return result;
{{/returnType}}
{{/vendorExtensions.x-codegen-response-ishttpcontent}}
});
});
}
{{/operation}}

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* ApiClient.h
*
* This is an API client responsible for stating the HTTP calls
*
* This is an API client responsible for stating the HTTP calls
*/
#ifndef ApiClient_H_
@@ -14,8 +14,8 @@
#include "IHttpBody.h"
#include "HttpContent.h"
#include <memory>
#include <vector>
#include <memory>
#include <vector>
#include <cpprest/details/basic_types.h>
#include <cpprest/http_client.h>
@@ -31,39 +31,39 @@ class {{declspec}} ApiClient
public:
ApiClient( std::shared_ptr<ApiConfiguration> configuration = nullptr );
virtual ~ApiClient();
std::shared_ptr<ApiConfiguration> getConfiguration() const;
void setConfiguration(std::shared_ptr<ApiConfiguration> configuration);
static utility::string_t parameterToString(utility::string_t value);
static utility::string_t parameterToString(int32_t value);
static utility::string_t parameterToString(int64_t value);
template<class T>
static utility::string_t parameterToArrayString(std::vector<T> value)
{
utility::stringstream_t ss;
for( size_t i = 0; i < value.size(); i++)
{
if( i > 0) ss << U(", ");
ss << ApiClient::parameterToString(value[i]);
}
return ss.str();
return ss.str();
}
pplx::task<web::http::http_response> callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
const std::shared_ptr<IHttpBody> postBody,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
pplx::task<web::http::http_response> callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
const std::shared_ptr<IHttpBody> postBody,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams,
const utility::string_t& contentType
) const;
protected:
std::shared_ptr<ApiConfiguration> m_Configuration;

View File

@@ -40,91 +40,91 @@ utility::string_t ApiClient::parameterToString(int32_t value)
return utility::conversions::to_string_t(std::to_string(value));
}
pplx::task<web::http::http_response> ApiClient::callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
pplx::task<web::http::http_response> ApiClient::callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
const std::shared_ptr<IHttpBody> postBody,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams,
const utility::string_t& contentType
) const
{
if (postBody != nullptr && formParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and form params"));
}
if (postBody != nullptr && formParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and form params"));
}
if (postBody != nullptr && fileParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and file params"));
}
if (postBody != nullptr && fileParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and file params"));
}
if (fileParams.size() > 0 && contentType != U("multipart/form-data"))
{
throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data"));
}
if (fileParams.size() > 0 && contentType != U("multipart/form-data"))
{
throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data"));
}
web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig());
web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig());
web::http::http_request request;
for ( auto& kvp : headerParams )
{
request.headers().add(kvp.first, kvp.second);
}
web::http::http_request request;
for ( auto& kvp : headerParams )
{
request.headers().add(kvp.first, kvp.second);
}
if (fileParams.size() > 0)
{
MultipartFormData uploadData;
for (auto& kvp : formParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
for (auto& kvp : fileParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
if (postBody != nullptr)
{
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
web::http::uri_builder formData;
for (auto& kvp : formParams)
{
formData.append_query(kvp.first, kvp.second);
}
request.set_body(formData.query(), U("application/x-www-form-urlencoded"));
}
}
if (fileParams.size() > 0)
{
MultipartFormData uploadData;
for (auto& kvp : formParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
for (auto& kvp : fileParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
if (postBody != nullptr)
{
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
web::http::uri_builder formData;
for (auto& kvp : formParams)
{
formData.append_query(kvp.first, kvp.second);
}
request.set_body(formData.query(), U("application/x-www-form-urlencoded"));
}
}
web::http::uri_builder builder(path);
for (auto& kvp : queryParams)
{
builder.append_query(kvp.first, kvp.second);
}
request.set_request_uri(builder.to_uri());
request.set_method(method);
if ( !request.headers().has( web::http::header_names::user_agent ) )
{
request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() );
}
web::http::uri_builder builder(path);
for (auto& kvp : queryParams)
{
builder.append_query(kvp.first, kvp.second);
}
request.set_request_uri(builder.to_uri());
request.set_method(method);
if ( !request.headers().has( web::http::header_names::user_agent ) )
{
request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() );
}
return client.request(request);
return client.request(request);
}
{{#apiNamespaceDeclarations}}

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* ApiConfiguration.h
*
* This class represents a single item of a multipart-formdata request.
*
* This class represents a single item of a multipart-formdata request.
*/
#ifndef ApiConfiguration_H_
@@ -12,7 +12,7 @@
#include <map>
#include <cpprest/details/basic_types.h>
#include <cpprest/details/basic_types.h>
#include <cpprest/http_client.h>
{{#apiNamespaceDeclarations}}
namespace {{this}} {
@@ -23,18 +23,18 @@ class {{declspec}} ApiConfiguration
public:
ApiConfiguration();
virtual ~ApiConfiguration();
web::http::client::http_client_config& getHttpConfig();
void setHttpConfig( web::http::client::http_client_config& value );
utility::string_t getBaseUrl() const;
void setBaseUrl( const utility::string_t value );
utility::string_t getUserAgent() const;
void setUserAgent( const utility::string_t value );
std::map<utility::string_t, utility::string_t>& getDefaultHeaders();
utility::string_t getApiKey( const utility::string_t& prefix) const;
void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey );
@@ -43,7 +43,7 @@ protected:
std::map<utility::string_t, utility::string_t> m_DefaultHeaders;
std::map<utility::string_t, utility::string_t> m_ApiKeys;
web::http::client::http_client_config m_HttpConfig;
utility::string_t m_UserAgent;
utility::string_t m_UserAgent;
};
{{#apiNamespaceDeclarations}}

View File

@@ -1,7 +1,7 @@
{{>licenseInfo}}
/*
* ApiException.h
*
*
* This is the exception being thrown in case the api call was not successful
*/
@@ -10,7 +10,7 @@
{{{defaultInclude}}}
#include <memory>
#include <memory>
#include <map>
#include <cpprest/details/basic_types.h>
@@ -33,12 +33,12 @@ public:
, std::map<utility::string_t, utility::string_t>& headers
, std::shared_ptr<std::istream> content = nullptr );
virtual ~ApiException();
std::map<utility::string_t, utility::string_t>& getHeaders();
std::shared_ptr<std::istream> getContent() const;
protected:
std::shared_ptr<std::istream> m_Content;
std::shared_ptr<std::istream> m_Content;
std::map<utility::string_t, utility::string_t> m_Headers;
};

View File

@@ -28,7 +28,7 @@ git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* HttpContent.h
*
* This class represents a single item of a multipart-formdata request.
*
* This class represents a single item of a multipart-formdata request.
*/
#ifndef HttpContent_H_
@@ -12,7 +12,7 @@
#include <memory>
#include <cpprest/details/basic_types.h>
#include <cpprest/details/basic_types.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
@@ -38,7 +38,7 @@ public:
virtual std::shared_ptr<std::istream> getData();
virtual void setData( std::shared_ptr<std::istream> value );
virtual void writeTo( std::ostream& stream );
protected:

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* IHttpBody.h
*
* This is the interface for contents that can be sent to a remote HTTP server.
*
* This is the interface for contents that can be sent to a remote HTTP server.
*/
#ifndef IHttpBody_H_

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* JsonBody.h
*
* This is a JSON http body which can be submitted via http
*
* This is a JSON http body which can be submitted via http
*/
#ifndef JsonBody_H_
@@ -11,7 +11,7 @@
{{{defaultInclude}}}
#include "IHttpBody.h"
#include <cpprest/json.h>
#include <cpprest/json.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
@@ -25,7 +25,7 @@ public:
virtual ~JsonBody();
void writeTo( std::ostream& target ) override;
protected:
web::json::value m_Json;
};

View File

@@ -7,7 +7,7 @@ namespace {{this}} {
JsonBody::JsonBody( const web::json::value& json)
: m_Json(json)
{
{
}
JsonBody::~JsonBody()

View File

@@ -1,7 +1,7 @@
{{>licenseInfo}}
{{#models}}{{#model}}/*
* {{classname}}.h
*
*
* {{description}}
*/
@@ -22,15 +22,15 @@ namespace {{this}} {
/// {{description}}
/// </summary>
class {{declspec}} {{classname}}
: public ModelBase
: public ModelBase
{
public:
{{classname}}();
virtual ~{{classname}}();
/////////////////////////////////////////////
/// ModelBase overrides
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
@@ -38,10 +38,10 @@ public:
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// {{classname}} members
/////////////////////////////////////////////
/// {{classname}} members
{{#vars}}
/// <summary>
/// {{description}}
@@ -53,7 +53,7 @@ public:
void unset{{name}}();
{{/required}}
{{/vars}}
protected:
{{#vars}}{{{datatype}}} m_{{name}};
{{^required}}bool m_{{name}}IsSet;

View File

@@ -20,7 +20,7 @@ namespace {{this}} {
{
}
void {{classname}}::validate()
void {{classname}}::validate()
{
// TODO: implement validation
}
@@ -28,7 +28,7 @@ void {{classname}}::validate()
web::json::value {{classname}}::toJson() const
{
web::json::value val = web::json::value::object();
{{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{
val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
@@ -42,7 +42,7 @@ web::json::value {{classname}}::toJson() const
}
{{#required}}val[U("{{baseName}}")] = web::json::value::array(jsonArray);
{{/required}}{{^required}}
if(jsonArray.size() > 0)
if(jsonArray.size() > 0)
{
val[U("{{baseName}}")] = web::json::value::array(jsonArray);
}
@@ -77,7 +77,7 @@ void {{classname}}::fromJson(web::json::value& val)
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}
if(item.is_null())
if(item.is_null())
{
m_{{name}}.push_back( {{{items.datatype}}}(nullptr) );
}
@@ -89,7 +89,7 @@ void {{classname}}::fromJson(web::json::value& val)
}
{{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}}
}
{{^required}}
{{^required}}
}
{{/required}}
}
@@ -97,13 +97,13 @@ void {{classname}}::fromJson(web::json::value& val)
{
{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")]));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")]));
{{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null())
{{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null())
{
{{{datatype}}} newItem({{{defaultValue}}});
newItem->fromJson(val[U("{{baseName}}")]);
{{setter}}( newItem );
}
{{/isDateTime}}{{/isString}}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")]));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")]));
@@ -135,7 +135,7 @@ void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, co
}
{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json")));
{{/required}}{{^required}}
if(jsonArray.size() > 0)
if(jsonArray.size() > 0)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json")));
}
@@ -149,7 +149,7 @@ void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, co
{
m_{{name}}->toMultipart(multipart, U("{{baseName}}."));
}
{{/isDateTime}}{{/isString}}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
@@ -174,9 +174,9 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{
m_{{name}}.clear();
{{^required}}if(multipart->hasContent(U("{{baseName}}")))
{
{
{{/required}}
web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}"))));
for( auto& item : jsonArray.as_array() )
{
@@ -184,7 +184,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}
if(item.is_null())
if(item.is_null())
{
m_{{name}}.push_back( {{{items.datatype}}}(nullptr) );
}
@@ -196,7 +196,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
}
{{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}}
}
{{^required}}
{{^required}}
}
{{/required}}
}
@@ -210,7 +210,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
newItem->fromMultiPart(multipart, U("{{baseName}}."));
{{setter}}( newItem );
}
{{/isDateTime}}{{/isString}}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}"))));
@@ -220,8 +220,8 @@ void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart,
{{setter}}( new{{name}} );
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}}
}
{{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}()
{
return m_{{name}};
@@ -235,12 +235,12 @@ void {{classname}}::{{setter}}({{{datatype}}} value)
m_{{name}} = value;
{{^required}}m_{{name}}IsSet = true;{{/required}}
}
{{/isNotContainer}}
{{/isNotContainer}}
{{^required}}bool {{classname}}::{{baseName}}IsSet() const
{
return m_{{name}}IsSet;
}
void {{classname}}::unset{{name}}()
void {{classname}}::unset{{name}}()
{
m_{{name}}IsSet = false;
}

View File

@@ -1,7 +1,7 @@
{{>licenseInfo}}
/*
* ModelBase.h
*
*
* This is the base class for all model classes
*/
@@ -13,7 +13,7 @@
#include "MultipartFormData.h"
#include <cpprest/details/basic_types.h>
#include <cpprest/json.h>
#include <cpprest/json.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
@@ -40,7 +40,7 @@ public:
static web::json::value toJson( int32_t value );
static web::json::value toJson( int64_t value );
static web::json::value toJson( double value );
static int64_t int64_tFromJson(web::json::value& val);
static int32_t int32_tFromJson(web::json::value& val);
static utility::string_t stringFromJson(web::json::value& val);
@@ -48,7 +48,7 @@ public:
static double doubleFromJson(web::json::value& val);
static bool boolFromJson(web::json::value& val);
static std::shared_ptr<HttpContent> fileFromJson(web::json::value& val);
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U(""));
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U(""));
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, std::shared_ptr<HttpContent> value );
@@ -56,14 +56,14 @@ public:
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") );
static int64_t int64_tFromHttpContent(std::shared_ptr<HttpContent> val);
static int32_t int32_tFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::string_t stringFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::datetime dateFromHttpContent(std::shared_ptr<HttpContent> val);
static bool boolFromHttpContent(std::shared_ptr<HttpContent> val);
static double doubleFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::string_t toBase64( utility::string_t value );
static utility::string_t toBase64( std::shared_ptr<std::istream> value );

View File

@@ -14,7 +14,7 @@ ModelBase::~ModelBase()
web::json::value ModelBase::toJson( const utility::string_t& value )
{
return web::json::value::string(value);
return web::json::value::string(value);
}
web::json::value ModelBase::toJson( const utility::datetime& value )
{
@@ -26,7 +26,7 @@ web::json::value ModelBase::toJson( int32_t value )
}
web::json::value ModelBase::toJson( int64_t value )
{
return web::json::value::number(value);
return web::json::value::number(value);
}
web::json::value ModelBase::toJson( double value )
{
@@ -46,7 +46,7 @@ web::json::value ModelBase::toJson( std::shared_ptr<HttpContent> content )
std::shared_ptr<HttpContent> ModelBase::fileFromJson(web::json::value& val)
{
std::shared_ptr<HttpContent> content(new HttpContent);
if(val.has_field(U("ContentDisposition")))
{
content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) );
@@ -169,14 +169,14 @@ utility::string_t ModelBase::toBase64( std::shared_ptr<std::istream> value )
{
case 1:
value->read( read, 1 );
temp = read[0] << 16;
temp = read[0] << 16;
base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] );
base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] );
base64.append( 2, Base64PadChar );
break;
case 2:
value->read( read, 2 );
temp = read[0] << 16;
temp = read[0] << 16;
temp += read[1] << 8;
base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] );
base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] );
@@ -191,7 +191,7 @@ utility::string_t ModelBase::toBase64( std::shared_ptr<std::istream> value )
std::shared_ptr<std::istream> ModelBase::fromBase64( const utility::string_t& encoded )
{
std::shared_ptr<std::stringstream> result(new std::stringstream);
char outBuf[3] = { 0 };
uint32_t temp = 0;
@@ -201,9 +201,9 @@ std::shared_ptr<std::istream> ModelBase::fromBase64( const utility::string_t& en
for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ )
{
temp <<= 6;
if ( *cursor >= 0x41 && *cursor <= 0x5A )
if ( *cursor >= 0x41 && *cursor <= 0x5A )
{
temp |= *cursor - 0x41;
temp |= *cursor - 0x41;
}
else if ( *cursor >= 0x61 && *cursor <= 0x7A )
{
@@ -283,7 +283,7 @@ double ModelBase::doubleFromJson(web::json::value& val)
int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
int64_t result = 0;
ss >> result;
@@ -292,7 +292,7 @@ int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr<HttpContent> val)
int32_t ModelBase::int32_tFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
int32_t result = 0;
ss >> result;
@@ -302,22 +302,22 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr<HttpContent>
{
std::shared_ptr<std::istream> data = val->getData();
data->seekg( 0, data->beg );
std::string str((std::istreambuf_iterator<char>(*data.get())),
std::istreambuf_iterator<char>());
return utility::conversions::to_string_t(str);
}
utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::string_t str = ModelBase::stringFromHttpContent(val);
return utility::datetime::from_string(str, utility::datetime::ISO_8601);
}
bool ModelBase::boolFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
bool result = false;
ss >> result;
@@ -326,7 +326,7 @@ bool ModelBase::boolFromHttpContent(std::shared_ptr<HttpContent> val)
double ModelBase::doubleFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
double result = 0.0;
ss >> result;

View File

@@ -1,8 +1,8 @@
{{>licenseInfo}}
/*
* MultipartFormData.h
*
* This class represents a container for building a application/x-multipart-formdata requests.
*
* This class represents a container for building a application/x-multipart-formdata requests.
*/
#ifndef MultipartFormData_H_
@@ -36,7 +36,7 @@ public:
virtual std::shared_ptr<HttpContent> getContent(const utility::string_t& name) const;
virtual bool hasContent(const utility::string_t& name) const;
virtual void writeTo( std::ostream& target );
protected:
std::vector<std::shared_ptr<HttpContent>> m_Contents;
utility::string_t m_Boundary;

View File

@@ -1,9 +1,9 @@
{{>licenseInfo}}
#include "MultipartFormData.h"
#include "ModelBase.h"
#include "ModelBase.h"
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_io.hpp>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
@@ -82,7 +82,7 @@ void MultipartFormData::writeTo( std::ostream& target )
// body
std::shared_ptr<std::istream> data = content->getData();
data->seekg( 0, data->end );
std::vector<char> dataBytes( data->tellg() );

View File

@@ -64,7 +64,7 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType}
{{/isApiKey}}
{{#isBasic}}
// http basic authentication required
if a.Configuration.UserName != "" || a.Configuration.Password != ""{
if a.Configuration.Username != "" || a.Configuration.Password != ""{
localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString()
}
{{/isBasic}}
@@ -83,16 +83,11 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType}
{{#queryParams}}
{{#isListContainer}}
var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}"
if collectionFormat == "multi" {
for _, value := range {{paramName}} {
localVarQueryParams.Add("{{baseName}}", value)
}
} else {
localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat))
}
localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat))
{{/isListContainer}}
{{^isListContainer}}
localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, ""))
localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, ""))
{{/isListContainer}}
{{/queryParams}}
{{/hasQueryParams}}

View File

@@ -79,18 +79,21 @@ func (c *APIClient) CallAPI(path string, method string,
return nil, fmt.Errorf("invalid method %v", method)
}
func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string {
if reflect.TypeOf(obj).String() == "[]string" {
switch collectionFormat {
case "pipes":
return strings.Join(obj.([]string), "|")
case "ssv":
return strings.Join(obj.([]string), " ")
case "tsv":
return strings.Join(obj.([]string), "\t")
case "csv" :
return strings.Join(obj.([]string), ",")
}
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
delimiter := ""
switch collectionFormat {
case "pipes":
delimiter = "|"
case "ssv":
delimiter = " "
case "tsv":
delimiter = "\t"
case "csv":
delimiter = ","
}
if reflect.TypeOf(obj).Kind() == reflect.Slice {
return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
}
return fmt.Sprintf("%v", obj)

View File

@@ -9,7 +9,7 @@ import (
type Configuration struct {
UserName string `json:"userName,omitempty"`
Username string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"`
APIKey map[string]string `json:"APIKey,omitempty"`
@@ -42,7 +42,7 @@ func NewConfiguration() *Configuration {
}
func (c *Configuration) GetBasicAuthEncodedString() string {
return base64.StdEncoding.EncodeToString([]byte(c.UserName + ":" + c.Password))
return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password))
}
func (c *Configuration) AddDefaultHeader(key string, value string) {

View File

@@ -1,3 +1,3 @@
{{#isBodyParam}}<div class="param">{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isBodyParam}}<div class="param">{{baseName}} {{#baseType}}<a href="#{{baseType}}">{{baseType}}</a>{{/baseType}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Body Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isBodyParam}}
<div class="param-desc"><span class="param-type">Body Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isBodyParam}}

View File

@@ -143,7 +143,10 @@ export class {{classname}} {
// oauth required
if (this.configuration.accessToken)
{
headers.set('Authorization', 'Bearer ' + this.configuration.accessToken);
let accessToken = typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken()
: this.configuration.accessToken;
headers.set('Authorization', 'Bearer ' + accessToken);
}
{{/isOAuth}}
{{/authMethods}}

View File

@@ -2,5 +2,5 @@ export class Configuration {
apiKey: string;
username: string;
password: string;
accessToken: string;
accessToken: string | (() => string);
}

View File

@@ -8,35 +8,6 @@ import * as models from './models';
* {{{description}}}
*/
{{/description}}
export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{
{{#additionalPropertiesType}}
[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};
{{/additionalPropertiesType}}
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}
{{#hasEnums}}
export namespace {{classname}} {
{{#vars}}
{{#isEnum}}
export enum {{enumName}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}} = <any> {{{value}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
}
{{/hasEnums}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>modelGeneric}}{{/isEnum}}
{{/model}}
{{/models}}
{{/models}}

View File

@@ -0,0 +1,12 @@
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
export enum {{classname}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}} = <any> {{{value}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@@ -0,0 +1,28 @@
export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{
{{#additionalPropertiesType}}
[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};
{{/additionalPropertiesType}}
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}{{#hasEnums}}
export namespace {{classname}} {
{{#vars}}
{{#isEnum}}
export enum {{enumName}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}} = <any> {{{value}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
}{{/hasEnums}}

View File

@@ -237,7 +237,12 @@ export class {{classname}} {
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
{{^isResponseFile}}
json: true,
{{/isResponseFile}}
{{#isResponseFile}}
encoding: null,
{{/isResponseFile}}
{{#bodyParam}}
body: {{paramName}},
{{/bodyParam}}

View File

@@ -43,7 +43,7 @@ public class CodegenTest {
final CodegenParameter file = op.formParams.get(1);
Assert.assertTrue(file.isFormParam);
Assert.assertEquals(file.dataType, "file");
Assert.assertEquals(file.dataType, "File");
Assert.assertNull(file.required);
Assert.assertTrue(file.isFile);
Assert.assertNull(file.hasMore);
@@ -187,6 +187,19 @@ public class CodegenTest {
Assert.assertTrue(op.bodyParam.isBinary);
Assert.assertTrue(op.responses.get(0).isBinary);
}
@Test(description = "return file when response format is file")
public void fileResponeseTest() {
final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/fileResponseTest.json");
final DefaultCodegen codegen = new DefaultCodegen();
final String path = "/tests/fileResponse";
final Operation p = model.getPaths().get(path).getGet();
final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions());
Assert.assertEquals(op.returnType, "File");
Assert.assertTrue(op.responses.get(0).isFile);
Assert.assertTrue(op.isResponseFile);
}
@Test(description = "discriminator is present")
public void discriminatorTest() {

View File

@@ -3,7 +3,7 @@ package io.swagger.codegen.java;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.options.JavaClientOptionsProvider;
import io.swagger.codegen.options.JavaOptionsProvider;
import io.swagger.codegen.options.JavaClientOptionsProvider;
import io.swagger.codegen.languages.JavaClientCodegen;
import io.swagger.codegen.options.OptionsProvider;
@@ -32,33 +32,37 @@ public class JavaClientOptionsTest extends AbstractOptionsTest {
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
clientCodegen.setModelPackage(JavaOptionsProvider.MODEL_PACKAGE_VALUE);
clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE);
times = 1;
clientCodegen.setApiPackage(JavaOptionsProvider.API_PACKAGE_VALUE);
clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE);
times = 1;
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaOptionsProvider.SORT_PARAMS_VALUE));
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setInvokerPackage(JavaOptionsProvider.INVOKER_PACKAGE_VALUE);
clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE);
times = 1;
clientCodegen.setGroupId(JavaOptionsProvider.GROUP_ID_VALUE);
clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE);
times = 1;
clientCodegen.setArtifactId(JavaOptionsProvider.ARTIFACT_ID_VALUE);
clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE);
times = 1;
clientCodegen.setArtifactVersion(JavaOptionsProvider.ARTIFACT_VERSION_VALUE);
clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE);
times = 1;
clientCodegen.setSourceFolder(JavaOptionsProvider.SOURCE_FOLDER_VALUE);
clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE);
times = 1;
clientCodegen.setLocalVariablePrefix(JavaOptionsProvider.LOCAL_PREFIX_VALUE);
clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE);
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE));
clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE);
times = 1;
clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE);
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JavaClientOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE));
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;
//clientCodegen.setSupportJava6(Boolean.valueOf(JavaOptionsProvider.SUPPORT_JAVA6));
//times = 1;
clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaOptionsProvider.USE_BEANVALIDATION));
clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION));
times = 1;
clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION));
times = 1;
}};
}

View File

@@ -1,6 +1,5 @@
package io.swagger.codegen.options;
import com.google.common.collect.ImmutableMap;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.JavaClientCodegen;
@@ -9,6 +8,8 @@ import java.util.Map;
public class JavaClientOptionsProvider extends JavaOptionsProvider {
public static final String PERFORM_BEANVALIDATION = "false";
public static final String DEFAULT_LIBRARY_VALUE = "jersey2";
@Override
@@ -16,9 +17,11 @@ public class JavaClientOptionsProvider extends JavaOptionsProvider {
Map<String, String> options = new HashMap<String, String>(super.createOptions());
options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE);
options.put(JavaClientCodegen.USE_RX_JAVA, "false");
options.put(JavaClientCodegen.USE_PLAY24_WS, "false");
options.put(JavaClientCodegen.PARCELABLE_MODEL, "false");
options.put(JavaClientCodegen.SUPPORT_JAVA6, "false");
options.put(JavaClientCodegen.USE_BEANVALIDATION, "false");
options.put(JavaClientCodegen.PERFORM_BEANVALIDATION, PERFORM_BEANVALIDATION);
return options;
}

View File

@@ -11,6 +11,8 @@ public class JavaOptionsProvider implements OptionsProvider {
public static final String MODEL_PACKAGE_VALUE = "package";
public static final String API_PACKAGE_VALUE = "apiPackage";
public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test";
public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0";
public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0";
public static final String SORT_PARAMS_VALUE = "false";
public static final String GROUP_ID_VALUE = "io.swagger.test";
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
@@ -37,6 +39,8 @@ public class JavaOptionsProvider implements OptionsProvider {
.put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE)
.put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE)
.put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE)
.put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE)
.put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE)
.put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE)
.put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE)

View File

@@ -14,6 +14,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider {
public static final String SORT_PARAMS_VALUE = "false";
public static final String GROUP_ID_VALUE = "io.swagger.test";
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0";
public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0";
public static final String SOURCE_FOLDER_VALUE = "src/main/java/test";
public static final String LOCAL_PREFIX_VALUE = "tst";
public static final String DEFAULT_LIBRARY_VALUE = "jersey2";
@@ -49,6 +51,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider {
.put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE)
.put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE)
.put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE)
.put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE)
.put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE)
.put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE)
.put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE)

View File

@@ -0,0 +1,33 @@
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "File Response Test",
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"basePath": "/v2",
"schemes": [
"http"
],
"paths": {
"/tests/fileResponse": {
"get": {
"operationId": "fileresponsetest",
"produces": [
"application/octet-stream"
],
"responses": {
"200": {
"description": "OutputFileData",
"schema": {
"type": "file"
}
}
}
}
}
}
}

View File

@@ -565,7 +565,7 @@ paths:
tags:
- fake
summary: To test "client" model
descriptions: To test "client" model
description: To test "client" model
operationId: testClientModel
consumes:
- application/json
@@ -587,7 +587,7 @@ paths:
tags:
- fake
summary: To test enum parameters
descriptions: To test enum parameters
description: To test enum parameters
operationId: testEnumParameters
consumes:
- "*/*"
@@ -1080,7 +1080,6 @@ definitions:
- 1.1
- -1.2
outerEnum:
type: string
$ref: '#/definitions/OuterEnum'
AdditionalPropertiesClass:
type: object

View File

@@ -1,72 +1,67 @@
/**
* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http';
import {Injectable, Optional} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import * as models from '../model/models';
import 'rxjs/Rx';
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import * as models from '../model/models';
import { BASE_PATH } from '../variables';
import { Configuration } from '../configuration';
/* tslint:disable:no-unused-variable member-ordering */
'use strict';
@Injectable()
export class FakeApi {
protected basePath = 'https://petstore.swagger.io *_/ &#39; \&quot; &#x3D;end \\r\\n \\n \\r/v2 *_/ &#39; \&quot; &#x3D;end \\r\\n \\n \\r';
public defaultHeaders : Headers = new Headers();
protected basePath = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r';
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional() basePath: string) {
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
}
}
/**
* To test code injection *_/ &#39; \&quot; &#x3D;end \\r\\n \\n \\r
*
* @param test code inject * &#39; &quot; &#x3D;end rn n r To test code injection *_/ &#39; \&quot; &#x3D;end \\r\\n \\n \\r
* Extends object by coping non-existing properties.
* @param objA object to be extended
* @param objB source object
*/
public testCodeInjectEndRnNR (test code inject * &#39; &quot; &#x3D;end rn n r?: string, extraHttpRequestParams?: any ) : Observable<{}> {
const path = this.basePath + '/fake';
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
(objA as any)[key] = (objB as any)[key];
}
}
return <T1&T2>objA;
}
let queryParameters = new URLSearchParams();
let headerParams = this.defaultHeaders;
let formParams = new URLSearchParams();
headerParams.set('Content-Type', 'application/x-www-form-urlencoded');
formParams['test code inject */ &#39; &quot; &#x3D;end \r\n \n \r'] = test code inject * &#39; &quot; &#x3D;end rn n r;
let requestOptions: RequestOptionsArgs = {
method: 'PUT',
headers: headerParams,
search: queryParameters
};
requestOptions.body = formParams.toString();
return this.http.request(path, requestOptions)
/**
* To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*
* @param test code inject * &#39; &quot; &#x3D;end rn n r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*/
public testCodeInjectEndRnNR(test code inject * &#39; &quot; &#x3D;end rn n r?: string, extraHttpRequestParams?: any): Observable<{}> {
return this.testCodeInjectEndRnNRWithHttpInfo(test code inject * &#39; &quot; &#x3D;end rn n r, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
@@ -76,4 +71,54 @@ export class FakeApi {
});
}
/**
* To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*
* @param test code inject * &#39; &quot; &#x3D;end rn n r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*/
public testCodeInjectEndRnNRWithHttpInfo(test code inject * &#39; &quot; &#x3D;end rn n r?: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/fake`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
let formParams = new URLSearchParams();
// to determine the Content-Type header
let consumes: string[] = [
'application/json',
'*_/ =end -- '
];
// to determine the Accept header
let produces: string[] = [
'application/json',
'*_/ =end -- '
];
headers.set('Content-Type', 'application/x-www-form-urlencoded');
if (test code inject * &#39; &quot; &#x3D;end rn n r !== undefined) {
formParams.set('test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r', <any>test code inject * &#39; &quot; &#x3D;end rn n r);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: formParams.toString(),
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
}

View File

@@ -0,0 +1,6 @@
export class Configuration {
apiKey: string;
username: string;
password: string;
accessToken: string | (() => string);
}

View File

@@ -1,2 +1,4 @@
export * from './api/api';
export * from './model/models';
export * from './model/models';
export * from './variables';
export * from './configuration';

View File

@@ -1,38 +1,24 @@
/**
* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
import * as models from './models';
/**
* Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r
* Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r
*/
export interface ModelReturn {
/**
* property description *_/ ' \" =end \\r\\n \\n \\r
* property description *_/ ' \" =end -- \\r\\n \\n \\r
*/
return?: number;
}

View File

@@ -0,0 +1,3 @@
import { OpaqueToken } from '@angular/core';
export const BASE_PATH = new OpaqueToken('basePath');

Some files were not shown because too many files have changed in this diff Show More