Code reformatting

This commit is contained in:
Ron 2015-06-07 11:56:08 -04:00
parent 22d7db2cb4
commit 1c2d0656b0
732 changed files with 61242 additions and 55773 deletions

View File

@ -1,4 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>io.swagger</groupId>
@ -62,7 +62,8 @@
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>

View File

@ -1,17 +1,17 @@
package io.swagger.codegen;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
import io.swagger.codegen.cmd.ConfigHelp;
import io.swagger.codegen.cmd.Generate;
import io.swagger.codegen.cmd.Langs;
import io.swagger.codegen.cmd.Meta;
import io.airlift.airline.Cli;
import io.airlift.airline.Help;
/**
* User: lanwen
* Date: 24.03.15
* Time: 17:56
*
* <p/>
* Command line interface for swagger codegen
* use `swagger-codegen-cli.jar help` for more info
*

View File

@ -1,10 +1,12 @@
package io.swagger.codegen.cmd;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import java.util.ServiceLoader;
import static java.util.ServiceLoader.load;
@Command(name = "config-help", description = "Config help for chosen lang")
@ -14,20 +16,9 @@ public class ConfigHelp implements Runnable {
description = "language to get config help for")
private String lang;
@Override
public void run() {
System.out.println();
CodegenConfig config = forName(lang);
System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t " + langCliOption.getDescription());
System.out.println();
}
}
/**
* Tries to load config class with SPI first, then with class name directly from classpath
*
* @param name name of config, or full qualified class name in classpath
* @return config class
*/
@ -46,4 +37,16 @@ public class ConfigHelp implements Runnable {
throw new RuntimeException("Can't load config class with name ".concat(name), e);
}
}
@Override
public void run() {
System.out.println();
CodegenConfig config = forName(lang);
System.out.println("CONFIG OPTIONS");
for (CliOption langCliOption : config.cliOptions()) {
System.out.println("\t" + langCliOption.getOpt());
System.out.println("\t " + langCliOption.getDescription());
System.out.println();
}
}
}

View File

@ -1,15 +1,15 @@
package io.swagger.codegen.cmd;
import config.Config;
import config.ConfigParser;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.models.Swagger;
import config.Config;
import config.ConfigParser;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.parser.SwaggerParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -66,6 +66,28 @@ public class Generate implements Runnable {
"Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
private String configFile;
/**
* Tries to load config class with SPI first, then with class name directly from classpath
*
* @param name name of config, or full qualified class name in classpath
* @return config class
*/
private static CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
}
// else try to load directly
try {
return (CodegenConfig) Class.forName(name).newInstance();
} catch (Exception e) {
throw new RuntimeException("Can't load config class with name ".concat(name), e);
}
}
@Override
public void run() {
verbosed(verbose);
@ -115,6 +137,7 @@ public class Generate implements Runnable {
/**
* If true parameter, adds system properties which enables debug mode in generator
*
* @param verbose - if true, enables debug mode
*/
private void verbosed(boolean verbose) {
@ -132,25 +155,4 @@ public class Generate implements Runnable {
System.setProperty("debugOperations", "");
System.setProperty("debugSupportingFiles", "");
}
/**
* Tries to load config class with SPI first, then with class name directly from classpath
* @param name name of config, or full qualified class name in classpath
* @return config class
*/
private static CodegenConfig forName(String name) {
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
for (CodegenConfig config : loader) {
if (config.getName().equals(name)) {
return config;
}
}
// else try to load directly
try {
return (CodegenConfig) Class.forName(name).newInstance();
} catch (Exception e) {
throw new RuntimeException("Can't load config class with name ".concat(name), e);
}
}
}

View File

@ -1,8 +1,8 @@
package io.swagger.codegen.cmd;
import ch.lambdaj.collection.LambdaIterable;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command;
import io.swagger.codegen.CodegenConfig;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.collection.LambdaCollections.with;

View File

@ -4,10 +4,10 @@ import ch.lambdaj.function.convert.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -81,6 +81,7 @@ public class Meta implements Runnable {
/**
* Converter method to process supporting files: execute with mustache,
* or simply copy to destination directory
*
* @param targetDir - destination directory
* @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj
@ -121,6 +122,7 @@ public class Meta implements Runnable {
/**
* Creates mustache loader for template using classpath loader
*
* @param generator - class with reader getter
* @return loader for template
*/
@ -135,6 +137,7 @@ public class Meta implements Runnable {
/**
* Converts package name to path on file system
*
* @param packageName - package name to convert
* @return relative path
*/

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>

View File

@ -1,6 +1,7 @@
package config;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;

View File

@ -2,6 +2,7 @@ package config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
@ -25,13 +26,11 @@ public class ConfigParser {
if (optionNode.getValue().isValueNode()) {
config.setOption(optionNode.getKey(), optionNode.getValue().asText());
}
else{
} else {
System.out.println("omitting non-value node " + optionNode.getKey());
}
}
}
catch (Exception e) {
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}

View File

@ -1,9 +1,16 @@
package io.swagger.codegen;
import com.samskivert.mustache.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.io.*;
public abstract class AbstractGenerator {
@ -26,12 +33,12 @@ public abstract class AbstractGenerator {
public String readTemplate(String name) {
try {
Reader reader = getTemplateReader(name);
if(reader == null)
if (reader == null) {
throw new RuntimeException("no file found");
}
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
@ -40,21 +47,23 @@ public abstract class AbstractGenerator {
public Reader getTemplateReader(String name) {
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if(is == null)
if (is == null) {
is = new FileInputStream(new File(name));
if(is == null)
throw new RuntimeException("no file found");
return new InputStreamReader(is);
}
catch(Exception e) {
if (is == null) {
throw new RuntimeException("no file found");
}
return new InputStreamReader(is);
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("can't load template " + name);
}
private String getCPResourcePath(String name) {
if (!"/".equals(File.separator))
if (!"/".equals(File.separator)) {
return name.replaceAll(Pattern.quote(File.separator), "/");
}
return name;
}
}

View File

@ -1,29 +1,52 @@
package io.swagger.codegen;
import io.swagger.codegen.ClientOpts;
import io.swagger.annotations.*;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import java.util.*;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class ClientOptInput {
protected CodegenConfig config;
private ClientOpts opts;
private Swagger swagger;
private List<AuthorizationValue> auths;
protected CodegenConfig config;
public ClientOptInput swagger(Swagger swagger) {
this.setSwagger(swagger);
return this;
}
public ClientOptInput opts(ClientOpts opts) {
this.setOpts(opts);
return this;
}
public String getAuth() {
if (auths != null) {
StringBuilder b = new StringBuilder();
for (AuthorizationValue v : auths) {
try {
if (b.toString().length() > 0) {
b.append(",");
}
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
.append(":")
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
} catch (Exception e) {
// continue
e.printStackTrace();
}
}
return b.toString();
} else {
return null;
}
}
public void setAuth(String urlEncodedAuthString) {
List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
@ -37,27 +60,7 @@ public class ClientOptInput {
}
this.auths = auths;
}
public String getAuth() {
if(auths != null) {
StringBuilder b = new StringBuilder();
for(AuthorizationValue v : auths) {
try {
if(b.toString().length() > 0)
b.append(",");
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
.append(":")
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
}
catch (Exception e) {
// continue
e.printStackTrace();
}
}
return b.toString();
}
else
return null;
}
public List<AuthorizationValue> getAuthorizationValues() {
return auths;
}
@ -65,24 +68,25 @@ public class ClientOptInput {
public CodegenConfig getConfig() {
return config;
}
public void setConfig(CodegenConfig config) {
this.config = config;
}
public void setOpts(ClientOpts opts) {
this.opts = opts;
}
public ClientOpts getOpts() {
return opts;
}
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
public void setOpts(ClientOpts opts) {
this.opts = opts;
}
@ApiModelProperty(dataType = "Object")
public Swagger getSwagger() {
return swagger;
}
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
}
}

View File

@ -1,8 +1,9 @@
package io.swagger.codegen;
import io.swagger.codegen.auth.*;
import io.swagger.codegen.auth.AuthMethod;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
public class ClientOpts {
protected String uri;
@ -14,6 +15,7 @@ public class ClientOpts {
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@ -21,6 +23,7 @@ public class ClientOpts {
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
@ -28,6 +31,7 @@ public class ClientOpts {
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
@ -35,6 +39,7 @@ public class ClientOpts {
public String getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}

View File

@ -1,16 +1,19 @@
package io.swagger.codegen;
import io.swagger.codegen.languages.*;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.util.*;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.*;
import java.io.File;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@ -20,24 +23,12 @@ import java.util.*;
public class Codegen extends DefaultGenerator {
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for(CodegenConfig config : extensions) {
if(sb.toString().length() != 0)
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" +
"\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" +
"\n -DdebugModels prints models passed to the template engine" +
"\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
@ -66,16 +57,18 @@ public class Codegen extends DefaultGenerator {
System.out.println(debugInfoOptions);
return;
}
if (cmd.hasOption("a"))
if (cmd.hasOption("a")) {
clientOptInput.setAuth(cmd.getOptionValue("a"));
if (cmd.hasOption("l"))
}
if (cmd.hasOption("l")) {
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
else {
} else {
usage(options);
return;
}
if (cmd.hasOption("o"))
if (cmd.hasOption("o")) {
clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
}
if (cmd.hasOption("h")) {
if (cmd.hasOption("l")) {
config = getConfig(String.valueOf(cmd.getOptionValue("l")));
@ -88,12 +81,13 @@ public class Codegen extends DefaultGenerator {
usage(options);
return;
}
if (cmd.hasOption("i"))
if (cmd.hasOption("i")) {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
if (cmd.hasOption("t"))
}
if (cmd.hasOption("t")) {
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t")));
}
catch (Exception e) {
} catch (Exception e) {
usage(options);
return;
}
@ -102,8 +96,7 @@ public class Codegen extends DefaultGenerator {
.opts(clientOpts)
.swagger(swagger);
new Codegen().opts(clientOptInput).generate();
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -126,18 +119,30 @@ public class Codegen extends DefaultGenerator {
public static CodegenConfig getConfig(String name) {
if (configs.containsKey(name)) {
return configs.get(name);
}
else {
} else {
// see if it's a class
try {
System.out.println("loading class " + name);
Class customClass = Class.forName(name);
System.out.println("loaded");
return (CodegenConfig) customClass.newInstance();
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException("can't load class " + name);
}
}
}
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for (CodegenConfig config : extensions) {
if (sb.toString().length() != 0) {
sb.append(", ");
}
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
}

View File

@ -1,61 +1,102 @@
package io.swagger.codegen;
import io.swagger.models.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.*;
import io.swagger.models.properties.Property;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface CodegenConfig {
CodegenType getTag();
String getName();
String getHelp();
Map<String, Object> additionalProperties();
String apiPackage();
String apiFileFolder();
String fileSuffix();
String outputFolder();
String templateDir();
String modelFileFolder();
String modelPackage();
String toApiName(String name);
String toApiVarName(String name);
String toModelName(String name);
String toParamName(String name);
String escapeText(String text);
String escapeReservedWord(String name);
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);
void processOpts();
List<CliOption> cliOptions();
String generateExamplePath(String path, Operation operation);
Set<String> reservedWords();
List<SupportingFile> supportingFiles();
void setOutputDir(String dir);
String getOutputDir();
void setOutputDir(String dir);
CodegenModel fromModel(String name, Model model);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
Set<String> defaultIncludes();
Map<String, String> typeMapping();
Map<String, String> instantiationTypes();
Map<String, String> importMapping();
Map<String, String> apiTemplateFiles();
Map<String, String> modelTemplateFiles();
void processSwagger(Swagger swagger);
String toApiFilename(String name);
String toModelFilename(String name);
String toModelImport(String name);
String toApiImport(String name);
void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations);
Map<String, Object> postProcessModels(Map<String, Object> objs);
Map<String, Object> postProcessOperations(Map<String, Object> objs);
Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs);
String apiFilename(String templateName, String tag);

View File

@ -1,9 +1,11 @@
package io.swagger.codegen;
import io.swagger.models.*;
import io.swagger.models.properties.*;
import io.swagger.models.ExternalDocs;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CodegenModel {
public String parent;

View File

@ -9,6 +9,7 @@ public final class CodegenModelFactory {
/**
* Configure a different implementation class.
*
* @param type the type that shall be replaced
* @param implementation the implementation class must extend the default class and must provide a public no-arg constructor
*/

View File

@ -1,16 +1,20 @@
package io.swagger.codegen;
import io.swagger.models.*;
import io.swagger.models.ExternalDocs;
import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
hasMore = Boolean.TRUE, isMultipart;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, notes, baseName, defaultResponse;
public List<Map<String, String>> consumes, produces;
public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
@ -22,7 +26,6 @@ public class CodegenOperation {
public List<CodegenSecurity> authMethods;
public List<String> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples;
public ExternalDocs externalDocs;

View File

@ -1,18 +1,27 @@
package io.swagger.codegen;
import java.util.*;
import java.util.List;
import java.util.Map;
public class CodegenProperty {
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
name, min, max, defaultValue, baseType, containerType;
/** maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */
/**
* maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1
*/
public Integer maxLength;
/** minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 */
/**
* minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2
*/
public Integer minLength;
/** pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 */
/**
* pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3
*/
public String pattern;
/** A free-form property to include an example of an instance for this schema. */
/**
* A free-form property to include an example of an instance for this schema.
*/
public String example;
public String jsonSchema;

View File

@ -5,10 +5,10 @@ import java.util.List;
import java.util.Map;
public class CodegenResponse {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message;
public Boolean hasMore;
public List<Map<String, Object>> examples;
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String dataType, baseType, containerType;
public Boolean isDefault;
public Boolean simpleType;
@ -17,5 +17,8 @@ public class CodegenResponse {
public Boolean isListContainer;
public Object schema;
public String jsonSchema;
public boolean isWildcard() { return "0".equals(code) || "default".equals(code); }
public boolean isWildcard() {
return "0".equals(code) || "default".equals(code);
}
}

View File

@ -1,22 +1,16 @@
package io.swagger.codegen;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Map;
import java.util.HashMap;
import java.util.Map;
public enum CodegenType {
CLIENT, SERVER, DOCUMENTATION, OTHER;
private static Map<String, CodegenType> names = new HashMap<String, CodegenType>();
static {
names.put("client", CLIENT);
names.put("server", SERVER);
names.put("documentation", DOCUMENTATION);
names.put("other", OTHER);
}
@JsonCreator
public static CodegenType forValue(String value) {
return names.get(value.toLowerCase());
@ -25,10 +19,18 @@ public enum CodegenType {
@JsonValue
public String toValue() {
for (Map.Entry<String, CodegenType> entry : names.entrySet()) {
if (entry.getValue() == this)
if (entry.getValue() == this) {
return entry.getKey();
}
}
return null; // or fail
}
static {
names.put("client", CLIENT);
names.put("server", SERVER);
names.put("documentation", DOCUMENTATION);
names.put("other", OTHER);
}
}

View File

@ -11,17 +11,14 @@ import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.Reader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@ -267,8 +264,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
try {
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
}
catch (Exception e) {
} catch (Exception e) {
// continue
}
if (in == null) {
@ -276,14 +272,16 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
}
File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false);
if(in != null && out != null)
if (in != null && out != null) {
IOUtils.copy(in, out);
else {
if(in == null)
} else {
if (in == null) {
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input");
if(out == null)
}
if (out == null) {
System.out.println("can't open " + outputFile + " for output");
}
}
files.add(outputFile);
}
@ -306,8 +304,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
count += 1;
if (count < mimeTypeList.size()) {
mediaType.put("hasMore", "true");
}
else {
} else {
mediaType.put("hasMore", null);
}
c.add(mediaType);

View File

@ -1,11 +1,10 @@
package io.swagger.codegen;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.List;
public interface Generator {
Generator opts(ClientOptInput opts);
List<File> generate();
}

View File

@ -1,20 +1,23 @@
package io.swagger.codegen;
import io.swagger.codegen.languages.*;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.util.*;
import io.swagger.parser.SwaggerParser;
import com.samskivert.mustache.*;
import org.apache.commons.cli.*;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.Reader;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@ -24,23 +27,35 @@ import java.util.*;
public class MetaGenerator extends AbstractGenerator {
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString;
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
for(CodegenConfig config : extensions) {
if(sb.toString().length() != 0)
sb.append(", ");
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
}
public static void main(String[] args) {
new MetaGenerator().generate(args);
}
public static List<CodegenConfig> getExtensions() {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator();
while (itr.hasNext()) {
output.add(itr.next());
}
return output;
}
static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MetaGenerator. Generator for creating a new template set " +
"and configuration for Codegen. The output will be based on the language you " +
"specify, and includes default templates to include.", options);
}
public static CodegenConfig getConfig(String name) {
if (configs.containsKey(name)) {
return configs.get(name);
}
return null;
}
protected void generate(String[] args) {
StringBuilder sb = new StringBuilder();
String targetLanguage = null;
@ -67,39 +82,43 @@ public class MetaGenerator extends AbstractGenerator {
usage(options);
return;
}
if (cmd.hasOption("n"))
if (cmd.hasOption("n")) {
name = cmd.getOptionValue("n");
else {
} else {
System.out.println("name is required");
usage(options);
return;
}
if (cmd.hasOption("l"))
if (cmd.hasOption("l")) {
targetLanguage = cmd.getOptionValue("l");
if (cmd.hasOption("p"))
}
if (cmd.hasOption("p")) {
targetPackage = cmd.getOptionValue("p");
if (cmd.hasOption("o"))
}
if (cmd.hasOption("o")) {
outputFolder = cmd.getOptionValue("o");
else {
} else {
System.out.println("output folder is required");
usage(options);
return;
}
}
catch (Exception e) {
} catch (Exception e) {
usage(options);
return;
}
System.out.println("writing to folder " + outputFolder);
File outputFolderLocation = new File(outputFolder);
if(!outputFolderLocation.exists())
if (!outputFolderLocation.exists()) {
outputFolderLocation.mkdirs();
}
File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar));
if(!sourceFolder.exists())
if (!sourceFolder.exists()) {
sourceFolder.mkdirs();
}
File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services");
if(!resourcesFolder.exists())
if (!resourcesFolder.exists()) {
resourcesFolder.mkdirs();
}
String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator";
@ -125,11 +144,13 @@ public class MetaGenerator extends AbstractGenerator {
for (SupportingFile support : supportingFiles) {
try {
String destinationFolder = outputFolder;
if(support.folder != null && !"".equals(support.folder))
if (support.folder != null && !"".equals(support.folder)) {
destinationFolder += File.separator + support.folder;
}
File of = new File(destinationFolder);
if(!of.isDirectory())
if (!of.isDirectory()) {
of.mkdirs();
}
String outputFilename = destinationFolder + File.separator + support.destinationFilename;
if (support.templateFile.endsWith("mustache")) {
@ -138,48 +159,38 @@ public class MetaGenerator extends AbstractGenerator {
.withLoader(new Mustache.TemplateLoader() {
public Reader getTemplate(String name) {
return getTemplateReader(templateDir + File.separator + name + ".mustache");
};
}
;
})
.defaultValue("")
.compile(template);
writeToFile(outputFilename, tmpl.execute(data));
files.add(new File(outputFilename));
}
else {
} else {
String template = readTemplate(templateDir + File.separator + support.templateFile);
FileUtils.writeStringToFile(new File(outputFilename), template);
System.out.println("copying file to " + outputFilename);
files.add(new File(outputFilename));
}
}
catch (java.io.IOException e) {
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
public static List<CodegenConfig> getExtensions() {
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
Iterator<CodegenConfig> itr = loader.iterator();
while(itr.hasNext()) {
output.add(itr.next());
}
return output;
}
static {
List<CodegenConfig> extensions = getExtensions();
StringBuilder sb = new StringBuilder();
static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "MetaGenerator. Generator for creating a new template set " +
"and configuration for Codegen. The output will be based on the language you " +
"specify, and includes default templates to include.", options );
for (CodegenConfig config : extensions) {
if (sb.toString().length() != 0) {
sb.append(", ");
}
sb.append(config.getName());
configs.put(config.getName(), config);
configString = sb.toString();
}
public static CodegenConfig getConfig(String name) {
if(configs.containsKey(name)) {
return configs.get(name);
}
return null;
}
}

View File

@ -2,5 +2,6 @@ package io.swagger.codegen.auth;
public interface AuthMethod {
String getType();
void setType(String type);
}

View File

@ -1,14 +1,5 @@
package io.swagger.codegen.examples;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
@ -29,6 +20,15 @@ import io.swagger.models.properties.StringProperty;
import io.swagger.models.properties.UUIDProperty;
import io.swagger.util.Json;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ExampleGenerator {
protected Map<String, Model> examples;
@ -54,8 +54,7 @@ public class ExampleGenerator {
kv.put("example", example);
output.add(kv);
}
}
else if(property != null && mediaType.startsWith("application/xml")) {
} else if (property != null && mediaType.startsWith("application/xml")) {
String example = new XmlExampleGenerator(this.examples).toXml(property);
if (example != null) {
kv.put("example", example);
@ -63,8 +62,7 @@ public class ExampleGenerator {
}
}
}
}
else {
} else {
for (Map.Entry<String, Object> entry : examples.entrySet()) {
final Map<String, String> kv = new HashMap<String, String>();
kv.put("contentType", entry.getKey());
@ -83,14 +81,11 @@ public class ExampleGenerator {
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
if (property.getExample() != null) {
return property.getExample();
}
else if(property instanceof StringProperty) {
} else if (property instanceof StringProperty) {
return "aeiou";
}
else if(property instanceof BooleanProperty) {
} else if (property instanceof BooleanProperty) {
return Boolean.TRUE;
}
else if(property instanceof ArrayProperty) {
} else if (property instanceof ArrayProperty) {
Property innerType = ((ArrayProperty) property).getItems();
if (innerType != null) {
Object[] output = new Object[]{
@ -98,53 +93,41 @@ public class ExampleGenerator {
};
return output;
}
}
else if(property instanceof DateProperty) {
} else if (property instanceof DateProperty) {
return new java.util.Date(System.currentTimeMillis());
}
else if(property instanceof DateTimeProperty) {
} else if (property instanceof DateTimeProperty) {
return new java.util.Date(System.currentTimeMillis());
}
else if(property instanceof DecimalProperty) {
} else if (property instanceof DecimalProperty) {
return new BigDecimal(1.3579);
}
else if(property instanceof DoubleProperty) {
} else if (property instanceof DoubleProperty) {
return new Double(3.149);
}
else if(property instanceof FileProperty) {
} else if (property instanceof FileProperty) {
return ""; // TODO
}
else if(property instanceof FloatProperty) {
} else if (property instanceof FloatProperty) {
return new Float(1.23);
}
else if(property instanceof IntegerProperty) {
} else if (property instanceof IntegerProperty) {
return new Integer(123);
}
else if(property instanceof LongProperty) {
} else if (property instanceof LongProperty) {
return new Long(123456789);
}
else if(property instanceof MapProperty) {
} else if (property instanceof MapProperty) {
Map<String, Object> mp = new HashMap<String, Object>();
if (property.getName() != null) {
mp.put(property.getName(),
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
}
else {
} else {
mp.put("key",
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
}
return mp;
}
else if(property instanceof ObjectProperty) {
} else if (property instanceof ObjectProperty) {
return "{}";
}
else if(property instanceof RefProperty) {
} else if (property instanceof RefProperty) {
String simpleName = ((RefProperty) property).getSimpleRef();
Model model = examples.get(simpleName);
if(model != null)
if (model != null) {
return resolveModelToExample(simpleName, mediaType, model, processedModels);
}
else if(property instanceof UUIDProperty) {
} else if (property instanceof UUIDProperty) {
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
}

View File

@ -1,30 +1,47 @@
package io.swagger.codegen.examples;
import io.swagger.util.Json;
import io.swagger.models.*;
import io.swagger.models.properties.*;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.RefModel;
import io.swagger.models.Xml;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import org.codehaus.plexus.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.*;
import org.codehaus.plexus.util.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class XmlExampleGenerator {
public static String NEWLINE = "\n";
public static String TAG_START = "<";
public static String CLOSE_TAG = ">";
public static String TAG_END = "</";
private static String EMPTY = "";
protected Map<String, Model> examples;
protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private static String EMPTY = "";
public XmlExampleGenerator(Map<String, Model> examples) {
this.examples = examples;
if(examples == null)
if (examples == null) {
examples = new HashMap<String, Model>();
}
}
public String toXml(Property property) {
return toXml(null, property, 0, Collections.<String>emptySet());
@ -34,10 +51,10 @@ public class XmlExampleGenerator {
if (model instanceof RefModel) {
RefModel ref = (RefModel) model;
Model actualModel = examples.get(ref.getSimpleRef());
if(actualModel instanceof ModelImpl)
if (actualModel instanceof ModelImpl) {
return modelImplToXml((ModelImpl) actualModel, indent, path);
}
else if(model instanceof ModelImpl) {
} else if (model instanceof ModelImpl) {
return modelImplToXml((ModelImpl) model, indent, path);
}
return null;
@ -63,16 +80,18 @@ public class XmlExampleGenerator {
Xml xml = model.getXml();
if (xml != null) {
if(xml.getName() != null)
if (xml.getName() != null) {
name = xml.getName();
}
}
for (String pName : model.getProperties().keySet()) {
Property p = model.getProperties().get(pName);
if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute())
if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) {
attributes.put(pName, p);
else
} else {
elements.put(pName, p);
}
}
sb.append(indent(indent)).append(TAG_START);
sb.append(name);
for (String pName : attributes.keySet()) {
@ -109,8 +128,9 @@ public class XmlExampleGenerator {
ArrayProperty p = (ArrayProperty) property;
Property inner = p.getItems();
boolean wrapped = false;
if(property.getXml() != null && property.getXml().getWrapped())
if (property.getXml() != null && property.getXml().getWrapped()) {
wrapped = true;
}
if (wrapped) {
String prefix = EMPTY;
if (name != null) {
@ -127,64 +147,64 @@ public class XmlExampleGenerator {
sb.append(indent(indent));
sb.append(closeTag(name));
}
}
else
} else {
sb.append(toXml(name, inner, indent, path));
}
else if(property instanceof RefProperty) {
} else if (property instanceof RefProperty) {
RefProperty ref = (RefProperty) property;
Model actualModel = examples.get(ref.getSimpleRef());
sb.append(toXml(actualModel, indent, path));
}
else {
} else {
if (name != null) {
sb.append(indent(indent));
sb.append(openTag(name));
}
sb.append(getExample(property));
if(name != null)
if (name != null) {
sb.append(closeTag(name));
}
}
return sb.toString();
}
protected String getExample(Property property) {
if (property instanceof DateTimeProperty) {
if(property.getExample() != null)
if (property.getExample() != null) {
return property.getExample();
else
} else {
return dtFormat.format(new Date());
}
else if(property instanceof StringProperty) {
if(property.getExample() != null)
} else if (property instanceof StringProperty) {
if (property.getExample() != null) {
return property.getExample();
else
} else {
return "string";
}
else if(property instanceof DateProperty) {
if(property.getExample() != null)
} else if (property instanceof DateProperty) {
if (property.getExample() != null) {
return property.getExample();
else
} else {
return dateFormat.format(new Date());
}
else if(property instanceof IntegerProperty) {
if(property.getExample() != null)
} else if (property instanceof IntegerProperty) {
if (property.getExample() != null) {
return property.getExample();
else
} else {
return "0";
}
else if(property instanceof BooleanProperty) {
if(property.getExample() != null)
} else if (property instanceof BooleanProperty) {
if (property.getExample() != null) {
return property.getExample();
else
} else {
return "true";
}
else if(property instanceof LongProperty) {
if(property.getExample() != null)
} else if (property instanceof LongProperty) {
if (property.getExample() != null) {
return property.getExample();
else
} else {
return "123456";
}
}
return "not implemented " + property;
}

View File

@ -3,9 +3,26 @@ package io.swagger.codegen.languages;
import com.google.common.base.CaseFormat;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenResponse;
import io.swagger.codegen.CodegenSecurity;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.models.properties.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -14,13 +31,16 @@ import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
protected String mainPackage = "io.swagger.client";
protected String invokerPackage = mainPackage + ".core";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-client";
@ -30,7 +50,6 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
protected String configKey = "apiRequest";
protected int defaultTimeoutInMs = 5000;
protected String configKeyPath = mainPackage;
protected boolean registerNonStandardStatusCodes = true;
protected boolean renderJavadoc = true;
protected boolean removeOAuthSecurities = true;
@ -41,18 +60,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
* unmarshalling problems and any other RuntimeException will be considered as ApiErrors.
*/
protected boolean onlyOneSuccess = true;
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "akka-scala";
}
public String getHelp() {
return "Generates a Scala client library base on Akka/Spray.";
}
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
public AkkaScalaClientCodegen() {
super();
@ -79,8 +87,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
additionalProperties.put("configKey", configKey);
additionalProperties.put("configKeyPath", configKeyPath);
additionalProperties.put("defaultTimeout", defaultTimeoutInMs);
if (renderJavadoc)
if (renderJavadoc) {
additionalProperties.put("javadocRenderer", new JavadocLambda());
}
additionalProperties.put("fnCapitalize", new CapitalizeLambda());
additionalProperties.put("fnCamelize", new CamelizeLambda(false));
additionalProperties.put("fnEnumEntry", new EnumEntryLambda());
@ -139,6 +148,18 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
instantiationTypes.put("map", "Map");
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "akka-scala";
}
public String getHelp() {
return "Generates a Scala client library base on Akka/Spray.";
}
@Override
public String escapeReservedWord(String name) {
return "`" + name + "`";
@ -162,8 +183,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
HashSet<Integer> unknownCodes = new HashSet<Integer>();
for (CodegenOperation operation : opsMap.get("operation")) {
for (CodegenResponse response : operation.responses) {
if ("default".equals(response.code))
if ("default".equals(response.code)) {
continue;
}
try {
int code = Integer.parseInt(response.code);
if (code >= 600) {
@ -202,16 +224,18 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
if (!removeOAuthSecurities)
if (!removeOAuthSecurities) {
return codegenSecurities;
}
// Remove OAuth securities
Iterator<CodegenSecurity> it = codegenSecurities.iterator();
while (it.hasNext()) {
final CodegenSecurity security = it.next();
if (security.isOAuth)
if (security.isOAuth) {
it.remove();
}
}
// Adapt 'hasMore'
it = codegenSecurities.iterator();
while (it.hasNext()) {
@ -219,8 +243,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
security.hasMore = it.hasNext();
}
if (codegenSecurities.isEmpty())
if (codegenSecurities.isEmpty()) {
return null;
}
return codegenSecurities;
}
@ -231,15 +256,19 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
private String formatIdentifier(String name, boolean capitalized) {
String identifier = camelize(name, true);
if (capitalized)
if (capitalized) {
identifier = StringUtils.capitalize(identifier);
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier))
}
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) {
return identifier;
}
return escapeReservedWord(identifier);
}
@Override
public String toParamName(String name) { return formatIdentifier(name, false); }
public String toParamName(String name) {
return formatIdentifier(name, false);
}
@Override
public String toVarName(String name) {
@ -247,8 +276,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
}
@Override
public String toEnumName(CodegenProperty property)
{
public String toEnumName(CodegenProperty property) {
return formatIdentifier(property.baseName, true);
}
@ -258,10 +286,12 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
String type;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
} else
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -275,30 +305,32 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
} else
} else {
return null;
}
}
public String toDefaultValue(Property p) {
if (!p.getRequired())
if (!p.getRequired()) {
return "None";
if (p instanceof StringProperty)
}
if (p instanceof StringProperty) {
return "null";
else if (p instanceof BooleanProperty)
} else if (p instanceof BooleanProperty) {
return "null";
else if (p instanceof DateProperty)
} else if (p instanceof DateProperty) {
return "null";
else if (p instanceof DateTimeProperty)
} else if (p instanceof DateTimeProperty) {
return "null";
else if (p instanceof DoubleProperty)
} else if (p instanceof DoubleProperty) {
return "null";
else if (p instanceof FloatProperty)
} else if (p instanceof FloatProperty) {
return "null";
else if (p instanceof IntegerProperty)
} else if (p instanceof IntegerProperty) {
return "null";
else if (p instanceof LongProperty)
} else if (p instanceof LongProperty) {
return "null";
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "Map[String, " + inner + "].empty ";
@ -306,9 +338,10 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "Seq[" + inner + "].empty ";
} else
} else {
return "null";
}
}
private static abstract class CustomLambda implements Mustache.Lambda {
@Override
@ -317,6 +350,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
frag.execute(tempWriter);
out.write(formatFragment(tempWriter.toString()));
}
public abstract String formatFragment(String fragment);
}

View File

@ -1,10 +1,17 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -15,18 +22,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
protected String sourceFolder = projectFolder + "/java";
protected Boolean useAndroidMavenGradlePlugin = true;
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "android";
}
public String getHelp() {
return "Generates an Android client library.";
}
public AndroidClientCodegen() {
super();
outputFolder = "generated-code/android";
@ -69,6 +64,18 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true."));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "android";
}
public String getHelp() {
return "Generates an Android client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -89,8 +96,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -105,11 +111,12 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -119,16 +126,18 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -142,8 +151,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -159,8 +169,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}
@ -171,32 +182,28 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
if (additionalProperties.containsKey("invokerPackage")) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
}
else{
} else {
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
}
if (additionalProperties.containsKey("groupId")) {
this.setGroupId((String) additionalProperties.get("groupId"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
}
if (additionalProperties.containsKey("artifactId")) {
this.setArtifactId((String) additionalProperties.get("artifactId"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
}
if (additionalProperties.containsKey("artifactVersion")) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
}
@ -207,8 +214,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) {
this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin"));
}
else{
} else {
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin);
}

View File

@ -1,10 +1,25 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -17,18 +32,6 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
protected boolean authPreemptive = false;
protected boolean asyncHttpClient = !authScheme.isEmpty();
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "async-scala";
}
public String getHelp() {
return "Generates an Asynchronous Scala client library.";
}
public AsyncScalaClientCodegen() {
super();
outputFolder = "generated-code/async-scala";
@ -101,6 +104,18 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
instantiationTypes.put("map", "HashMap");
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "async-scala";
}
public String getHelp() {
return "Generates an Asynchronous Scala client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -121,8 +136,7 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -137,11 +151,12 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -151,44 +166,42 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
}
else
} else {
return null;
}
}
public String toDefaultValue(Property p) {
if(p instanceof StringProperty)
if (p instanceof StringProperty) {
return "null";
else if (p instanceof BooleanProperty)
} else if (p instanceof BooleanProperty) {
return "null";
else if(p instanceof DateProperty)
} else if (p instanceof DateProperty) {
return "null";
else if(p instanceof DateTimeProperty)
} else if (p instanceof DateTimeProperty) {
return "null";
else if (p instanceof DoubleProperty)
} else if (p instanceof DoubleProperty) {
return "null";
else if (p instanceof FloatProperty)
} else if (p instanceof FloatProperty) {
return "null";
else if (p instanceof IntegerProperty)
} else if (p instanceof IntegerProperty) {
return "null";
else if (p instanceof LongProperty)
} else if (p instanceof LongProperty) {
return "null";
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() ";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
}
else
} else {
return "null";
}
}
}

View File

@ -1,10 +1,17 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "IO.Swagger.Client";
@ -13,18 +20,6 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/csharp";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "csharp";
}
public String getHelp() {
return "Generates a CSharp client library.";
}
public CSharpClientCodegen() {
super();
outputFolder = "generated-code/csharp";
@ -92,6 +87,18 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "csharp";
}
public String getHelp() {
return "Generates a CSharp client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -112,16 +119,18 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
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(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -135,8 +144,9 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -156,8 +166,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -172,19 +181,21 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
String type = null;
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType.toLowerCase());
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return type;
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId);
}

View File

@ -1,10 +1,17 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -13,18 +20,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "java";
}
public String getHelp() {
return "Generates a Java client library.";
}
public JavaClientCodegen() {
super();
outputFolder = "generated-code/java";
@ -66,38 +61,46 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "java";
}
public String getHelp() {
return "Generates a Java client library.";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey("invokerPackage")) {
this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
}
else{
} else {
//not set, use default to be passed to template
additionalProperties.put("invokerPackage", invokerPackage);
}
if (additionalProperties.containsKey("groupId")) {
this.setGroupId((String) additionalProperties.get("groupId"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("groupId", groupId);
}
if (additionalProperties.containsKey("artifactId")) {
this.setArtifactId((String) additionalProperties.get("artifactId"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("artifactId", artifactId);
}
if (additionalProperties.containsKey("artifactVersion")) {
this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
}
else{
} else {
//not set, use to be passed to template
additionalProperties.put("artifactVersion", artifactVersion);
}
@ -122,7 +125,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -143,16 +145,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -166,8 +170,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -186,8 +191,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -202,19 +206,21 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}

View File

@ -1,11 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api";
@ -14,18 +23,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
protected String artifactVersion = "1.0.0";
protected String title = "Swagger Server";
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "jaxrs";
}
public String getHelp() {
return "Generates a Java JAXRS Server application.";
}
public JaxRSServerCodegen() {
super.processOpts();
@ -60,6 +57,17 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
);
}
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "jaxrs";
}
public String getHelp() {
return "Generates a Java JAXRS Server application.";
}
@Override
public void processOpts() {
@ -87,8 +95,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -100,17 +107,20 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if(basePath.startsWith("/"))
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if(pos > 0)
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if(basePath == "")
if (basePath == "") {
basePath = "default";
else {
if(co.path.startsWith("/" + basePath))
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
@ -127,25 +137,23 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if(operation.returnType == null)
if (operation.returnType == null) {
operation.returnType = "Void";
else if(operation.returnType.startsWith("List")) {
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end);
operation.returnContainer = "List";
}
}
else if(operation.returnType.startsWith("Map")) {
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end);
operation.returnContainer = "Map";
}
}
else if(operation.returnType.startsWith("Set")) {
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
@ -171,8 +179,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
if (output != null) {
result = result.replace(apiFileFolder(), implFileFolder(output));
}
}
else if( templateName.endsWith( "Factory.mustache")){
} else if (templateName.endsWith("Factory.mustache")) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java";
@ -180,8 +187,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
if (output != null) {
result = result.replace(apiFileFolder(), implFileFolder(output));
}
}
else if( templateName.endsWith( "Service.mustache")) {
} else if (templateName.endsWith("Service.mustache")) {
int ix = result.lastIndexOf('.');
result = result.substring(0, ix) + "Service.java";
}

View File

@ -1,12 +1,5 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
@ -15,46 +8,18 @@ import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
public String apiPackage() {
return "controllers";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "nodejs";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a nodejs server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
public NodeJSServerCodegen() {
super();
@ -131,10 +96,46 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
}
}
public String apiPackage() {
return "controllers";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "nodejs";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a nodejs server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultController";
}
return initialCaps(name);
}
@ -142,6 +143,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
@ -171,15 +173,17 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
for (CodegenOperation operation : operations) {
operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams;
if(params != null && params.size() == 0)
if (params != null && params.size() == 0) {
operation.allParams = null;
}
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if("0".equals(resp.code))
if ("0".equals(resp.code)) {
resp.code = "default";
}
}
}
if (operation.examples != null && !operation.examples.isEmpty()) {
// Leave application/json* items only
for (Iterator<Map<String, String>> it = operation.examples.iterator(); it.hasNext(); ) {

View File

@ -1,10 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected Set<String> foundationClasses = new HashSet<String>();
@ -12,18 +22,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String classPrefix = "SWG";
protected String projectName = "swaggerClient";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "objc";
}
public String getHelp() {
return "Generates an Objective-C client library.";
}
public ObjcClientCodegen() {
super();
outputFolder = "generated-code" + File.separator + "objc";
@ -111,6 +109,18 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "objc";
}
public String getHelp() {
return "Generates an Objective-C client library.";
}
@Override
public void processOpts() {
super.processOpts();
@ -125,8 +135,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (additionalProperties.containsKey("projectName")) {
this.setProjectName((String) additionalProperties.get("projectName"));
}
else{
} else {
additionalProperties.put("projectName", projectName);
}
@ -151,23 +160,23 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map");
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array");
}
else
} else {
return null;
}
}
@Override
public String getTypeDeclaration(String name) {
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name))
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
return name;
else
} else {
return name + "*";
}
}
@Override
public String getSwaggerType(Property p) {
@ -175,11 +184,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type))
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -192,19 +202,20 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
// In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*'
if (languageSpecificPrimitives.contains(innerType))
if (languageSpecificPrimitives.contains(innerType)) {
return getSwaggerType(p) + "*";
}
// In this codition, type of property p is array of model,
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*"))
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
}
else {
} else {
String swaggerType = getSwaggerType(p);
// In this codition, type of p is objective-c primitive type, e.g. `NSSNumber',
@ -255,19 +266,19 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
super.setNonArrayMapProperty(property, type);
if ("NSDictionary".equals(type)) {
property.setter = "initWithDictionary";
}
else {
} else {
property.setter = "initWithValues";
}
}
@Override
public String toModelImport(String name) {
if("".equals(modelPackage()))
if ("".equals(modelPackage())) {
return name;
else
} else {
return modelPackage() + "." + name;
}
}
@Override
public String toDefaultValue(Property p) {
@ -300,16 +311,18 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
name = name.replaceAll("[^a-zA-Z0-9_]", "_");
// if it's all upper case, do noting
if (name.matches("^[A-Z_]$"))
if (name.matches("^[A-Z_]$")) {
return name;
}
// camelize (lower first character) the variable name
// e.g. `pet_id` to `petId`
name = camelize(name, true);
// for reserved word or word starting with number, prepend `_`
if (reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -327,8 +340,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}

View File

@ -1,11 +1,16 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.Json;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "SwaggerClient";
@ -13,18 +18,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "perl";
}
public String getHelp() {
return "Generates a Perl client library.";
}
public PerlClientCodegen() {
super();
modelPackage = File.separatorChar + "Object";
@ -83,6 +76,18 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "perl";
}
public String getHelp() {
return "Generates a Perl client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -103,8 +108,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
@ -121,11 +125,12 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
if (languageSpecificPrimitives.contains(type)) {
return type;
}
}
else
} else {
type = swaggerType;
if(type == null)
}
if (type == null) {
return null;
}
return type;
}
@ -156,8 +161,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
escapeReservedWord(name); // e.g. return => _return
}
// camelize the model name
// phone_number => PhoneNumber
@ -181,8 +187,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@ -190,8 +197,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}

View File

@ -1,11 +1,17 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.Json;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -13,18 +19,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "php";
}
public String getHelp() {
return "Generates a PHP client library.";
}
public PhpClientCodegen() {
super();
@ -91,6 +85,18 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "php";
}
public String getHelp() {
return "Generates a PHP client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -111,8 +117,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
@ -128,15 +133,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return type;
}
else if (instantiationTypes.containsKey(type)) {
} else if (instantiationTypes.containsKey(type)) {
return type;
}
}
else
} else {
type = swaggerType;
if(type == null)
}
if (type == null) {
return null;
}
return toModelName(type);
}
@ -167,8 +172,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
escapeReservedWord(name); // e.g. return => _return
}
// camelize the model name
// phone_number => PhoneNumber

View File

@ -1,26 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig {
String module = "client";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "python3";
}
public String getHelp() {
return "Generates a Python3 client library.";
}
public Python3ClientCodegen() {
super();
outputFolder = "generated-code/python3";
@ -64,6 +58,18 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "python3";
}
public String getHelp() {
return "Generates a Python3 client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -84,8 +90,7 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -103,9 +108,9 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
if (languageSpecificPrimitives.contains(type)) {
return type;
}
}
else
} else {
type = swaggerType;
}
return type;
}
@ -120,16 +125,18 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// camelize (lower first character) the variable name
// petId => pet_id
name = underscore(name);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -143,8 +150,9 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -154,8 +162,9 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name
// PhoneNumber.rb => phone_number.rb
@ -173,24 +182,27 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@Override
public String toApiVarName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "default_api";
}
return underscore(name) + "_api";
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}

View File

@ -1,28 +1,22 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String module = "SwaggerPetstore";
protected String invokerPackage;
protected String eggPackage;
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "python";
}
public String getHelp() {
return "Generates a Python client library.";
}
public PythonClientCodegen() {
super();
@ -77,6 +71,22 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
}
private static String dropDots(String str) {
return str.replaceAll("\\.", "_");
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "python";
}
public String getHelp() {
return "Generates a Python client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -97,8 +107,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -133,22 +142,20 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// underscore the variable name
// petId => pet_id
name = underscore(dropDots(name));
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
return name;
}
private static String dropDots(String str) {
return str.replaceAll("\\.", "_");
return name;
}
@Override
@ -160,8 +167,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -171,8 +179,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name
// PhoneNumber => phone_number
@ -190,24 +199,27 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@Override
public String toApiVarName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "default_api";
}
return underscore(name) + "_api";
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}

View File

@ -1,52 +1,39 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.Json;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
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.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
protected final String PREFIX = "SWG";
protected Set<String> foundationClasses = new HashSet<String>();
// source folder where to write the files
protected String sourceFolder = "client";
protected String apiVersion = "1.0.0";
protected final String PREFIX = "SWG";
protected Map<String, String> namespaces = new HashMap<String, String>();
protected Set<String> systemIncludes = new HashSet<String>();
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "qt5cpp";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a qt5 C++ client library.";
}
public Qt5CPPGenerator() {
super();
@ -145,12 +132,41 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
systemIncludes.add("QList");
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "qt5cpp";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a qt5 C++ client library.";
}
@Override
public String toModelImport(String name) {
if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";";
}
else if(systemIncludes.contains(name)) {
} else if (systemIncludes.contains(name)) {
return "#include <" + name + ">";
}
return "#include \"" + name + ".h\"";
@ -208,46 +224,45 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
}
if(foundationClasses.contains(swaggerType))
if (foundationClasses.contains(swaggerType)) {
return swaggerType + "*";
else if(languageSpecificPrimitives.contains(swaggerType))
} else if (languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
else
} else {
return swaggerType + "*";
}
}
@Override
public String toDefaultValue(Property p) {
if(p instanceof StringProperty)
if (p instanceof StringProperty) {
return "new QString(\"\")";
else if (p instanceof BooleanProperty)
} else if (p instanceof BooleanProperty) {
return "false";
else if(p instanceof DateProperty)
} else if (p instanceof DateProperty) {
return "NULL";
else if(p instanceof DateTimeProperty)
} else if (p instanceof DateTimeProperty) {
return "NULL";
else if (p instanceof DoubleProperty)
} else if (p instanceof DoubleProperty) {
return "0.0";
else if (p instanceof FloatProperty)
} else if (p instanceof FloatProperty) {
return "0.0f";
else if (p instanceof IntegerProperty)
} else if (p instanceof IntegerProperty) {
return "0";
else if (p instanceof LongProperty)
} else if (p instanceof LongProperty) {
return "0L";
else if (p instanceof DecimalProperty)
} else if (p instanceof DecimalProperty) {
return "0.0";
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new QMap<QString, " + inner + ">()";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
@ -277,13 +292,15 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
if(foundationClasses.contains(type))
}
if (foundationClasses.contains(type)) {
return type;
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -295,8 +312,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return type;
}
else {
} else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}

View File

@ -1,11 +1,19 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -14,18 +22,6 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "retrofit";
}
public String getHelp() {
return "Generates a Retrofit client library.";
}
public RetrofitClientCodegen() {
super();
outputFolder = "generated-code/java";
@ -70,6 +66,18 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
instantiationTypes.put("map", "HashMap");
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "retrofit";
}
public String getHelp() {
return "Generates a Retrofit client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -90,16 +98,18 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -113,8 +123,9 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -134,8 +145,7 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -150,19 +160,21 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}

View File

@ -1,36 +1,22 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.Json;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String gemName = "swagger_client";
protected String moduleName = null;
protected String libFolder = "lib";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "ruby";
}
public String getHelp() {
return "Generates a Ruby client library.";
}
/**
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
*/
public String generateModuleName() {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
public RubyClientCodegen() {
super();
moduleName = generateModuleName();
@ -83,6 +69,25 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "ruby";
}
public String getHelp() {
return "Generates a Ruby client library.";
}
/**
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
*/
public String generateModuleName() {
return camelize(gemName.replaceAll("[^\\w]+", "_"));
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -103,8 +108,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
@ -121,11 +125,12 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
if (languageSpecificPrimitives.contains(type)) {
return type;
}
}
else
} else {
type = swaggerType;
if(type == null)
}
if (type == null) {
return null;
}
return type;
}
@ -139,16 +144,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
name = name.replaceAll("-", "_");
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$"))
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase();
}
// camelize (lower first character) the variable name
// petId => pet_id
name = underscore(name);
// for reserved word or word starting with number, append _
if(reservedWords.contains(name) || name.matches("^\\d.*"))
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@ -162,8 +169,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
@ -173,8 +181,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toModelFilename(String name) {
// model name cannot use reserved keyword, e.g. return
if(reservedWords.contains(name))
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// underscore the model file name
// PhoneNumber.rb => phone_number.rb
@ -192,8 +201,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultApi";
}
// e.g. phone_number_api => PhoneNumberApi
return camelize(name) + "Api";
}
@ -201,8 +211,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return underscore(operationId);
}

View File

@ -1,10 +1,25 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -16,18 +31,6 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
protected boolean authPreemptive = false;
protected boolean asyncHttpClient = !authScheme.isEmpty();
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "scala";
}
public String getHelp() {
return "Generates a Scala client library.";
}
public ScalaClientCodegen() {
super();
outputFolder = "generated-code/scala";
@ -99,6 +102,18 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
instantiationTypes.put("map", "HashMap");
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "scala";
}
public String getHelp() {
return "Generates a Scala client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -119,8 +134,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -135,11 +149,12 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -149,53 +164,52 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map") + "[String, " + inner + "]";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array") + "[" + inner + "]";
}
else
} else {
return null;
}
}
public String toDefaultValue(Property p) {
if(p instanceof StringProperty)
if (p instanceof StringProperty) {
return "null";
else if (p instanceof BooleanProperty)
} else if (p instanceof BooleanProperty) {
return "null";
else if(p instanceof DateProperty)
} else if (p instanceof DateProperty) {
return "null";
else if(p instanceof DateTimeProperty)
} else if (p instanceof DateTimeProperty) {
return "null";
else if (p instanceof DoubleProperty)
} else if (p instanceof DoubleProperty) {
return "null";
else if (p instanceof FloatProperty)
} else if (p instanceof FloatProperty) {
return "null";
else if (p instanceof IntegerProperty)
} else if (p instanceof IntegerProperty) {
return "null";
else if (p instanceof LongProperty)
} else if (p instanceof LongProperty) {
return "null";
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap[String, " + inner + "]() ";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ListBuffer[" + inner + "]() ";
}
else
} else {
return "null";
}
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}

View File

@ -1,11 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
@ -14,18 +23,6 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "scalatra";
}
public String getHelp() {
return "Generates a Scala server application with Scalatra.";
}
public ScalatraServerCodegen() {
super();
outputFolder = "generated-code/scalatra";
@ -121,6 +118,18 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
importMapping.put("LocalTime", "org.joda.time.LocalTime");
}
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "scalatra";
}
public String getHelp() {
return "Generates a Scala server application with Scalatra.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
@ -152,8 +161,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -168,11 +176,12 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
}

View File

@ -1,13 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.util.Json;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api";
@ -19,18 +26,6 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
protected String configPackage = "";
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "spring-mvc";
}
public String getHelp() {
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
}
public SpringMVCServerCodegen() {
super.processOpts();
outputFolder = "generated-code/javaSpringMVC";
@ -62,6 +57,18 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
);
}
public CodegenType getTag() {
return CodegenType.SERVER;
}
public String getName() {
return "spring-mvc";
}
public String getHelp() {
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
}
@Override
public void processOpts() {
super.processOpts();
@ -97,8 +104,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
@ -110,17 +116,20 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if(basePath.startsWith("/"))
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if(pos > 0)
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if(basePath == "")
if (basePath == "") {
basePath = "default";
else {
if(co.path.startsWith("/" + basePath))
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
@ -137,25 +146,23 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if(operation.returnType == null)
if (operation.returnType == null) {
operation.returnType = "Void";
else if(operation.returnType.startsWith("List")) {
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end);
operation.returnContainer = "List";
}
}
else if(operation.returnType.startsWith("Map")) {
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end);
operation.returnContainer = "Map";
}
}
else if(operation.returnType.startsWith("Set")) {
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {

View File

@ -1,9 +1,10 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import java.util.*;
import java.io.File;
public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
@ -13,18 +14,6 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "docs";
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "dynamic-html";
}
public String getHelp() {
return "Generates a dynamic HTML site.";
}
public StaticDocCodegen() {
super();
outputFolder = "docs";
@ -60,6 +49,18 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("map", "HashMap");
}
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "dynamic-html";
}
public String getHelp() {
return "Generates a dynamic HTML site.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;

View File

@ -1,12 +1,20 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Operation;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
private static final String ALL_OPERATIONS = "";
@ -16,18 +24,6 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "html";
}
public String getHelp() {
return "Generates a static HTML file.";
}
public StaticHtmlGenerator() {
super();
outputFolder = "docs";
@ -53,14 +49,25 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
importMapping = new HashMap<String, String>();
}
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "html";
}
public String getHelp() {
return "Generates a static HTML file.";
}
@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) {
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();

View File

@ -1,14 +1,24 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger;
import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
public SwaggerGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
@ -21,14 +31,6 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
return "Creates a static swagger.json file.";
}
public SwaggerGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
@Override
public void processSwagger(Swagger swagger) {
String swaggerString = Json.pretty(swagger);
@ -37,8 +39,7 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
String outputFile = outputFolder + File.separator + "swagger.json";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
}
catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}

View File

@ -1,14 +1,24 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.util.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig {
public SwaggerYamlGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
@ -21,14 +31,6 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
return "Creates a static swagger.yaml file.";
}
public SwaggerYamlGenerator() {
super();
templateDir = "swagger";
outputFolder = "generated-code/swagger";
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
}
@Override
public void processSwagger(Swagger swagger) {
try {
@ -36,8 +38,7 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
String outputFile = outputFolder + File.separator + "swagger.yaml";
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
System.out.println("wrote file to " + outputFile);
}
catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}

View File

@ -3,17 +3,29 @@ package io.swagger.codegen.languages;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import io.swagger.codegen.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Nullable;
import java.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -21,18 +33,6 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
protected String sourceFolder = "Classes/Swaggers";
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "swift";
}
public String getHelp() {
return "Generates a swift client library.";
}
public SwiftGenerator() {
super();
outputFolder = "generated-code/swift";
@ -119,6 +119,45 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
importMapping = new HashMap<String, String>();
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "swift";
}
public String getHelp() {
return "Generates a swift client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
@ -154,10 +193,12 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
} else
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@ -202,8 +243,9 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
@Override
public String toApiName(String name) {
if(name.length() == 0)
if (name.length() == 0) {
return "DefaultAPI";
}
return initialCaps(name) + "API";
}
@ -220,31 +262,4 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions);
}
private static String normalizePath(String path) {
StringBuilder builder = new StringBuilder();
int cursor = 0;
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
boolean found = matcher.find();
while (found) {
String stringBeforeMatch = path.substring(cursor, matcher.start());
builder.append(stringBeforeMatch);
String group = matcher.group().substring(1, matcher.group().length() - 1);
group = camelize(group, true);
builder
.append("{")
.append(group)
.append("}");
cursor = matcher.end();
found = matcher.find();
}
String stringAfterMatch = path.substring(cursor);
builder.append(stringAfterMatch);
return builder.toString();
}
}

View File

@ -1,30 +1,36 @@
package io.swagger.codegen.languages;
import io.swagger.util.Json;
import io.swagger.codegen.*;
import io.swagger.models.properties.*;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
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.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import java.util.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
protected static String PREFIX = "Sami";
protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client";
protected static String PREFIX = "Sami";
protected Map<String, String> namespaces = new HashMap<String, String>();
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "tizen";
}
public String getHelp() {
return "Generates a Samsung Tizen C++ client library.";
}
public TizenClientCodegen() {
super();
outputFolder = "generated-code/tizen";
@ -102,29 +108,41 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp"));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "tizen";
}
public String getHelp() {
return "Generates a Samsung Tizen C++ client library.";
}
@Override
public String toInstantiationType(Property p) {
if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map");
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array");
}
else
} else {
return null;
}
}
@Override
public String getTypeDeclaration(String name) {
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name))
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
return name;
else
} else {
return name + "*";
}
}
@Override
public String getSwaggerType(Property p) {
@ -132,22 +150,24 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type))
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
return toModelName(type);
}
else
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType))
if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
return toModelName(swaggerType);
else
} else {
return swaggerType + "*";
}
}
@Override
public String toModelName(String type) {
@ -158,8 +178,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return type;
}
else {
} else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@ -174,30 +193,29 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toDefaultValue(Property p) {
if(p instanceof StringProperty)
if (p instanceof StringProperty) {
return "new String()";
else if (p instanceof BooleanProperty)
} else if (p instanceof BooleanProperty) {
return "new Boolean(false)";
else if(p instanceof DateProperty)
} else if (p instanceof DateProperty) {
return "new DateTime()";
else if(p instanceof DateTimeProperty)
} else if (p instanceof DateTimeProperty) {
return "new DateTime()";
else if (p instanceof DoubleProperty)
} else if (p instanceof DoubleProperty) {
return "new Double()";
else if (p instanceof FloatProperty)
} else if (p instanceof FloatProperty) {
return "new Float()";
else if (p instanceof IntegerProperty)
} else if (p instanceof IntegerProperty) {
return "new Integer()";
else if (p instanceof LongProperty)
} else if (p instanceof LongProperty) {
return "new Long()";
else if (p instanceof DecimalProperty)
} else if (p instanceof DecimalProperty) {
return "new Long()";
else if (p instanceof MapProperty) {
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap()";
}
else if (p instanceof ArrayProperty) {
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
return "new ArrayList()";
@ -248,8 +266,9 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return$
if(reservedWords.contains(operationId))
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
// add_pet_by_id => addPetById
return camelize(operationId, true);

View File

@ -1,9 +1,6 @@
package {{package}};
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

View File

@ -40,12 +40,17 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
public class ApiClient {
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map
<String, Client> hostMap = new HashMap
<String, Client>();
private Map
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private boolean debugging = false;
private String basePath = "{{basePath}}";
private Map<String, Authentication> authentications;
private Map
<String, Authentication> authentications;
private DateFormat dateFormat;
@ -61,7 +66,8 @@ public class ApiClient {
setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications = new HashMap
<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
@ -81,7 +87,8 @@ public class ApiClient {
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
public Map
<String, Authentication> getAuthentications() {
return authentications;
}
@ -341,7 +348,10 @@ public class ApiClient {
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
public String invokeAPI(String path, String method, Map
<String, String> queryParams, Object body, Map
<String, String> headerParams, Map
<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
Client client = getClient();
@ -457,7 +467,9 @@ public class ApiClient {
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
private void updateParamsForAuth(String[] authNames, Map
<String, String> queryParams, Map
<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
@ -468,10 +480,12 @@ public class ApiClient {
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
private String getXWWWFormUrlencodedParams(Map
<String, String> formParams) {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, String> param : formParams.entrySet()) {
for (Entry
<String, String> param : formParams.entrySet()) {
String keyStr = parameterToString(param.getKey());
String valueStr = parameterToString(param.getValue());

View File

@ -61,9 +61,15 @@ public class {{classname}} {
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> queryParams = new HashMap
<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
{{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));

View File

@ -6,7 +6,9 @@ import java.util.List;
public class ApiException extends Exception {
private int code = 0;
private String message = null;
private Map<String, List<String>> responseHeaders = null;
private Map
<String, List
<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {}
@ -16,7 +18,10 @@ public class ApiException extends Exception {
this.message = message;
}
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
public ApiException(int code, String message, Map
<String
, List
<String>> responseHeaders, String responseBody) {
this.code = code;
this.message = message;
this.responseHeaders = responseHeaders;
@ -34,7 +39,10 @@ public class ApiException extends Exception {
/**
* Get the HTTP response headers.
*/
public Map<String, List<String>> getResponseHeaders() {
public Map
<String
, List
<String>> getResponseHeaders() {
return responseHeaders;
}

View File

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

View File

@ -4,5 +4,7 @@ import java.util.Map;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams);
void applyToParams(Map
<String, String> queryParams, Map
<String, String> headerParams);
}

View File

@ -26,7 +26,9 @@ public class HttpBasicAuth implements Authentication {
}
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
public void applyToParams(Map
<String, String> queryParams, Map
<String, String> headerParams) {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
try {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));

View File

@ -4,7 +4,9 @@ import java.util.Map;
public class OAuth implements Authentication {
@Override
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
public void applyToParams(Map
<String, String> queryParams, Map
<String, String> headerParams) {
// TODO: support oauth
}
}

View File

@ -77,7 +77,8 @@
</goals>
<configuration>
<sources>
<source>src/main/java</source>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
@ -89,7 +90,8 @@
</goals>
<configuration>
<sources>
<source>src/test/java</source>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<source>
1.6</source>
<target>1.6</target>
</configuration>
</plugin>

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
@ -75,7 +76,8 @@
</goals>
<configuration>
<sources>
<source>src/gen/java</source>
<source>
src/gen/java</source>
</sources>
</configuration>
</execution>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
<servlet>
<servlet-name>jersey</servlet-name>

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
@ -31,7 +32,8 @@
<version>${jetty-version}</version>
<configuration>
<webAppConfig>
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
<contextPath>{{^contextPath}}
/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
</webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
@ -95,7 +97,8 @@
<outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
<resources>
<resource>
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory>
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist
</directory>
<filtering>true</filtering>
<excludes>
<exclude>index.html</exclude>

View File

@ -64,7 +64,8 @@ object ApiInvoker {
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
invoker.execute(request)
def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] =
def result[U
<: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U]=
invoker.execute(request).map(_.content).mapTo[U]
}

View File

@ -11,7 +11,8 @@ object EnumsSerializers {
private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E)
private class EnumNameSerializer[E
<: Enumeration: ClassTag](enum: E)
extends Serializer[E#Value] {
import JsonDSL._

View File

@ -58,11 +58,17 @@ public class {{classname}} {
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map
<String, String> queryParams = new HashMap
<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
{{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));

View File

@ -53,7 +53,9 @@ import com.google.gson.JsonParseException;
public class ApiInvoker {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private HttpClient client = null;
@ -184,7 +186,10 @@ public class ApiInvoker {
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
public String invokeAPI(String host, String path, String method, Map
<String, String> queryParams, Object body, Map
<String, String> headerParams, Map
<String, String> formParams, String contentType) throws ApiException {
HttpClient client = getClient(host);
StringBuilder b = new StringBuilder();
@ -200,7 +205,9 @@ public class ApiInvoker {
}
String url = host + path + b.toString();
HashMap<String, String> headers = new HashMap<String, String>();
HashMap
<String, String> headers = new HashMap
<String, String>();
for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));

View File

@ -24,11 +24,13 @@ public class JsonUtil {
return getGson().toJson(obj);
}
public static <T> T deserializeToList(String jsonString, Class cls){
public static
<T> T deserializeToList(String jsonString, Class cls){
return getGson().fromJson(jsonString, getListTypeForDeserialization(cls));
}
public static <T> T deserializeToObject(String jsonString, Class cls){
public static
<T> T deserializeToObject(String jsonString, Class cls){
return getGson().fromJson(jsonString, getTypeForDeserialization(cls));
}
@ -36,10 +38,14 @@ public class JsonUtil {
String className = cls.getSimpleName();
{{#models}}{{#model}}
if ("{{classname}}".equalsIgnoreCase(className)) {
return new TypeToken<List<{{classname}}>>(){}.getType();
return new TypeToken
<List
<{{classname}}>>(){}.getType();
}
{{/model}}{{/models}}
return new TypeToken<List<Object>>(){}.getType();
return new TypeToken
<List
<Object>>(){}.getType();
}
public static Type getTypeForDeserialization(Class cls) {
@ -49,7 +55,8 @@ public class JsonUtil {
return new TypeToken<{{classname}}>(){}.getType();
}
{{/model}}{{/models}}
return new TypeToken<Object>(){}.getType();
return new TypeToken
<Object>(){}.getType();
}
};

View File

@ -77,7 +77,8 @@
</goals>
<configuration>
<sources>
<source>src/main/java</source>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
@ -89,7 +90,8 @@
</goals>
<configuration>
<sources>
<source>src/test/java</source>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<source>
1.6</source>
<target>1.6</target>
</configuration>
</plugin>

View File

@ -86,7 +86,8 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String> (
reservedWords = new HashSet
<String> (
Arrays.asList(
"sample1", // replace with static values
"sample2")
@ -112,7 +113,8 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>(
languageSpecificPrimitives = new HashSet
<String>(
Arrays.asList(
"Type1", // replace these with your types
"Type2")

View File

@ -57,7 +57,8 @@
</goals>
<configuration>
<sources>
<source>src/main/java</source>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
@ -69,7 +70,8 @@
</goals>
<configuration>
<sources>
<source>src/test/java</source>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
@ -80,7 +82,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<source>
1.6</source>
<target>1.6</target>
</configuration>
</plugin>

View File

@ -9,36 +9,55 @@ using Newtonsoft.Json;
using RestSharp;
namespace {{invokerPackage}} {
/// <summary>
///
<summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
///
</summary>
public class ApiClient {
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class.
/// </summary>
/// <param name="basePath">The base path.</param>
///
<summary>
/// Initializes a new instance of the
<see cref="ApiClient"/>
class.
///
</summary>
///
<param name="basePath">The base path.</param>
public ApiClient(String basePath="{{basePath}}") {
this.basePath = basePath;
this.restClient = new RestClient(this.basePath);
}
/// <summary>
///
<summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
///
</summary>
///
<value>The base path.</value>
public string basePath { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
///
</summary>
///
<value>The RestClient.</value>
public RestClient restClient { get; set; }
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
private Dictionary
<String, String> defaultHeaderMap = new Dictionary
<String, String>();
public Object CallApi(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
public Object CallApi(String Path, RestSharp.Method Method, Dictionary
<String, String> QueryParams, String PostBody,
Dictionary
<String, String> HeaderParams, Dictionary
<String, String> FormParams, Dictionary
<String, String> FileParams, String[] AuthSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings);
return resp;
@ -46,31 +65,50 @@ namespace {{invokerPackage}} {
return response.Result;
}
public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
public async Task
<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary
<String
, String> QueryParams, String PostBody,
Dictionary
<String
, String> HeaderParams, Dictionary
<String
, String> FormParams, Dictionary
<String
, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
foreach(KeyValuePair
<string
, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in HeaderParams)
foreach(KeyValuePair
<string
, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in QueryParams)
foreach(KeyValuePair
<string
, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in FormParams)
foreach(KeyValuePair
<string
, string> param in FormParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, string> param in FileParams)
foreach(KeyValuePair
<string
, string> param in FileParams)
request.AddFile(param.Key, param.Value);
if (PostBody != null) {
@ -81,57 +119,88 @@ namespace {{invokerPackage}} {
}
/// <summary>
///
<summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
///
</summary>
///
<param name="key">
Header field name
///
<param name="value">
Header field value
///
<returns></returns>
public void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
/// <summary>
///
<summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
///
</summary>
///
<returns>Dictionary of default header</returns>
public Dictionary
<String
, String> GetDefaultHeader() {
return defaultHeaderMap;
}
/// <summary>
///
<summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
///
</summary>
///
<param name="str">
String to be escaped
///
<returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
}
/// <summary>
///
<summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
///
</summary>
///
<param name="obj">
The parameter (header, path, query, form)
///
<returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else if (obj is List
<string>) {
return String.Join(",", obj as List
<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
///
<summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="json"> JSON string
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
///
</summary>
///
<param name="json">
JSON string
///
<param name="type">
Object type
///
<returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
@ -145,11 +214,16 @@ namespace {{invokerPackage}} {
}
}
/// <summary>
///
<summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
///
</summary>
///
<param name="obj">
Object
///
<returns>JSON string</returns>
public string Serialize(object obj) {
try
{
@ -160,11 +234,16 @@ namespace {{invokerPackage}} {
}
}
/// <summary>
///
<summary>
/// Get the API key with prefix
/// </summary>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
///
</summary>
///
<param name="obj">
Object
///
<returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKey)
{
var apiKeyValue = "";
@ -177,13 +256,25 @@ namespace {{invokerPackage}} {
}
}
/// <summary>
///
<summary>
/// Update parameters based on authentication
/// </summary>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> QueryParams, Dictionary<String, String> HeaderParams, string[] AuthSettings) {
///
</summary>
///
<param name="QueryParams">
Query parameters</param>
///
<param name="HeaderParams">
Header parameters</param>
///
<param name="AuthSettings">
Authentication settings</param>
public void UpdateParamsForAuth(Dictionary
<String
, String> QueryParams, Dictionary
<String
, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0)
return;
@ -192,7 +283,11 @@ namespace {{invokerPackage}} {
switch(auth) {
{{#authMethods}}
case "{{name}}":
{{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + Configuration.password);{{/isBasic}}
{{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}
");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] =
GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}
HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" +
Configuration.password);{{/isBasic}}
{{#isOAuth}}//TODO support oauth{{/isOAuth}}
break;
{{/authMethods}}
@ -204,10 +299,14 @@ namespace {{invokerPackage}} {
}
/// <summary>
///
<summary>
/// Encode string in base64 format
/// </summary>
/// <param name="text">String to be encoded</param>
///
</summary>
///
<param name="text">
String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);

View File

@ -1,33 +1,52 @@
using System;
namespace {{invokerPackage}} {
/// <summary>
///
<summary>
/// API Exception
/// </summary>
///
</summary>
public class ApiException : Exception {
/// <summary>
///
<summary>
/// Gets or sets the error code (HTTP status code)
/// </summary>
/// <value>The error code (HTTP status code).</value>
///
</summary>
///
<value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the error content (body json object)
/// </summary>
/// <value>The error content (Http response body).</value>
///
</summary>
///
<value>The error content (Http response body).</value>
public dynamic ErrorContent { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="basePath">The base path.</param>
///
<summary>
/// Initializes a new instance of the
<see cref="ApiException"/>
class.
///
</summary>
///
<param name="basePath">The base path.</param>
public ApiException() {}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="errorCode">HTTP status code.</param>
/// <param name="message">Error message.</param>
///
<summary>
/// Initializes a new instance of the
<see cref="ApiException"/>
class.
///
</summary>
///
<param name="errorCode">HTTP status code.</param>
///
<param name="message">Error message.</param>
public ApiException(int errorCode, string message) : base(message) {
this.ErrorCode = errorCode;
}

View File

@ -7,40 +7,61 @@ using System.Text;
using {{invokerPackage}};
namespace {{invokerPackage}} {
/// <summary>
///
<summary>
/// Represents a set of configuration settings
/// </summary>
///
</summary>
public class Configuration{
/// <summary>
///
<summary>
/// Gets or sets the API client. This is the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
///
</summary>
///
<value>The API client.</value>
public static ApiClient apiClient = new ApiClient();
/// <summary>
///
<summary>
/// Gets or sets the username (HTTP basic authentication)
/// </summary>
/// <value>The username.</value>
///
</summary>
///
<value>The username.</value>
public static String username { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the password (HTTP basic authentication)
/// </summary>
/// <value>The password.</value>
///
</summary>
///
<value>The password.</value>
public static String password { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the API key based on the authentication name
/// </summary>
/// <value>The API key.</value>
public static Dictionary<String, String> apiKey = new Dictionary<String, String>();
///
</summary>
///
<value>The API key.</value>
public static Dictionary
<String, String> apiKey = new Dictionary
<String, String>();
/// <summary>
///
<summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name
/// </summary>
/// <value>The prefix of the API key.</value>
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>();
///
</summary>
///
<value>The prefix of the API key.</value>
public static Dictionary
<String, String> apiKeyPrefix = new Dictionary
<String, String>();
}

View File

@ -12,32 +12,48 @@ namespace {{package}} {
public interface I{{classname}} {
{{#operation}}
/// <summary>
///
<summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
///
</summary>
{{#allParams}}///
<param name="{{paramName}}">{{description}}</param>{{/allParams}}
///
<returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
/// <summary>
///
<summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
///
</summary>
{{#allParams}}///
<param name="{{paramName}}">{{description}}</param>{{/allParams}}
///
<returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
{{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
}
/// <summary>
///
<summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
///
</summary>
public class {{classname}} : I{{classname}} {
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
///
<summary>
/// Initializes a new instance of the
<see cref="{{classname}}"/>
class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public {{classname}}(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
@ -46,44 +62,62 @@ namespace {{package}} {
}
}
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <returns></returns>
///
<summary>
/// Initializes a new instance of the
<see cref="{{classname}}"/>
class.
///
</summary>
///
<returns></returns>
public {{classname}}(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
///
<summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
///
</summary>
///
<value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
///
<summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
///
</summary>
///
<value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
///
<summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
///
</summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;}
{{#operation}}
/// <summary>
///
<summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
///
</summary>
{{#allParams}}///
<param name="{{paramName}}">{{description}}</param>{{/allParams}}
///
<returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#allParams}}{{#required}}
@ -96,10 +130,14 @@ namespace {{package}} {
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}}));
{{/pathParams}}
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
<String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter
@ -124,11 +162,15 @@ namespace {{package}} {
return;{{/returnType}}
}
/// <summary>
///
<summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
///
</summary>
{{#allParams}}///
<param name="{{paramName}}">{{description}}</param>{{/allParams}}
///
<returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#allParams}}{{#required}}
@ -141,10 +183,14 @@ namespace {{package}} {
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}}));
{{/pathParams}}
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
<String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter

View File

@ -9,9 +9,11 @@ using Newtonsoft.Json;
{{#model}}
namespace {{package}} {
/// <summary>
///
<summary>
/// {{description}}
/// </summary>
///
</summary>
[DataContract]
public class {{classname}} {
{{#vars}}
@ -21,10 +23,13 @@ namespace {{package}} {
{{/vars}}
/// <summary>
///
<summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class {{classname}} {\n");
@ -35,10 +40,13 @@ namespace {{package}} {
return sb.ToString();
}
/// <summary>
///
<summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}

View File

@ -1,8 +1,4 @@
package io.swagger.event {
import io.swagger.event.Response;
import flash.events.Event;
/**
* Event dispatched by the SDK to communicate success events and failure events.
* If a custom dispatcher has been assigned by the consumer on the generated client then the dispatcher dispatches
@ -20,6 +16,9 @@ public class ApiClientEvent extends Event{
*/
public static const SUCCESS_EVENT:String = "successfulInvocation";
public function ApiClientEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
super(type, bubbles, cancelable);
}
/**
* The Response object which contains response info
*/
@ -28,9 +27,5 @@ public class ApiClientEvent extends Event{
* Any additional info
*/
public var message:String;
public function ApiClientEvent(type:String,bubbles:Boolean = false,cancelable:Boolean = false) {
super(type, bubbles, cancelable);
}
}
}

View File

@ -1,9 +1,6 @@
package io.swagger.exception
{
public class ApiError extends Error
{
public function ApiError(id:*=0, message:*="")
{
package io.swagger.exception {
public class ApiError extends Error {
public function ApiError(id:* = 0, message:* = "") {
super(message, id);
}
}

View File

@ -1,7 +1,5 @@
package io.swagger.exception
{
public class ApiErrorCodes
{
package io.swagger.exception {
public class ApiErrorCodes {
/**
* System exception.
*/

View File

@ -1,289 +0,0 @@
package io.swagger.common
{
import asaxb.xml.bind.ASAXBContext;
import asaxb.xml.bind.Unmarshaller;
import io.swagger.event.ApiClientEvent;
import io.swagger.event.Response;
import io.swagger.common.ApiUserCredentials;
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.messaging.ChannelSet;
import mx.messaging.channels.HTTPChannel;
import mx.messaging.messages.HTTPRequestMessage;
import mx.rpc.AsyncToken;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.utils.ObjectUtil;
public class ApiInvoker extends EventDispatcher
{
private var _apiUsageCredentials:ApiUserCredentials;
internal var _apiProxyServerUrl:String = "";
private var _baseUrl: String = "";
internal var _useProxyServer: Boolean = true;
private var _proxyHostName:String = "";
private var _apiPath: String = "";
private var _proxyPath: String = "";
public var _apiEventNotifier:EventDispatcher;
private static const DELETE_DATA_DUMMY:String = "dummyDataRequiredForDeleteOverride";
private static const X_HTTP_OVERRIDE_KEY:String = "X-HTTP-Method-Override";
private static const CONTENT_TYPE_HEADER_KEY:String = "Content-Type";
public function ApiInvoker(apiUsageCredentials: ApiUserCredentials, eventNotifier: EventDispatcher, useProxy: Boolean = true) {
_apiUsageCredentials = apiUsageCredentials;
_useProxyServer = useProxy;
if(_apiUsageCredentials.hostName != null){
_proxyHostName = _apiUsageCredentials.hostName;
}
_apiPath = _apiUsageCredentials.apiPath;
_proxyPath = _apiUsageCredentials.proxyPath;
_apiProxyServerUrl = _apiUsageCredentials.apiProxyServerUrl;
_apiEventNotifier = eventNotifier;
}
public function invokeAPI(resourceURL: String, method: String, queryParams: Dictionary, postObject: Object, headerParams: Dictionary): AsyncToken {
//make the communication
if(_useProxyServer) {
resourceURL = _apiProxyServerUrl + resourceURL;
}
else{
resourceURL = "http://"+ _proxyHostName + _apiPath + resourceURL;
}
var counter: int = 0;
var symbol: String = "&";
var paramValue: Object;
for (var paramName:String in queryParams) {
paramValue = queryParams[paramName];
//var key:String = paramName;
// do stuff
symbol = "&";
if(counter == 0){
symbol = "?";
}
resourceURL = resourceURL + symbol + paramName + "=" + paramValue.toString();
counter++;
}
// trace(resourceURL);
//create a httpservice and invoke the rest url waiting for response
var requestHeader:Object = new Object();
if(headerParams != null) {
for(var key: String in headerParams) {
requestHeader[key] = headerParams[key];
}
}
resourceURL = ApiUrlHelper.appendTokenInfo(resourceURL, requestHeader, _apiUsageCredentials);
var bodyData:String = marshal(postObject).toString();//restRequest.postData;
return doRestCall(resourceURL, onApiRequestResult, onApiRequestFault, method, bodyData, requestHeader, "application/xml");
}
private function doRestCall( url : String, resultFunction : Function, faultFunction : Function = null,
restMethod : String = "GET",
bodyData : Object = null, headers: Object = null, contentType:String = "application/xml" ) : AsyncToken
{
var httpService : HTTPService = new HTTPService( );
if(headers == null){
headers = new Object();
}
httpService.method = restMethod;
if ( restMethod.toUpperCase() != HTTPRequestMessage.GET_METHOD )
{
//httpService.method = HTTPRequestMessage.POST_METHOD; - not required as we're using the proxy
if( bodyData == null )
{
bodyData = new Object();
}
if(restMethod == HTTPRequestMessage.DELETE_METHOD){
headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.DELETE_METHOD;
bodyData = DELETE_DATA_DUMMY;
}
else if(restMethod == HTTPRequestMessage.PUT_METHOD){
headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.PUT_METHOD;
}
else{
headers[CONTENT_TYPE_HEADER_KEY]= contentType;
}
}
else
{
//if the request type is GET and content type is xml then the Flex HTTPService converts it to a POST ... yeah
contentType = null;
}
httpService.url = url;
httpService.contentType = contentType;
httpService.resultFormat = "e4x";
httpService.headers = headers;
httpService.addEventListener( ResultEvent.RESULT, resultFunction );
if( faultFunction != null )
{
httpService.addEventListener( FaultEvent.FAULT, faultFunction );
}
if(_useProxyServer){
httpService.useProxy = true;
var channelSet: ChannelSet = new ChannelSet();
var httpChannel: HTTPChannel = new HTTPChannel();
httpChannel.uri = ApiUrlHelper.getProxyUrl(_proxyHostName, _proxyPath);
channelSet.addChannel(httpChannel);
httpService.channelSet = channelSet;
}
return httpService.send( bodyData );
}
private function onApiRequestResult(event:ResultEvent):void
{
var completionListener: Function = event.token.completionListener;
var result: Object = event.result;
var resultType: Class = event.token.returnType;
var resultObject:Object;
if(resultType != null) {
var context:ASAXBContext = ASAXBContext.newInstance(resultType);
var unmarshaller:Unmarshaller = context.createUnmarshaller();
var resultXML: XML = new XML(event.result);
try{
resultObject = unmarshaller.unmarshal(resultXML);
}
catch(error: TypeError){
var errorResponse: Response = new Response(false, null, "Could not unmarshall response");
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent: ApiClientEvent = new ApiClientEvent(event.token.completionEventType);
failureEvent.response = errorResponse;
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
if(resultObject is ListWrapper){
resultObject = ListWrapper(resultObject).getList();
}
}
var response : Response = new Response(true, resultObject);
response.requestId = event.token.requestId;
var successEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.SUCCESS_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var successEvent: ApiClientEvent = new ApiClientEvent(successEventType);
successEvent.response = response;
_apiEventNotifier.dispatchEvent(successEvent);
}
}
private function onApiRequestFault(event:FaultEvent):void
{
var completionListener: Function = event.token.completionListener;
if(completionListener != null){
completionListener.call( null, new Response( false, null, event.fault.faultString) );
}
var failureEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.FAILURE_EVENT;
if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher
var failureEvent: ApiClientEvent = new ApiClientEvent(failureEventType);
failureEvent.response = new Response( false, null, event.fault.faultString);
_apiEventNotifier.dispatchEvent(failureEvent);
}
}
public function marshal(source:Object):Object {
// trace("marshal got - " + source)
if(source is String) {
return source;
} else if(source is Array && source.length > 0) {
var writer:XMLWriter=new XMLWriter();
var sourceArray: Array = source as Array;
var arrayEnclosure: String = getArrayEnclosure(sourceArray);
writer.xml.setName(arrayEnclosure);
for (var i:int = 0; i < sourceArray.length; i++) {
var o: Object = sourceArray[i];
writer.xml.appendChild(marshal(o));
}
return writer.xml;
} else
return marshalObject(source);
}
public function marshalObject(source:Object):XML
{
var writer:XMLWriter=new XMLWriter();
var objDescriptor:XML=describeType(source);
var property:XML;
var propertyType:String;
var propertyValue:Object;
var qualifiedClassName:String=objDescriptor.@name;
qualifiedClassName=qualifiedClassName.replace("::",".");
var className: String = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(".") + 1);
className = className().toLowerCase() + className.substring(1);
writer.xml.setName(className);
for each(property in objDescriptor.elements("variable")){
propertyValue=source[property.@name];
if (propertyValue!=null){
if (ObjectUtil.isSimple(propertyValue)){
writer.addProperty(property.@name, propertyValue.toString());
}
else {
writer.addProperty(property.@name, marshal(propertyValue).toXMLString());
}
}
}
for each(property in objDescriptor.elements("accessor")){
if (property.@access=="readonly"){
continue;
}
propertyValue=source[property.@name];
if (source[property.@name]!=null){
if (ObjectUtil.isSimple(propertyValue)){
writer.addProperty(property.@name, propertyValue.toString());
}
else {
writer.addProperty(property.@name, marshal(propertyValue).toXMLString());
}
}
}
return writer.xml;
}
public function escapeString(str: String): String {
return str;
}
private function getArrayEnclosure(arr: Array) : String {
if(arr != null && arr.length > 0) {
var className: String = flash.utils.getQualifiedClassName(arr[0])
if(className.indexOf("::") > 0)
className = className.substr(className.indexOf("::") + 2, className.length)
return className.substring(0, 1).toLowerCase() + className.substring(1, className.length) + "s";
} else
return "";
}
}
}

View File

@ -1,6 +1,4 @@
package io.swagger.common {
import io.swagger.common.ApiUserCredentials;
/**
* @private
* Internal class for the Rest client

View File

@ -5,41 +5,6 @@ package io.swagger.common {
*
*/
public class ApiUserCredentials {
/**
* An apitoken that is passed along with the requests
*/
public var apiToken:String;
/**
* A valid auth_token which could be necessary for certain operations
*/
public var authToken:String;
/**
* The userId which could be required for certain operations
*/
public var userId:Number;
/**
* The host name for the Rest API eg. api.companyName.com
*/
public var hostName:String;
/**
* The base path to the api resources - used along with the hostname
* eg. /v4
*/
public var apiPath: String;
/**
* The base path to the blazeds proxy
* eg. /v4/messagebroker/restproxy
*/
public var proxyPath: String;
/**
* If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with
* the value useProxy as true
*/
public var apiProxyServerUrl: String;
/**
* Constructor of ApiUserCredentials
* @param apiToken An apitoken that is passed along with the requests
@ -58,6 +23,37 @@ public class ApiUserCredentials {
this.apiProxyServerUrl = apiProxyServerUrl;
this.proxyPath = proxyPath;
}
/**
* An apitoken that is passed along with the requests
*/
public var apiToken:String;
/**
* A valid auth_token which could be necessary for certain operations
*/
public var authToken:String;
/**
* The userId which could be required for certain operations
*/
public var userId:Number;
/**
* The host name for the Rest API eg. api.companyName.com
*/
public var hostName:String;
/**
* The base path to the api resources - used along with the hostname
* eg. /v4
*/
public var apiPath:String;
/**
* The base path to the blazeds proxy
* eg. /v4/messagebroker/restproxy
*/
public var proxyPath:String;
/**
* If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with
* the value useProxy as true
*/
public var apiProxyServerUrl:String;
}
}

View File

@ -1,7 +1,5 @@
package io.swagger.common
{
public interface ListWrapper
{
package io.swagger.common {
public interface ListWrapper {
function getList():Array;

View File

@ -6,33 +6,8 @@ package io.swagger.event {
*/
public class Response {
/**
* Indicates whether the invoked operation failed or succeeded
*/
public var isSuccess:Boolean;
/**
* The payload of the succesful operation eg. a Word in a WordRequest
*/
public var payload:Object;
/**
* Error message in case of failure
*/
public var errorMessage:String;
/**
* A request Id that was passed in by the user as a param when invoking the operation
*/
public var requestId:String;
private static const API_ERROR_MSG:String = "Api error response: ";
public function Response(isSuccessful: Boolean, payload: Object = null, errorMessage: String = null, requestId: String = null) {
this.isSuccess = isSuccessful;
this.payload = payload;
this.errorMessage = getFriendlyMessage(errorMessage);
}
private static function getFriendlyMessage(errorMessage:String):String {
var result:String = errorMessage;
if (errorMessage == null)
@ -49,6 +24,28 @@ public class Response {
return result;
}
public function Response(isSuccessful:Boolean, payload:Object = null, errorMessage:String = null, requestId:String = null) {
this.isSuccess = isSuccessful;
this.payload = payload;
this.errorMessage = getFriendlyMessage(errorMessage);
}
/**
* Indicates whether the invoked operation failed or succeeded
*/
public var isSuccess:Boolean;
/**
* The payload of the succesful operation eg. a Word in a WordRequest
*/
public var payload:Object;
/**
* Error message in case of failure
*/
public var errorMessage:String;
/**
* A request Id that was passed in by the user as a param when invoking the operation
*/
public var requestId:String;
public function toString():String {
return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")";
}

View File

@ -1,50 +1,5 @@
package io.swagger.common
{
import io.swagger.common.ApiUserCredentials;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import mx.utils.UIDUtil;
public class SwaggerApi extends EventDispatcher
{
protected var _apiUsageCredentials:ApiUserCredentials;
protected var _apiEventNotifier:EventDispatcher;
protected var _apiInvoker: ApiInvoker;
protected var _useProxyServer: Boolean = false;
/**
* Constructor for the api client
* @param apiCredentials Wrapper object for tokens and hostName required towards authentication
* @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response
*/
public function SwaggerApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) {
super();
_apiUsageCredentials = apiCredentials;
_apiEventNotifier = eventDispatcher;
}
public function useProxyServer(value:Boolean, proxyServerUrl: String = null):void {
_useProxyServer = value;
}
protected function getApiInvoker():ApiInvoker {
if(_apiInvoker == null){
if(_apiEventNotifier == null){
_apiEventNotifier = this;
}
_apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer);
}
return _apiInvoker;
}
protected function getUniqueId():String {
return UIDUtil.createUID();
}
package io.swagger.common {
public class SwaggerApi extends EventDispatcher {
/**
* Method for returning the path value
@ -71,5 +26,38 @@ package io.swagger.common
return objects.join(",");
}
/**
* Constructor for the api client
* @param apiCredentials Wrapper object for tokens and hostName required towards authentication
* @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response
*/
public function SwaggerApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) {
super();
_apiUsageCredentials = apiCredentials;
_apiEventNotifier = eventDispatcher;
}
protected var _apiUsageCredentials:ApiUserCredentials;
protected var _apiEventNotifier:EventDispatcher;
protected var _apiInvoker:ApiInvoker;
protected var _useProxyServer:Boolean = false;
public function useProxyServer(value:Boolean, proxyServerUrl:String = null):void {
_useProxyServer = value;
}
protected function getApiInvoker():ApiInvoker {
if (_apiInvoker == null) {
if (_apiEventNotifier == null) {
_apiEventNotifier = this;
}
_apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer);
}
return _apiInvoker;
}
protected function getUniqueId():String {
return UIDUtil.createUID();
}
}
}

View File

@ -1,13 +1,9 @@
package io.swagger.common
{
public class XMLWriter
{
public var xml:XML;
public function XMLWriter()
{
package io.swagger.common {
public class XMLWriter {
public function XMLWriter() {
xml = <obj/>;
}
public var xml:XML;
public function reset():void {
xml = new XML();

View File

@ -1,3 +1,5 @@
{{#isBodyParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isBodyParam}}
<div class="param">{{paramName}} {{^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

@ -1,3 +1,5 @@
{{#isFormParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isFormParam}}
<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Form Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isFormParam}}
<div class="param-desc"><span class="param-type">Form Parameter</span> &mdash; {{description}} {{#defaultValue}}
default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isFormParam}}

View File

@ -1,3 +1,5 @@
{{#isHeaderParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isHeaderParam}}
<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Header Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isHeaderParam}}
<div class="param-desc"><span class="param-type">Header Parameter</span> &mdash; {{description}} {{#defaultValue}}
default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isHeaderParam}}

View File

@ -5,39 +5,50 @@
</head>
<body>
<h1>{{{appName}}}</h1>
<div class="app-desc">{{{appDescription}}} for {{partner}}</div>
{{#infoUrl}}<div class="app-desc">More information: <a href="{{{infoUrl}}}">{{{infoUrl}}}</a></div>{{/infoUrl}}
{{#infoEmail}}<div class="app-desc">Contact Info: <a href="{{{infoEmail}}}">{{{infoEmail}}}</a></div>{{/infoEmail}}
{{#version}}<div class="app-desc">Version: {{{version}}}</div>{{/version}}
{{#infoUrl}}
<div class="app-desc">More information: <a href="{{{infoUrl}}}">{{{infoUrl}}}</a></div>{{/infoUrl}}
{{#infoEmail}}
<div class="app-desc">Contact Info: <a href="{{{infoEmail}}}">{{{infoEmail}}}</a></div>{{/infoEmail}}
{{#version}}
<div class="app-desc">Version: {{{version}}}</div>{{/version}}
<div class="license-info">{{{licenseInfo}}}</div>
<div class="license-url">{{{licenseUrl}}}</div>
<h2>Access</h2>
<div class="method-summary">Customize this message as you see fit!</div>
<h2>Methods</h2>
{{#apiInfo}}
{{#apis}}
{{#operations}}{{#operation}}
<div class="method">
<div class="method-path"><pre class="{{httpMethod}}"><code class="huge"><span>{{httpMethod}}</span>: {{path}}</code></pre></div>
<div class="method-path">
<pre class="{{httpMethod}}"><code class="huge"><span>{{httpMethod}}</span>: {{path}}</code></pre>
</div>
<div class="method-tags"> {{#tags}}<span class="method-tag">{{this}}</span>{{/tags}}</div>
<div class="method-summary"><span class="nickname">{{nickname}}</span> {{summary}}</div>
<div class="method-notes">{{notes}}</div>
<h3 class="field-label">Parameters</h3>
<div class="field-items">
{{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}}
{{/allParams}}
</div> <!-- field-items -->
</div>
<!-- field-items -->
<h3 class="field-label">Return type</h3>
<div class="return-type"><a href="#{{returnContainer}}">{{{returnType}}}</a></div>
{{#examples}}
<h3 class="field-label">Example data</h3>
<div class="example-data-content-type">Content-Type: {{{contentType}}}</div>
<pre class="example"><code>{{example}}</code></pre>
{{/examples}}
</div> <!-- method -->
</div>
<!-- method -->
<hr>
{{/operation}}{{/operations}}
{{/apis}}{{/apiInfo}}
@ -47,10 +58,14 @@
{{#model}}
<div class="model">
<h3 class="field-label"><a name="{{classname}}">{{classname}}</a></h3>
<div class="field-items">
{{#vars}}<div class="param">{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}</div><div class="param-desc"><span class="param-type">{{datatype}}</span> {{description}}</div>
{{#vars}}
<div class="param">{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}</div>
<div class="param-desc"><span class="param-type">{{datatype}}</span> {{description}}</div>
{{/vars}}
</div> <!-- field-items -->
</div>
<!-- field-items -->
</div>
{{/model}}
{{/models}}

View File

@ -1,3 +1,5 @@
{{#isPathParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isPathParam}}
<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Path Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isPathParam}}
<div class="param-desc"><span class="param-type">Path Parameter</span> &mdash; {{description}} {{#defaultValue}}
default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isPathParam}}

View File

@ -1,3 +1,5 @@
{{#isQueryParam}}<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
{{#isQueryParam}}
<div class="param">{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}</div>
<div class="param-desc"><span class="param-type">Query Parameter</span> &mdash; {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isQueryParam}}
<div class="param-desc"><span class="param-type">Query Parameter</span> &mdash; {{description}} {{#defaultValue}}
default: {{{defaultValue}}}{{/defaultValue}}</div>{{/isQueryParam}}

View File

@ -1,4 +1,5 @@
#import <Foundation/Foundation.h>
#import
<Foundation/Foundation.h>
@interface SWGConfiguration : NSObject

View File

@ -1,4 +1,5 @@
#import <Foundation/Foundation.h>
#import
<Foundation/Foundation.h>
{{#imports}}#import "{{import}}.h"
{{/imports}}
#import "SWGObject.h"

View File

@ -1,4 +1,5 @@
#import <Foundation/Foundation.h>
#import
<Foundation/Foundation.h>
#import "SWGObject.h"
{{#imports}}#import "{{import}}.h"
{{/imports}}

View File

@ -2,8 +2,10 @@
#include "{{prefix}}Helpers.h"
#include "{{prefix}}ModelFactory.h"
#include <QJsonArray>
#include <QJsonDocument>
#include
<QJsonArray>
#include
<QJsonDocument>
namespace Swagger {
{{classname}}::{{classname}}() {}
@ -18,7 +20,8 @@ namespace Swagger {
{{#operations}}
{{#operation}}
void
{{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}
, {{/hasMore}}{{/allParams}}) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("{{path}}");
@ -95,7 +98,9 @@ void
{{#bodyParams}}
{{#isContainer}}
QJsonArray* {{paramName}}Array = new QJsonArray();
toJsonArray((QList<void*>*){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*"));
toJsonArray((QList
<void
*>*){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*{{paramName}}Array);
QByteArray bytes = doc.toJson();
@ -166,7 +171,8 @@ void
{{/isMapContainer}}
{{^isMapContainer}}
{{^returnTypeIsPrimitive}}QString json(worker->response);
{{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}")));
{{{returnType}}} output = static_cast<{{{returnType}}}>(create(json,
QString("{{{returnBaseType}}}")));
{{/returnTypeIsPrimitive}}
{{/isMapContainer}}
{{/isListContainer}}{{/returnType}}

View File

@ -6,7 +6,8 @@
{{#imports}}{{{import}}}
{{/imports}}
#include <QObject>
#include
<QObject>
namespace Swagger {
@ -21,7 +22,8 @@ public:
QString host;
QString basePath;
{{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}
, {{/hasMore}}{{/allParams}});
{{/operation}}{{/operations}}
private:
{{#operations}}{{#operation}}void {{nickname}}Callback (HttpRequestWorker * worker);

View File

@ -1,9 +1,12 @@
#include "SWGHelpers.h"
#include "SWGModelFactory.h"
#include "SWGObject.h"
#import <QDebug>
#import <QJsonArray>
#import <QJsonValue>
#import
<QDebug>
#import
<QJsonArray>
#import
<QJsonValue>
namespace Swagger {
@ -14,19 +17,27 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
return;
}
if(QStringLiteral("bool").compare(type) == 0) {
bool * val = static_cast<bool*>(value);
bool * val = static_cast
<bool
*>(value);
*val = obj.toBool();
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32 *val = static_cast<qint32*>(value);
qint32 *val = static_cast
<qint32
*>(value);
*val = obj.toInt();
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64 *val = static_cast<qint64*>(value);
qint64 *val = static_cast
<qint64
*>(value);
*val = obj.toVariant().toLongLong();
}
else if (QStringLiteral("QString").compare(type) == 0) {
QString **val = static_cast<QString**>(value);
QString **val = static_cast
<QString
**>(value);
if(val != NULL) {
if(!obj.isNull()) {
@ -51,14 +62,20 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
SWGObject * so = (SWGObject*)Swagger::create(type);
if(so != NULL) {
so->fromJsonObject(jsonObj);
SWGObject **val = static_cast<SWGObject**>(value);
SWGObject **val = static_cast
<SWGObject
**>(value);
delete *val;
*val = so;
}
}
else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) {
// list of values
QList<void*>* output = new QList<void*>();
QList
<void
*>* output = new QList
<void
*>();
QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) {
if(complexType.startsWith("SWG")) {
@ -88,7 +105,12 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
}
}
}
QList<void*> **val = static_cast<QList<void*>**>(value);
QList
<void
*> **val = static_cast
<QList
<void
*>**>(value);
delete *val;
*val = output;
}
@ -100,7 +122,8 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
return;
}
if(type.startsWith("SWG")) {
SWGObject *swgObject = reinterpret_cast<SWGObject *>(value);
SWGObject *swgObject = reinterpret_cast
<SWGObject *>(value);
if(swgObject != NULL) {
QJsonObject* o = (*swgObject).asJsonObject();
if(name != NULL) {
@ -116,25 +139,35 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
}
}
else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast<QString*>(value);
QString* str = static_cast
<QString
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast<qint32*>(value);
qint32* str = static_cast
<qint32
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast<qint64*>(value);
qint64* str = static_cast
<qint64
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast<bool*>(value);
bool* str = static_cast
<bool
*>(value);
output->insert(name, QJsonValue(*str));
}
}
void
toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType) {
toJsonArray(QList
<void
*>* value, QJsonArray* output, QString innerName, QString innerType) {
foreach(void* obj, *value) {
QJsonObject element;
@ -145,7 +178,9 @@ toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString
QString
stringValue(QString* value) {
QString* str = static_cast<QString*>(value);
QString* str = static_cast
<QString
*>(value);
return QString(*str);
}

View File

@ -1,11 +1,14 @@
#ifndef SWGHELPERS_H
#define SWGHELPERS_H
#include <QJsonValue>
#include
<QJsonValue>
namespace Swagger {
void setValue(void* value, QJsonValue obj, QString type, QString complexType);
void toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType);
void toJsonArray(QList
<void
*>* value, QJsonArray* output, QString innerName, QString innerType);
void toJsonValue(QString name, void* value, QJsonObject* output, QString type);
bool isCompatibleJsonValue(QString type);
QString stringValue(QString* value);

View File

@ -3,10 +3,14 @@
#include "SWGHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
#include
<QJsonDocument>
#include
<QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger {
@ -80,7 +84,8 @@ QJsonObject*
{{/isContainer}}{{#isContainer}}
QList<{{complexType}}*>* {{name}}List = {{name}};
QJsonArray {{name}}JsonArray;
toJsonArray((QList<void*>*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}");
toJsonArray((QList
<void*>*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}");
obj->insert("{{name}}", {{name}}JsonArray);
{{/isContainer}}

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