forked from loafle/openapi-generator-original
Merge remote-tracking branch 'origin/master' into 2.3.0
This commit is contained in:
@@ -1737,7 +1737,11 @@ public class DefaultCodegen {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
property.maxItems = ap.getMaxItems();
|
||||
property.minItems = ap.getMinItems();
|
||||
CodegenProperty cp = fromProperty(property.name, ap.getItems());
|
||||
String itemName = (String) p.getVendorExtensions().get("x-item-name");
|
||||
if (itemName == null) {
|
||||
itemName = property.name;
|
||||
}
|
||||
CodegenProperty cp = fromProperty(itemName, ap.getItems());
|
||||
updatePropertyForArray(property, cp);
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.swagger.codegen;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import com.samskivert.mustache.Template;
|
||||
import io.swagger.codegen.ignore.CodegenIgnoreProcessor;
|
||||
import io.swagger.codegen.utils.ImplementationVersion;
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.models.auth.OAuth2Definition;
|
||||
import io.swagger.models.auth.SecuritySchemeDefinition;
|
||||
@@ -126,8 +127,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
}
|
||||
config.processOpts();
|
||||
config.preprocessSwagger(swagger);
|
||||
// TODO need to obtain version from a file instead of hardcoding it
|
||||
config.additionalProperties().put("generatorVersion", "2.2.3-SNAPSHOT");
|
||||
config.additionalProperties().put("generatorVersion", ImplementationVersion.read());
|
||||
config.additionalProperties().put("generatedDate", DateTime.now().toString());
|
||||
config.additionalProperties().put("generatorClass", config.getClass().getName());
|
||||
config.additionalProperties().put("inputSpec", config.getInputSpec());
|
||||
@@ -581,6 +581,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
files.add(ignoreFile);
|
||||
}
|
||||
|
||||
final String swaggerVersionMetadata = config.outputFolder() + File.separator + ".swagger-codegen" + File.separator + "VERSION";
|
||||
File swaggerVersionMetadataFile = new File(swaggerVersionMetadata);
|
||||
try {
|
||||
writeToFile(swaggerVersionMetadata, ImplementationVersion.read());
|
||||
files.add(swaggerVersionMetadataFile);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Could not generate supporting file '" + swaggerVersionMetadata + "'", e);
|
||||
}
|
||||
|
||||
/*
|
||||
* The following code adds default LICENSE (Apache-2.0) for all generators
|
||||
* To use license other than Apache2.0, update the following file:
|
||||
|
||||
@@ -97,6 +97,7 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
supportingFiles.add(new SupportingFile("multipart-source.mustache", "", "MultipartFormData.cpp"));
|
||||
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
|
||||
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
|
||||
supportingFiles.add(new SupportingFile("cmake-lists.mustache", "", "CMakeLists.txt"));
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t"));
|
||||
|
||||
@@ -17,16 +17,12 @@ import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public class CsharpDotNet2ClientCodegen extends AbstractCSharpCodegen {
|
||||
public static final String CLIENT_PACKAGE = "clientPackage";
|
||||
protected String packageName = "IO.Swagger";
|
||||
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();
|
||||
|
||||
@@ -34,128 +30,74 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
|
||||
// at the moment
|
||||
importMapping.clear();
|
||||
|
||||
outputFolder = "generated-code" + File.separator + "CsharpDotNet2";
|
||||
modelTemplateFiles.put("model.mustache", ".cs");
|
||||
apiTemplateFiles.put("api.mustache", ".cs");
|
||||
embeddedTemplateDir = templateDir = "CsharpDotNet2";
|
||||
apiPackage = "IO.Swagger.Api";
|
||||
modelPackage = "IO.Swagger.Model";
|
||||
|
||||
setApiPackage("IO.Swagger.Api");
|
||||
setModelPackage("IO.Swagger.Model");
|
||||
setSourceFolder("src" + File.separator + "main" + File.separator + this.getName());
|
||||
|
||||
modelDocTemplateFiles.put("model_doc.mustache", ".md");
|
||||
apiDocTemplateFiles.put("api_doc.mustache", ".md");
|
||||
|
||||
setReservedWordsLowerCase(
|
||||
Arrays.asList(
|
||||
// local variable names in API methods (endpoints)
|
||||
"path", "queryParams", "headerParams", "formParams", "fileParams", "postBody",
|
||||
"authSettings", "response", "StatusCode",
|
||||
// C# reserved word
|
||||
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while")
|
||||
);
|
||||
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"string",
|
||||
"bool?",
|
||||
"double?",
|
||||
"int?",
|
||||
"long?",
|
||||
"float?",
|
||||
"byte[]",
|
||||
"List",
|
||||
"Dictionary",
|
||||
"DateTime?",
|
||||
"String",
|
||||
"Boolean",
|
||||
"Double",
|
||||
"Integer",
|
||||
"Long",
|
||||
"Float",
|
||||
"Guid?",
|
||||
"System.IO.Stream", // not really a primitive, we include it to avoid model import
|
||||
"Object")
|
||||
);
|
||||
instantiationTypes.put("array", "List");
|
||||
instantiationTypes.put("map", "Dictionary");
|
||||
|
||||
typeMapping = new HashMap<String, String>();
|
||||
typeMapping.put("string", "string");
|
||||
typeMapping.put("boolean", "bool?");
|
||||
typeMapping.put("integer", "int?");
|
||||
typeMapping.put("float", "float?");
|
||||
typeMapping.put("long", "long?");
|
||||
typeMapping.put("double", "double?");
|
||||
typeMapping.put("number", "double?");
|
||||
typeMapping.put("datetime", "DateTime?");
|
||||
typeMapping.put("date", "DateTime?");
|
||||
typeMapping.put("file", "System.IO.Stream");
|
||||
typeMapping.put("array", "List");
|
||||
typeMapping.put("list", "List");
|
||||
typeMapping.put("map", "Dictionary");
|
||||
typeMapping.put("object", "Object");
|
||||
typeMapping.put("uuid", "Guid?");
|
||||
|
||||
cliOptions.clear();
|
||||
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).")
|
||||
.defaultValue("IO.Swagger"));
|
||||
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0"));
|
||||
cliOptions.add(new CliOption(CLIENT_PACKAGE, "C# client package name (convention: Camel.Case).")
|
||||
.defaultValue("IO.Swagger.Client"));
|
||||
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME,
|
||||
"C# package name (convention: Camel.Case).")
|
||||
.defaultValue(packageName));
|
||||
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION,
|
||||
"C# package version.")
|
||||
.defaultValue(packageVersion));
|
||||
cliOptions.add(new CliOption(CLIENT_PACKAGE,
|
||||
"C# client package name (convention: Camel.Case).")
|
||||
.defaultValue(clientPackage));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) {
|
||||
setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION));
|
||||
} else {
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
|
||||
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
|
||||
apiPackage = packageName + ".Api";
|
||||
modelPackage = packageName + ".Model";
|
||||
clientPackage = packageName + ".Client";
|
||||
} else {
|
||||
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
|
||||
}
|
||||
|
||||
if (additionalProperties.containsKey(CLIENT_PACKAGE)) {
|
||||
this.setClientPackage((String) additionalProperties.get(CLIENT_PACKAGE));
|
||||
} else {
|
||||
additionalProperties.put(CLIENT_PACKAGE, clientPackage);
|
||||
additionalProperties.put(CLIENT_PACKAGE, getClientPackage());
|
||||
}
|
||||
|
||||
final String clientPackage = getClientPackage();
|
||||
final String clientPackagePath = clientPackage.replace(".", java.io.File.separator);
|
||||
|
||||
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"));
|
||||
sourceFolder + File.separator + clientPackagePath, "Configuration.cs"));
|
||||
supportingFiles.add(new SupportingFile("ApiClient.mustache",
|
||||
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs"));
|
||||
sourceFolder + File.separator + clientPackagePath, "ApiClient.cs"));
|
||||
supportingFiles.add(new SupportingFile("ApiException.mustache",
|
||||
sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
|
||||
sourceFolder + File.separator + clientPackagePath, "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.mustache", "", "README.md"));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiPackage() {
|
||||
return packageName + ".Api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String modelPackage() {
|
||||
return packageName + ".Model";
|
||||
}
|
||||
|
||||
public String getClientPackage(){
|
||||
return packageName + ".Client";
|
||||
}
|
||||
|
||||
public void setClientPackage(String clientPackage) {
|
||||
this.clientPackage = clientPackage;
|
||||
}
|
||||
|
||||
public void setPackageName(String packageName) {
|
||||
this.packageName = packageName;
|
||||
}
|
||||
|
||||
public void setPackageVersion(String packageVersion) {
|
||||
this.packageVersion = packageVersion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
@@ -171,14 +113,6 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
|
||||
return "Generates a C# .Net 2.0 client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
if(this.reservedWordsMappings().containsKey(name)) {
|
||||
return this.reservedWordsMappings().get(name);
|
||||
}
|
||||
return "_" + name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
|
||||
@@ -189,143 +123,6 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
|
||||
return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize the variable name
|
||||
// pet_id => PetId
|
||||
name = camelize(name);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if (isReservedWord(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toParamName(String name) {
|
||||
// replace - with _ e.g. created-at => created_at
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize(lower) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if (isReservedWord(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
if (!StringUtils.isEmpty(modelNamePrefix)) {
|
||||
name = modelNamePrefix + "_" + name;
|
||||
}
|
||||
|
||||
if (!StringUtils.isEmpty(modelNameSuffix)) {
|
||||
name = name + "_" + modelNameSuffix;
|
||||
}
|
||||
|
||||
name = sanitizeName(name);
|
||||
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if (isReservedWord(name)) {
|
||||
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
|
||||
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
|
||||
}
|
||||
|
||||
// model name starts with number
|
||||
if (name.matches("^\\d.*")) {
|
||||
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name));
|
||||
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
return camelize(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
// should be the same as the model name
|
||||
return toModelName(name);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
return super.getTypeDeclaration(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
||||
type = typeMapping.get(swaggerType.toLowerCase());
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// throw exception if method name is empty (should not occur as an auto-generated method name will be used)
|
||||
if (StringUtils.isEmpty(operationId)) {
|
||||
throw new RuntimeException("Empty method name (operationId) not allowed");
|
||||
}
|
||||
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if (isReservedWord(operationId)) {
|
||||
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
|
||||
operationId = "call_" + operationId;
|
||||
}
|
||||
|
||||
return camelize(sanitizeName(operationId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeQuotationMark(String input) {
|
||||
// remove " to avoid code injection
|
||||
return input.replace("\"", "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeUnsafeCharacters(String input) {
|
||||
return input.replace("*/", "*_/").replace("/*", "/_*");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String apiDocFileFolder() {
|
||||
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar);
|
||||
|
||||
@@ -29,10 +29,13 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
public static final String NPM_VERSION = "npmVersion";
|
||||
public static final String NPM_REPOSITORY = "npmRepository";
|
||||
public static final String SNAPSHOT = "snapshot";
|
||||
public static final String USE_OPAQUE_TOKEN = "useOpaqueToken";
|
||||
public static final String INJECTION_TOKEN = "injectionToken";
|
||||
|
||||
protected String npmName = null;
|
||||
protected String npmVersion = "1.0.0";
|
||||
protected String npmRepository = null;
|
||||
protected String injectionToken = "InjectionToken<string>";
|
||||
|
||||
public TypeScriptAngular2ClientCodegen() {
|
||||
super();
|
||||
@@ -52,6 +55,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package"));
|
||||
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
|
||||
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
this.cliOptions.add(new CliOption(USE_OPAQUE_TOKEN, "When setting this property to true, OpaqueToken is used instead of InjectionToken", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,6 +90,11 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
if(additionalProperties.containsKey(NPM_NAME)) {
|
||||
addNpmPackageGeneration();
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey(USE_OPAQUE_TOKEN) && Boolean.valueOf(additionalProperties.get(USE_OPAQUE_TOKEN).toString())) {
|
||||
this.setOpaqueToken();
|
||||
}
|
||||
additionalProperties.put(INJECTION_TOKEN, this.injectionToken);
|
||||
}
|
||||
|
||||
private void addNpmPackageGeneration() {
|
||||
@@ -320,4 +329,8 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
|
||||
String name = filename.substring((modelPackage() + "/").length());
|
||||
return camelize(name);
|
||||
}
|
||||
|
||||
public void setOpaqueToken() {
|
||||
this.injectionToken = "OpaqueToken";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package io.swagger.codegen.utils;
|
||||
|
||||
public class ImplementationVersion {
|
||||
public static String read() {
|
||||
// Assumes this version is required at runtime. This could be modified to use a properties file like the CLI.
|
||||
String compiledVersion = ImplementationVersion.class.getPackage().getImplementationVersion();
|
||||
if(compiledVersion != null) {
|
||||
return compiledVersion;
|
||||
}
|
||||
|
||||
return "unset";
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
{{^useSpringCloudClient}}
|
||||
import java.io.IOException;
|
||||
{{/useSpringCloudClient}}
|
||||
|
||||
import java.util.List;
|
||||
{{#async}}
|
||||
@@ -43,31 +40,20 @@ public interface {{classname}} {
|
||||
}{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} })
|
||||
@ApiResponses(value = { {{#responses}}
|
||||
@ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} })
|
||||
{{#implicitHeaders}}
|
||||
@ApiImplicitParams({
|
||||
{{#implicitHeaders}}@ApiImplicitParams({
|
||||
{{#headerParams}}{{>implicitHeader}}{{/headerParams}}
|
||||
})
|
||||
{{/implicitHeaders}}
|
||||
}){{/implicitHeaders}}
|
||||
@RequestMapping(value = "{{{path}}}",{{#singleContentTypes}}
|
||||
produces = "{{{vendorExtensions.x-accepts}}}",
|
||||
consumes = "{{{vendorExtensions.x-contentType}}}",{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}
|
||||
produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}}
|
||||
consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}}
|
||||
method = RequestMethod.{{httpMethod}})
|
||||
{{#useSpringCloudClient}}
|
||||
{{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} {
|
||||
// do some magic!
|
||||
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};
|
||||
}{{/jdk8}}
|
||||
|
||||
{{/useSpringCloudClient}}
|
||||
{{^useSpringCloudClient}}
|
||||
{{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}} @RequestHeader("Accept") String accept){{#examples}}{{#-first}} throws IOException{{/-first}}{{/examples}}{{^jdk8}};{{/jdk8}}{{#jdk8}} {
|
||||
// do some magic!
|
||||
return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}};
|
||||
}{{/jdk8}}
|
||||
|
||||
{{/useSpringCloudClient}}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
|
||||
@@ -21,12 +21,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import java.util.List;
|
||||
{{#async}}
|
||||
import java.util.concurrent.Callable;
|
||||
{{/async}}
|
||||
{{/jdk8-no-delegate}}
|
||||
{{^useSpringCloudClient}}
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
{{/useSpringCloudClient}}
|
||||
{{/async}}{{/jdk8-no-delegate}}
|
||||
{{#useBeanValidation}}
|
||||
import javax.validation.constraints.*;
|
||||
import javax.validation.Valid;
|
||||
@@ -35,72 +30,27 @@ import javax.validation.Valid;
|
||||
@Controller
|
||||
{{#operations}}
|
||||
public class {{classname}}Controller implements {{classname}} {
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public {{classname}}Controller(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
{{#isDelegate}}
|
||||
private final {{classname}}Delegate delegate;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
public {{classname}}Controller({{classname}}Delegate delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
}{{/isDelegate}}
|
||||
|
||||
{{/isDelegate}}
|
||||
{{^jdk8-no-delegate}}
|
||||
{{#operation}}
|
||||
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},
|
||||
{{/allParams}}@RequestHeader("Accept") String accept){{#examples}}{{#-first}} throws IOException{{/-first}}{{/examples}} {
|
||||
// do some magic!
|
||||
{{#useSpringCloudClient}}
|
||||
{{^isDelegate}}
|
||||
{{^async}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
{{/async}}
|
||||
{{#async}}
|
||||
{{^jdk8-no-delegate}}{{#operation}}
|
||||
public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
|
||||
{{/hasMore}}{{/allParams}}) {
|
||||
// do some magic!{{^isDelegate}}{{^async}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}}
|
||||
return new Callable<ResponseEntity<{{>returnTypes}}>>() {
|
||||
@Override
|
||||
public ResponseEntity<{{>returnTypes}}> call() throws Exception {
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
}
|
||||
};
|
||||
{{/async}}
|
||||
{{/isDelegate}}
|
||||
{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{/isDelegate}}
|
||||
{{/useSpringCloudClient}}
|
||||
{{^useSpringCloudClient}}
|
||||
{{^isDelegate}}
|
||||
{{^async}}
|
||||
{{#examples}}
|
||||
|
||||
if (accept != null && accept.contains("{{{contentType}}}")) {
|
||||
return new ResponseEntity<{{>returnTypes}}>(objectMapper.readValue("{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{>exampleReturnTypes}}.class), HttpStatus.OK);
|
||||
}
|
||||
|
||||
{{/examples}}
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
{{/async}}
|
||||
{{#async}}
|
||||
return new Callable<ResponseEntity<{{>returnTypes}}>>() {
|
||||
@Override
|
||||
public ResponseEntity<{{>returnTypes}}> call() throws Exception {
|
||||
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
|
||||
}
|
||||
};
|
||||
{{/async}}
|
||||
{{/isDelegate}}
|
||||
{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{/isDelegate}}
|
||||
{{/useSpringCloudClient}}
|
||||
};{{/async}}{{/isDelegate}}{{#isDelegate}}
|
||||
return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/isDelegate}}
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
{{/jdk8-no-delegate}}
|
||||
{{/operation}}{{/jdk8-no-delegate}}
|
||||
}
|
||||
{{/operations}}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{{#required}}
|
||||
@NotNull
|
||||
{{/required}}
|
||||
{{/required}}{{#isContainer}}{{^isPrimitiveType}}{{^isEnum}}
|
||||
@Valid{{/isEnum}}{{/isPrimitiveType}}{{/isContainer}}{{#isNotContainer}}{{^isPrimitiveType}}
|
||||
@Valid{{/isPrimitiveType}}{{/isNotContainer}}
|
||||
{{>beanValidationCore}}
|
||||
@Valid
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#
|
||||
# {{{appName}}}
|
||||
# {{{appDescription}}}
|
||||
#
|
||||
# OpenAPI spec version: 1.0.0
|
||||
#
|
||||
# https://github.com/swagger-api/swagger-codegen.git
|
||||
#
|
||||
# NOTE: Auto generated by the swagger code generator program.
|
||||
|
||||
cmake_minimum_required (VERSION 2.8)
|
||||
|
||||
#PROJECT's NAME
|
||||
project(CppRestSwaggerClient)
|
||||
|
||||
|
||||
# THE LOCATION OF OUTPUT BINARIES
|
||||
set(CMAKE_LIBRARY_DIR ${PROJECT_SOURCE_DIR}/lib)
|
||||
set(LIBRARY_OUTPUT_PATH ${CMAKE_LIBRARY_DIR})
|
||||
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
|
||||
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
endif()
|
||||
|
||||
# BUILD TYPE
|
||||
message("A ${CMAKE_BUILD_TYPE} build configuration is detected")
|
||||
|
||||
# Update require components as necessary
|
||||
#find_package(Boost 1.45.0 REQUIRED COMPONENTS ${Boost_THREAD_LIBRARY} ${Boost_SYSTEM_LIBRARY} ${Boost_REGEX_LIBRARY} ${Boost_DATE_TIME_LIBRARY} ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_FILESYSTEM_LIBRARY})
|
||||
|
||||
# build and set path to cpp rest sdk
|
||||
#set(CPPREST_ROOT ${PROJECT_SOURCE_DIR}/../../../developmentTools/3rdParty/cpprest)
|
||||
set(CPPREST_INCLUDE_DIR ${CPPREST_ROOT}/include)
|
||||
set(CPPREST_LIBRARY_DIR ${CPPREST_ROOT}/lib)
|
||||
|
||||
if( NOT DEFINED CPPREST_ROOT )
|
||||
message( FATAL_ERROR "Failed to find cpprest SDK (or missing components). Double check that \"CPPREST_ROOT\" is properly set")
|
||||
endif( NOT DEFINED CPPREST_ROOT )
|
||||
|
||||
include_directories(${PROJECT_SOURCE_DIR} api model ${CPPREST_INCLUDE_DIR})
|
||||
|
||||
#SUPPORTING FILES
|
||||
set(SUPPORTING_FILES "ApiClient" "ApiConfiguration" "ApiException" "HttpContent" "IHttpBody" "JsonBody" "ModelBase" "MultipartFormData")
|
||||
#SOURCE FILES
|
||||
file(GLOB SOURCE_FILES "api/*" "model/*")
|
||||
|
||||
add_library(${PROJECT_NAME} ${SUPPORTING_FILES} ${SOURCE_FILES})
|
||||
@@ -122,6 +122,10 @@ namespace {{packageName}}.Client
|
||||
String contentType)
|
||||
{
|
||||
var request = new RestRequest(path, method);
|
||||
{{#netStandard}}
|
||||
// disable ResetSharp.Portable built-in serialization
|
||||
request.Serializer = null;
|
||||
{{/netStandard}}
|
||||
|
||||
// add path parameter, if any
|
||||
foreach(var param in pathParams)
|
||||
@@ -161,11 +165,21 @@ namespace {{packageName}}.Client
|
||||
{
|
||||
if (postBody.GetType() == typeof(String))
|
||||
{
|
||||
{{#netStandard}}
|
||||
request.AddParameter(new Parameter { Value = postBody, Type = ParameterType.RequestBody, ContentType = "application/json" });
|
||||
{{/netStandard}}
|
||||
{{^netStandard}}
|
||||
request.AddParameter("application/json", postBody, ParameterType.RequestBody);
|
||||
{{/netStandard}}
|
||||
}
|
||||
else if (postBody.GetType() == typeof(byte[]))
|
||||
{
|
||||
{{#netStandard}}
|
||||
request.AddParameter(new Parameter { Value = postBody, Type = ParameterType.RequestBody, ContentType = contentType });
|
||||
{{/netStandard}}
|
||||
{{^netStandard}}
|
||||
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
|
||||
{{/netStandard}}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,10 @@
|
||||
{{/netStandard}}
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="**\*.cs"/>
|
||||
<Compile Include="Api\**\*.cs"/>
|
||||
<Compile Include="Client\**\*.cs"/>
|
||||
<Compile Include="Model\**\*.cs"/>
|
||||
<Compile Include="Properties\**\*.cs"/>
|
||||
</ItemGroup>
|
||||
{{^netStandard}}
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{deps, [
|
||||
{jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "v2.8.0"}}},
|
||||
{jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "2.8.2"}}},
|
||||
{jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.4.0"}}}
|
||||
]}.
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
<?php
|
||||
/**
|
||||
* ApiClient
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Class
|
||||
* @package {{invokerPackage}}
|
||||
* @author Swagger Codegen team
|
||||
* @link https://github.com/swagger-api/swagger-codegen
|
||||
*/
|
||||
|
||||
{{>partial_header}}
|
||||
/**
|
||||
* NOTE: This class is auto generated by the swagger code generator program.
|
||||
* https://github.com/swagger-api/swagger-codegen
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
namespace {{invokerPackage}};
|
||||
|
||||
/**
|
||||
* ApiClient Class Doc Comment
|
||||
*
|
||||
* @category Class
|
||||
* @package {{invokerPackage}}
|
||||
* @author Swagger Codegen team
|
||||
* @link https://github.com/swagger-api/swagger-codegen
|
||||
*/
|
||||
class ApiClient
|
||||
{
|
||||
public static $PATCH = "PATCH";
|
||||
public static $POST = "POST";
|
||||
public static $GET = "GET";
|
||||
public static $HEAD = "HEAD";
|
||||
public static $OPTIONS = "OPTIONS";
|
||||
public static $PUT = "PUT";
|
||||
public static $DELETE = "DELETE";
|
||||
|
||||
/**
|
||||
* Configuration
|
||||
*
|
||||
* @var Configuration
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* Object Serializer
|
||||
*
|
||||
* @var ObjectSerializer
|
||||
*/
|
||||
protected $serializer;
|
||||
|
||||
/**
|
||||
* Constructor of the class
|
||||
*
|
||||
* @param Configuration $config config for this ApiClient
|
||||
*/
|
||||
public function __construct(\{{invokerPackage}}\Configuration $config = null)
|
||||
{
|
||||
if ($config === null) {
|
||||
$config = Configuration::getDefaultConfiguration();
|
||||
}
|
||||
|
||||
$this->config = $config;
|
||||
$this->serializer = new ObjectSerializer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the config
|
||||
*
|
||||
* @return Configuration
|
||||
*/
|
||||
public function getConfig()
|
||||
{
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the serializer
|
||||
*
|
||||
* @return ObjectSerializer
|
||||
*/
|
||||
public function getSerializer()
|
||||
{
|
||||
return $this->serializer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get API key (with prefix if set)
|
||||
*
|
||||
* @param string $apiKeyIdentifier name of apikey
|
||||
*
|
||||
* @return string API key with the prefix
|
||||
*/
|
||||
public function getApiKeyWithPrefix($apiKeyIdentifier)
|
||||
{
|
||||
$prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier);
|
||||
$apiKey = $this->config->getApiKey($apiKeyIdentifier);
|
||||
|
||||
if (!isset($apiKey)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($prefix)) {
|
||||
$keyWithPrefix = $prefix." ".$apiKey;
|
||||
} else {
|
||||
$keyWithPrefix = $apiKey;
|
||||
}
|
||||
|
||||
return $keyWithPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the HTTP call (Sync)
|
||||
*
|
||||
* @param string $resourcePath path to method endpoint
|
||||
* @param string $method method to call
|
||||
* @param array $queryParams parameters to be place in query URL
|
||||
* @param array $postData parameters to be placed in POST body
|
||||
* @param array $headerParams parameters to be place in request header
|
||||
* @param string $responseType expected response type of the endpoint
|
||||
* @param string $endpointPath path to method endpoint before expanding parameters
|
||||
*
|
||||
* @throws \{{invokerPackage}}\ApiException on a non 2xx response
|
||||
* @return mixed
|
||||
*/
|
||||
public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null)
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
// construct the http header
|
||||
$headerParams = array_merge(
|
||||
(array)$this->config->getDefaultHeaders(),
|
||||
(array)$headerParams
|
||||
);
|
||||
|
||||
foreach ($headerParams as $key => $val) {
|
||||
$headers[] = "$key: $val";
|
||||
}
|
||||
|
||||
// form data
|
||||
if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) {
|
||||
$postData = http_build_query($postData);
|
||||
} elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model
|
||||
$postData = json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData));
|
||||
}
|
||||
|
||||
$url = $this->config->getHost() . $resourcePath;
|
||||
|
||||
$curl = curl_init();
|
||||
// set timeout, if needed
|
||||
if ($this->config->getCurlTimeout() !== 0) {
|
||||
curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout());
|
||||
}
|
||||
// set connect timeout, if needed
|
||||
if ($this->config->getCurlConnectTimeout() != 0) {
|
||||
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout());
|
||||
}
|
||||
|
||||
// return the result on success, rather than just true
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||
|
||||
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
|
||||
|
||||
// disable SSL verification, if needed
|
||||
if ($this->config->getSSLVerification() === false) {
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
|
||||
}
|
||||
|
||||
if ($this->config->getCurlProxyHost()) {
|
||||
curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost());
|
||||
}
|
||||
|
||||
if ($this->config->getCurlProxyPort()) {
|
||||
curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort());
|
||||
}
|
||||
|
||||
if ($this->config->getCurlProxyType()) {
|
||||
curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType());
|
||||
}
|
||||
|
||||
if ($this->config->getCurlProxyUser()) {
|
||||
curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword());
|
||||
}
|
||||
|
||||
if (!empty($queryParams)) {
|
||||
$url = ($url . '?' . http_build_query($queryParams));
|
||||
}
|
||||
|
||||
if ($this->config->getAllowEncoding()) {
|
||||
curl_setopt($curl, CURLOPT_ENCODING, '');
|
||||
}
|
||||
|
||||
if ($method === self::$POST) {
|
||||
curl_setopt($curl, CURLOPT_POST, true);
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||
} elseif ($method === self::$HEAD) {
|
||||
curl_setopt($curl, CURLOPT_NOBODY, true);
|
||||
} elseif ($method === self::$OPTIONS) {
|
||||
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||
} elseif ($method === self::$PATCH) {
|
||||
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||
} elseif ($method === self::$PUT) {
|
||||
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||
} elseif ($method === self::$DELETE) {
|
||||
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
|
||||
} elseif ($method !== self::$GET) {
|
||||
throw new ApiException('Method ' . $method . ' is not recognized.');
|
||||
}
|
||||
curl_setopt($curl, CURLOPT_URL, $url);
|
||||
|
||||
// Set user agent
|
||||
curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent());
|
||||
|
||||
// debugging for curl
|
||||
if ($this->config->getDebug()) {
|
||||
error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile());
|
||||
|
||||
curl_setopt($curl, CURLOPT_VERBOSE, 1);
|
||||
curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a'));
|
||||
} else {
|
||||
curl_setopt($curl, CURLOPT_VERBOSE, 0);
|
||||
}
|
||||
|
||||
// obtain the HTTP response headers
|
||||
curl_setopt($curl, CURLOPT_HEADER, 1);
|
||||
|
||||
// Make the request
|
||||
$response = curl_exec($curl);
|
||||
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
|
||||
$http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size));
|
||||
$http_body = substr($response, $http_header_size);
|
||||
$response_info = curl_getinfo($curl);
|
||||
|
||||
// debug HTTP response body
|
||||
if ($this->config->getDebug()) {
|
||||
error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile());
|
||||
}
|
||||
|
||||
// Handle the response
|
||||
if ($response_info['http_code'] === 0) {
|
||||
$curl_error_message = curl_error($curl);
|
||||
|
||||
// curl_exec can sometimes fail but still return a blank message from curl_error().
|
||||
if (!empty($curl_error_message)) {
|
||||
$error_message = "API call to $url failed: $curl_error_message";
|
||||
} else {
|
||||
$error_message = "API call to $url failed, but for an unknown reason. " .
|
||||
"This could happen if you are disconnected from the network.";
|
||||
}
|
||||
|
||||
$exception = new ApiException($error_message, 0, null, null);
|
||||
$exception->setResponseObject($response_info);
|
||||
throw $exception;
|
||||
} elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) {
|
||||
// return raw body if response is a file
|
||||
if ($responseType === '\SplFileObject' || $responseType === 'string') {
|
||||
return [$http_body, $response_info['http_code'], $http_header];
|
||||
}
|
||||
|
||||
$data = json_decode($http_body);
|
||||
if (json_last_error() > 0) { // if response is a string
|
||||
$data = $http_body;
|
||||
}
|
||||
} else {
|
||||
$data = json_decode($http_body);
|
||||
if (json_last_error() > 0) { // if response is a string
|
||||
$data = $http_body;
|
||||
}
|
||||
|
||||
throw new ApiException(
|
||||
"[".$response_info['http_code']."] Error connecting to the API ($url)",
|
||||
$response_info['http_code'],
|
||||
$http_header,
|
||||
$data
|
||||
);
|
||||
}
|
||||
return [$data, $response_info['http_code'], $http_header];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the header 'Accept' based on an array of Accept provided
|
||||
*
|
||||
* @param string[] $accept Array of header
|
||||
*
|
||||
* @return string Accept (e.g. application/json)
|
||||
*/
|
||||
public function selectHeaderAccept($accept)
|
||||
{
|
||||
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
|
||||
return null;
|
||||
} elseif (preg_grep("/application\/json/i", $accept)) {
|
||||
return 'application/json';
|
||||
} else {
|
||||
return implode(',', $accept);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the content type based on an array of content-type provided
|
||||
*
|
||||
* @param string[] $content_type Array fo content-type
|
||||
*
|
||||
* @return string Content-Type (e.g. application/json)
|
||||
*/
|
||||
public function selectHeaderContentType($content_type)
|
||||
{
|
||||
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
|
||||
return 'application/json';
|
||||
} elseif (preg_grep("/application\/json/i", $content_type)) {
|
||||
return 'application/json';
|
||||
} else {
|
||||
return implode(',', $content_type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an array of HTTP response headers
|
||||
*
|
||||
* @param string $raw_headers A string of raw HTTP response headers
|
||||
*
|
||||
* @return string[] Array of HTTP response heaers
|
||||
*/
|
||||
protected function httpParseHeaders($raw_headers)
|
||||
{
|
||||
// ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986
|
||||
$headers = [];
|
||||
$key = '';
|
||||
|
||||
foreach (explode("\n", $raw_headers) as $h) {
|
||||
$h = explode(':', $h, 2);
|
||||
|
||||
if (isset($h[1])) {
|
||||
if (!isset($headers[$h[0]])) {
|
||||
$headers[$h[0]] = trim($h[1]);
|
||||
} elseif (is_array($headers[$h[0]])) {
|
||||
$headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]);
|
||||
} else {
|
||||
$headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]);
|
||||
}
|
||||
|
||||
$key = $h[0];
|
||||
} else {
|
||||
if (substr($h[0], 0, 1) === "\t") {
|
||||
$headers[$key] .= "\r\n\t".trim($h[0]);
|
||||
} elseif (!$key) {
|
||||
$headers[0] = trim($h[0]);
|
||||
}
|
||||
trim($h[0]);
|
||||
}
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ use {{invokerPackage}}\ObjectSerializer;
|
||||
* @throws \InvalidArgumentException
|
||||
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
*/
|
||||
public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
|
||||
public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
|
||||
{
|
||||
{{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
|
||||
return $response;{{/returnType}}
|
||||
@@ -110,7 +110,7 @@ use {{invokerPackage}}\ObjectSerializer;
|
||||
* @throws \InvalidArgumentException
|
||||
* @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings)
|
||||
*/
|
||||
public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
|
||||
public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = {{#defaultValue}}'{{{.}}}'{{/defaultValue}}{{^defaultValue}}null{{/defaultValue}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
|
||||
{
|
||||
{{#allParams}}
|
||||
{{#required}}
|
||||
|
||||
@@ -90,7 +90,8 @@ void
|
||||
HttpRequestWorker *worker = new HttpRequestWorker();
|
||||
HttpRequestInput input(fullPath, "{{httpMethod}}");
|
||||
|
||||
{{#formParams}}if ({{paramName}} != nullptr) {
|
||||
{{#formParams}}
|
||||
if ({{paramName}} != nullptr) {
|
||||
{{^isFile}}input.add_var("{{baseName}}", *{{paramName}});{{/isFile}}{{#isFile}}input.add_file("{{baseName}}", (*{{paramName}}).local_filename, (*{{paramName}}).request_filename, (*{{paramName}}).mime_type);{{/isFile}}
|
||||
}
|
||||
{{/formParams}}
|
||||
@@ -125,6 +126,9 @@ void
|
||||
void
|
||||
{{classname}}::{{nickname}}Callback(HttpRequestWorker * worker) {
|
||||
QString msg;
|
||||
QString error_str = worker->error_str;
|
||||
QNetworkReply::NetworkError error_type = worker->error_type;
|
||||
|
||||
if (worker->error_type == QNetworkReply::NoError) {
|
||||
msg = QString("Success! %1 bytes").arg(worker->response.length());
|
||||
}
|
||||
@@ -132,7 +136,8 @@ void
|
||||
msg = "Error: " + worker->error_str;
|
||||
}
|
||||
|
||||
{{#returnType}}{{#isListContainer}}
|
||||
{{#returnType}}
|
||||
{{#isListContainer}}
|
||||
{{{returnType}}} output = {{{defaultResponse}}};
|
||||
QString json(worker->response);
|
||||
QByteArray array (json.toStdString().c_str());
|
||||
@@ -148,12 +153,12 @@ void
|
||||
}
|
||||
{{/isListContainer}}
|
||||
|
||||
{{^isListContainer}}{{#returnTypeIsPrimitive}}
|
||||
{{^isListContainer}}
|
||||
{{#returnTypeIsPrimitive}}
|
||||
{{{returnType}}} output; // TODO add primitive output support
|
||||
{{/returnTypeIsPrimitive}}
|
||||
{{#isMapContainer}}
|
||||
{{{returnType}}} output = {{{defaultResponse}}};
|
||||
|
||||
QString json(worker->response);
|
||||
QByteArray array (json.toStdString().c_str());
|
||||
QJsonDocument doc = QJsonDocument::fromJson(array);
|
||||
@@ -164,21 +169,21 @@ void
|
||||
setValue(&val, obj[key], "{{returnBaseType}}", "");
|
||||
output->insert(key, *val);
|
||||
}
|
||||
|
||||
|
||||
{{/isMapContainer}}
|
||||
{{^isMapContainer}}
|
||||
{{^returnTypeIsPrimitive}}QString json(worker->response);
|
||||
{{^returnTypeIsPrimitive}}
|
||||
QString json(worker->response);
|
||||
{{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}")));
|
||||
{{/returnTypeIsPrimitive}}
|
||||
{{/isMapContainer}}
|
||||
{{/isListContainer}}{{/returnType}}
|
||||
|
||||
{{/isListContainer}}
|
||||
{{/returnType}}
|
||||
worker->deleteLater();
|
||||
|
||||
{{#returnType}}emit {{nickname}}Signal(output);{{/returnType}}
|
||||
{{^returnType}}emit {{nickname}}Signal();{{/returnType}}
|
||||
emit {{nickname}}Signal({{#returnType}}output{{/returnType}});
|
||||
emit {{nickname}}SignalE({{#returnType}}output, {{/returnType}}error_type, error_str);
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
{{/operations}}
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ private:
|
||||
signals:
|
||||
{{#operations}}{{#operation}}void {{nickname}}Signal({{#returnType}}{{{returnType}}} summary{{/returnType}});
|
||||
{{/operation}}{{/operations}}
|
||||
{{#operations}}{{#operation}}void {{nickname}}SignalE({{#returnType}}{{{returnType}}} summary, {{/returnType}}QNetworkReply::NetworkError error_type, QString& error_str);
|
||||
{{/operation}}{{/operations}}
|
||||
};
|
||||
|
||||
{{#cppNamespaceDeclarations}}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Alamofire
|
||||
|
||||
class AlamofireRequestBuilderFactory: RequestBuilderFactory {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Alamofire{{#usePromiseKit}}
|
||||
import PromiseKit{{/usePromiseKit}}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// https://github.com/swagger-api/swagger-codegen
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Alamofire{{#usePromiseKit}}
|
||||
import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
|
||||
import RxSwift{{/useRxSwift}}
|
||||
|
||||
@@ -5,5 +5,5 @@ export * from './{{ classFilename }}';
|
||||
import { {{ classname }} } from './{{ classFilename }}';
|
||||
{{/operations}}
|
||||
{{/apis}}
|
||||
export const APIS = [{{#apis}}{{#operations}}{{ classname }}, {{/operations}}{{/apis}}];
|
||||
{{/apiInfo}}
|
||||
export const APIS = [{{#apis}}{{#operations}}{{ classname }}{{/operations}}{{^-last}}, {{/-last}}{{/apis}}];
|
||||
{{/apiInfo}}
|
||||
|
||||
@@ -81,7 +81,7 @@ export class {{classname}} {
|
||||
return undefined;
|
||||
} else {
|
||||
{{^isResponseFile}}
|
||||
return response.json();
|
||||
return response.json() || {};
|
||||
{{/isResponseFile}}
|
||||
{{#isResponseFile}}
|
||||
return response.blob();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { OpaqueToken } from '@angular/core';
|
||||
import { {{{injectionToken}}} } from '@angular/core';
|
||||
|
||||
export const BASE_PATH = new OpaqueToken('basePath');
|
||||
export const BASE_PATH = new {{{injectionToken}}}('basePath');
|
||||
export const COLLECTION_FORMATS = {
|
||||
'csv': ',',
|
||||
'tsv': ' ',
|
||||
|
||||
@@ -274,6 +274,42 @@ public class JavaModelTest {
|
||||
|
||||
}
|
||||
|
||||
@Test(description = "convert a model with an array property with item name")
|
||||
public void arrayModelWithItemNameTest() {
|
||||
final Model model = new ModelImpl()
|
||||
.description("a sample model")
|
||||
.property("children", new ArrayProperty()
|
||||
.description("an array property")
|
||||
.items(new RefProperty("#/definitions/Child"))
|
||||
.vendorExtension("x-item-name", "child"));
|
||||
final DefaultCodegen codegen = new JavaClientCodegen();
|
||||
final CodegenModel cm = codegen.fromModel("sample", model);
|
||||
|
||||
Assert.assertEquals(cm.name, "sample");
|
||||
Assert.assertEquals(cm.classname, "Sample");
|
||||
Assert.assertEquals(cm.description, "a sample model");
|
||||
Assert.assertEquals(cm.vars.size(), 1);
|
||||
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("List", "Child")).size(), 2);
|
||||
|
||||
final CodegenProperty property = cm.vars.get(0);
|
||||
Assert.assertEquals(property.baseName, "children");
|
||||
Assert.assertEquals(property.complexType, "Child");
|
||||
Assert.assertEquals(property.getter, "getChildren");
|
||||
Assert.assertEquals(property.setter, "setChildren");
|
||||
Assert.assertEquals(property.datatype, "List<Child>");
|
||||
Assert.assertEquals(property.name, "children");
|
||||
Assert.assertEquals(property.defaultValue, "new ArrayList<Child>()");
|
||||
Assert.assertEquals(property.baseType, "List");
|
||||
Assert.assertEquals(property.containerType, "array");
|
||||
Assert.assertFalse(property.required);
|
||||
Assert.assertTrue(property.isContainer);
|
||||
Assert.assertFalse(property.isNotContainer);
|
||||
|
||||
final CodegenProperty itemsProperty = property.items;
|
||||
Assert.assertEquals(itemsProperty.baseName,"child");
|
||||
Assert.assertEquals(itemsProperty.name,"child");
|
||||
}
|
||||
|
||||
@Test(description = "convert an array model")
|
||||
public void arrayModelTest() {
|
||||
final Model model = new ArrayModel()
|
||||
|
||||
@@ -35,6 +35,7 @@ public class TypeScriptAngular2ClientOptionsProvider implements OptionsProvider
|
||||
.put(TypeScriptAngular2ClientCodegen.SNAPSHOT, Boolean.FALSE.toString())
|
||||
.put(TypeScriptAngular2ClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY)
|
||||
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
|
||||
.put(TypeScriptAngular2ClientCodegen.USE_OPAQUE_TOKEN, Boolean.FALSE.toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user