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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
@ -62,7 +62,8 @@
</goals> </goals>
<configuration> <configuration>
<transformers> <transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers> </transformers>
</configuration> </configuration>
</execution> </execution>

View File

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

View File

@ -1,10 +1,12 @@
package io.swagger.codegen.cmd; package io.swagger.codegen.cmd;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; import io.airlift.airline.Option;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import static java.util.ServiceLoader.load; import static java.util.ServiceLoader.load;
@Command(name = "config-help", description = "Config help for chosen lang") @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") description = "language to get config help for")
private String lang; 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 * 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 * @param name name of config, or full qualified class name in classpath
* @return config class * @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); 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; 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.CliOption;
import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts; import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.DefaultGenerator;
import io.swagger.models.Swagger; 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 io.swagger.parser.SwaggerParser;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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.") "Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
private String configFile; 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 @Override
public void run() { public void run() {
verbosed(verbose); verbosed(verbose);
@ -115,6 +137,7 @@ public class Generate implements Runnable {
/** /**
* If true parameter, adds system properties which enables debug mode in generator * If true parameter, adds system properties which enables debug mode in generator
*
* @param verbose - if true, enables debug mode * @param verbose - if true, enables debug mode
*/ */
private void verbosed(boolean verbose) { private void verbosed(boolean verbose) {
@ -132,25 +155,4 @@ public class Generate implements Runnable {
System.setProperty("debugOperations", ""); System.setProperty("debugOperations", "");
System.setProperty("debugSupportingFiles", ""); 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; package io.swagger.codegen.cmd;
import ch.lambdaj.collection.LambdaIterable; import ch.lambdaj.collection.LambdaIterable;
import io.swagger.codegen.CodegenConfig;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.swagger.codegen.CodegenConfig;
import static ch.lambdaj.Lambda.on; import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.collection.LambdaCollections.with; 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.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.SupportingFile;
import io.airlift.airline.Command; import io.airlift.airline.Command;
import io.airlift.airline.Option; 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.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -81,6 +81,7 @@ public class Meta implements Runnable {
/** /**
* Converter method to process supporting files: execute with mustache, * Converter method to process supporting files: execute with mustache,
* or simply copy to destination directory * or simply copy to destination directory
*
* @param targetDir - destination directory * @param targetDir - destination directory
* @param data - map with additional params needed to process templates * @param data - map with additional params needed to process templates
* @return converter object to pass to lambdaj * @return converter object to pass to lambdaj
@ -121,6 +122,7 @@ public class Meta implements Runnable {
/** /**
* Creates mustache loader for template using classpath loader * Creates mustache loader for template using classpath loader
*
* @param generator - class with reader getter * @param generator - class with reader getter
* @return loader for template * @return loader for template
*/ */
@ -135,6 +137,7 @@ public class Meta implements Runnable {
/** /**
* Converts package name to path on file system * Converts package name to path on file system
*
* @param packageName - package name to convert * @param packageName - package name to convert
* @return relative path * @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> <parent>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId> <artifactId>swagger-codegen-project</artifactId>

View File

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

View File

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

View File

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

View File

@ -1,29 +1,52 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.ClientOpts; import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.*;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue; import io.swagger.models.auth.AuthorizationValue;
import java.util.*;
import java.net.URLEncoder;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class ClientOptInput { public class ClientOptInput {
protected CodegenConfig config;
private ClientOpts opts; private ClientOpts opts;
private Swagger swagger; private Swagger swagger;
private List<AuthorizationValue> auths; private List<AuthorizationValue> auths;
protected CodegenConfig config;
public ClientOptInput swagger(Swagger swagger) { public ClientOptInput swagger(Swagger swagger) {
this.setSwagger(swagger); this.setSwagger(swagger);
return this; return this;
} }
public ClientOptInput opts(ClientOpts opts) { public ClientOptInput opts(ClientOpts opts) {
this.setOpts(opts); this.setOpts(opts);
return this; 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) { public void setAuth(String urlEncodedAuthString) {
List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>(); List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) { if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
@ -37,27 +60,7 @@ public class ClientOptInput {
} }
this.auths = auths; 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() { public List<AuthorizationValue> getAuthorizationValues() {
return auths; return auths;
} }
@ -65,24 +68,25 @@ public class ClientOptInput {
public CodegenConfig getConfig() { public CodegenConfig getConfig() {
return config; return config;
} }
public void setConfig(CodegenConfig config) { public void setConfig(CodegenConfig config) {
this.config = config; this.config = config;
} }
public void setOpts(ClientOpts opts) {
this.opts = opts;
}
public ClientOpts getOpts() { public ClientOpts getOpts() {
return opts; return opts;
} }
public void setSwagger(Swagger swagger) { public void setOpts(ClientOpts opts) {
this.swagger = swagger; this.opts = opts;
} }
@ApiModelProperty(dataType = "Object") @ApiModelProperty(dataType = "Object")
public Swagger getSwagger() { public Swagger getSwagger() {
return swagger; return swagger;
} }
public void setSwagger(Swagger swagger) {
this.swagger = swagger;
}
} }

View File

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

View File

@ -1,16 +1,19 @@
package io.swagger.codegen; package io.swagger.codegen;
import io.swagger.codegen.languages.*;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.AuthorizationValue;
import io.swagger.util.*;
import io.swagger.parser.SwaggerParser; 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.util.ArrayList;
import java.util.HashMap;
import java.io.File; import java.util.Iterator;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/** /**
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
@ -20,24 +23,12 @@ import java.util.*;
public class Codegen extends DefaultGenerator { public class Codegen extends DefaultGenerator {
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>(); static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
static String configString; 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:" + 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 -DdebugSwagger prints the swagger specification as interpreted by the codegen" +
"\n -DdebugModels prints models passed to the template engine" + "\n -DdebugModels prints models passed to the template engine" +
"\n -DdebugOperations prints operations passed to the template engine" + "\n -DdebugOperations prints operations passed to the template engine" +
"\n -DdebugSupportingFiles prints additional data passed to the template engine"; "\n -DdebugSupportingFiles prints additional data passed to the template engine";
public static void main(String[] args) { public static void main(String[] args) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -66,16 +57,18 @@ public class Codegen extends DefaultGenerator {
System.out.println(debugInfoOptions); System.out.println(debugInfoOptions);
return; return;
} }
if (cmd.hasOption("a")) if (cmd.hasOption("a")) {
clientOptInput.setAuth(cmd.getOptionValue("a")); clientOptInput.setAuth(cmd.getOptionValue("a"));
if (cmd.hasOption("l")) }
if (cmd.hasOption("l")) {
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
else { } else {
usage(options); usage(options);
return; return;
} }
if (cmd.hasOption("o")) if (cmd.hasOption("o")) {
clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
}
if (cmd.hasOption("h")) { if (cmd.hasOption("h")) {
if (cmd.hasOption("l")) { if (cmd.hasOption("l")) {
config = getConfig(String.valueOf(cmd.getOptionValue("l"))); config = getConfig(String.valueOf(cmd.getOptionValue("l")));
@ -88,12 +81,13 @@ public class Codegen extends DefaultGenerator {
usage(options); usage(options);
return; return;
} }
if (cmd.hasOption("i")) if (cmd.hasOption("i")) {
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); 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"))); clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t")));
} }
catch (Exception e) { } catch (Exception e) {
usage(options); usage(options);
return; return;
} }
@ -102,8 +96,7 @@ public class Codegen extends DefaultGenerator {
.opts(clientOpts) .opts(clientOpts)
.swagger(swagger); .swagger(swagger);
new Codegen().opts(clientOptInput).generate(); new Codegen().opts(clientOptInput).generate();
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -126,18 +119,30 @@ public class Codegen extends DefaultGenerator {
public static CodegenConfig getConfig(String name) { public static CodegenConfig getConfig(String name) {
if (configs.containsKey(name)) { if (configs.containsKey(name)) {
return configs.get(name); return configs.get(name);
} } else {
else {
// see if it's a class // see if it's a class
try { try {
System.out.println("loading class " + name); System.out.println("loading class " + name);
Class customClass = Class.forName(name); Class customClass = Class.forName(name);
System.out.println("loaded"); System.out.println("loaded");
return (CodegenConfig) customClass.newInstance(); return (CodegenConfig) customClass.newInstance();
} } catch (Exception e) {
catch (Exception e) {
throw new RuntimeException("can't load class " + name); 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; 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.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 { public interface CodegenConfig {
CodegenType getTag(); CodegenType getTag();
String getName(); String getName();
String getHelp(); String getHelp();
Map<String, Object> additionalProperties(); Map<String, Object> additionalProperties();
String apiPackage(); String apiPackage();
String apiFileFolder(); String apiFileFolder();
String fileSuffix(); String fileSuffix();
String outputFolder(); String outputFolder();
String templateDir(); String templateDir();
String modelFileFolder(); String modelFileFolder();
String modelPackage(); String modelPackage();
String toApiName(String name); String toApiName(String name);
String toApiVarName(String name); String toApiVarName(String name);
String toModelName(String name); String toModelName(String name);
String toParamName(String name); String toParamName(String name);
String escapeText(String text); String escapeText(String text);
String escapeReservedWord(String name); String escapeReservedWord(String name);
String getTypeDeclaration(Property p); String getTypeDeclaration(Property p);
String getTypeDeclaration(String name); String getTypeDeclaration(String name);
void processOpts(); void processOpts();
List<CliOption> cliOptions(); List<CliOption> cliOptions();
String generateExamplePath(String path, Operation operation); String generateExamplePath(String path, Operation operation);
Set<String> reservedWords(); Set<String> reservedWords();
List<SupportingFile> supportingFiles(); List<SupportingFile> supportingFiles();
void setOutputDir(String dir);
String getOutputDir(); String getOutputDir();
void setOutputDir(String dir);
CodegenModel fromModel(String name, Model model); CodegenModel fromModel(String name, Model model);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions); CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes); List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
Set<String> defaultIncludes(); Set<String> defaultIncludes();
Map<String, String> typeMapping(); Map<String, String> typeMapping();
Map<String, String> instantiationTypes(); Map<String, String> instantiationTypes();
Map<String, String> importMapping(); Map<String, String> importMapping();
Map<String, String> apiTemplateFiles(); Map<String, String> apiTemplateFiles();
Map<String, String> modelTemplateFiles(); Map<String, String> modelTemplateFiles();
void processSwagger(Swagger swagger); void processSwagger(Swagger swagger);
String toApiFilename(String name); String toApiFilename(String name);
String toModelFilename(String name); String toModelFilename(String name);
String toModelImport(String name); String toModelImport(String name);
String toApiImport(String name); String toApiImport(String name);
void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations); 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> postProcessModels(Map<String, Object> objs);
Map<String, Object> postProcessOperations(Map<String, Object> objs); Map<String, Object> postProcessOperations(Map<String, Object> objs);
Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs); Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs);
String apiFilename(String templateName, String tag); String apiFilename(String templateName, String tag);

View File

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

View File

@ -9,6 +9,7 @@ public final class CodegenModelFactory {
/** /**
* Configure a different implementation class. * Configure a different implementation class.
*
* @param type the type that shall be replaced * @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 * @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; 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 class CodegenOperation {
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
returnSimpleType, subresourceOperation, isMapContainer, isListContainer, returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
hasMore = Boolean.TRUE, isMultipart; hasMore = Boolean.TRUE, isMultipart;
public String path, operationId, returnType, httpMethod, returnBaseType, public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, notes, baseName, defaultResponse; returnContainer, summary, notes, baseName, defaultResponse;
public List<Map<String, String>> consumes, produces; public List<Map<String, String>> consumes, produces;
public CodegenParameter bodyParam; public CodegenParameter bodyParam;
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>(); public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
@ -22,7 +26,6 @@ public class CodegenOperation {
public List<CodegenSecurity> authMethods; public List<CodegenSecurity> authMethods;
public List<String> tags; public List<String> tags;
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>(); public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
public Set<String> imports = new HashSet<String>(); public Set<String> imports = new HashSet<String>();
public List<Map<String, String>> examples; public List<Map<String, String>> examples;
public ExternalDocs externalDocs; public ExternalDocs externalDocs;

View File

@ -1,18 +1,27 @@
package io.swagger.codegen; package io.swagger.codegen;
import java.util.*; import java.util.List;
import java.util.Map;
public class CodegenProperty { public class CodegenProperty {
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
name, min, max, defaultValue, baseType, containerType; 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; 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; 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; 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 example;
public String jsonSchema; public String jsonSchema;

View File

@ -5,10 +5,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class CodegenResponse { public class CodegenResponse {
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String code, message; public String code, message;
public Boolean hasMore; public Boolean hasMore;
public List<Map<String, Object>> examples; public List<Map<String, Object>> examples;
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
public String dataType, baseType, containerType; public String dataType, baseType, containerType;
public Boolean isDefault; public Boolean isDefault;
public Boolean simpleType; public Boolean simpleType;
@ -17,5 +17,8 @@ public class CodegenResponse {
public Boolean isListContainer; public Boolean isListContainer;
public Object schema; public Object schema;
public String jsonSchema; 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; 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.HashMap;
import java.util.Map;
public enum CodegenType { public enum CodegenType {
CLIENT, SERVER, DOCUMENTATION, OTHER; CLIENT, SERVER, DOCUMENTATION, OTHER;
private static Map<String, CodegenType> names = new HashMap<String, CodegenType>(); 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 @JsonCreator
public static CodegenType forValue(String value) { public static CodegenType forValue(String value) {
return names.get(value.toLowerCase()); return names.get(value.toLowerCase());
@ -25,10 +19,18 @@ public enum CodegenType {
@JsonValue @JsonValue
public String toValue() { public String toValue() {
for (Map.Entry<String, CodegenType> entry : names.entrySet()) { for (Map.Entry<String, CodegenType> entry : names.entrySet()) {
if (entry.getValue() == this) if (entry.getValue() == this) {
return entry.getKey(); return entry.getKey();
} }
}
return null; // or fail 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.Swagger;
import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.auth.SecuritySchemeDefinition;
import io.swagger.util.Json; import io.swagger.util.Json;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import java.io.File; import java.io.File;
import java.io.Reader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -267,8 +264,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
try { try {
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile); in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
} } catch (Exception e) {
catch (Exception e) {
// continue // continue
} }
if (in == null) { if (in == null) {
@ -276,14 +272,16 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
} }
File outputFile = new File(outputFilename); File outputFile = new File(outputFilename);
OutputStream out = new FileOutputStream(outputFile, false); OutputStream out = new FileOutputStream(outputFile, false);
if(in != null && out != null) if (in != null && out != null) {
IOUtils.copy(in, out); IOUtils.copy(in, out);
else { } else {
if(in == null) if (in == null) {
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input"); 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"); System.out.println("can't open " + outputFile + " for output");
} }
}
files.add(outputFile); files.add(outputFile);
} }
@ -306,8 +304,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
count += 1; count += 1;
if (count < mimeTypeList.size()) { if (count < mimeTypeList.size()) {
mediaType.put("hasMore", "true"); mediaType.put("hasMore", "true");
} } else {
else {
mediaType.put("hasMore", null); mediaType.put("hasMore", null);
} }
c.add(mediaType); c.add(mediaType);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,12 +1,5 @@
package io.swagger.codegen.languages; 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.CodegenConfig;
import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenParameter;
@ -15,46 +8,18 @@ import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; 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 { public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String apiVersion = "1.0.0"; protected String apiVersion = "1.0.0";
protected int serverPort = 8080; protected int serverPort = 8080;
protected String projectName = "swagger-server"; 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() { public NodeJSServerCodegen() {
super(); 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 @Override
public String toApiName(String name) { public String toApiName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "DefaultController"; return "DefaultController";
}
return initialCaps(name); return initialCaps(name);
} }
@ -142,6 +143,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
public String toApiFilename(String name) { public String toApiFilename(String name) {
return toApiName(name); return toApiName(name);
} }
/** /**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping * 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 * 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) { for (CodegenOperation operation : operations) {
operation.httpMethod = operation.httpMethod.toLowerCase(); operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams; List<CodegenParameter> params = operation.allParams;
if(params != null && params.size() == 0) if (params != null && params.size() == 0) {
operation.allParams = null; operation.allParams = null;
}
List<CodegenResponse> responses = operation.responses; List<CodegenResponse> responses = operation.responses;
if (responses != null) { if (responses != null) {
for (CodegenResponse resp : responses) { for (CodegenResponse resp : responses) {
if("0".equals(resp.code)) if ("0".equals(resp.code)) {
resp.code = "default"; resp.code = "default";
} }
} }
}
if (operation.examples != null && !operation.examples.isEmpty()) { if (operation.examples != null && !operation.examples.isEmpty()) {
// Leave application/json* items only // Leave application/json* items only
for (Iterator<Map<String, String>> it = operation.examples.iterator(); it.hasNext(); ) { for (Iterator<Map<String, String>> it = operation.examples.iterator(); it.hasNext(); ) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,52 +1,39 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.util.Json; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; 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.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 { public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
protected final String PREFIX = "SWG";
protected Set<String> foundationClasses = new HashSet<String>(); protected Set<String> foundationClasses = new HashSet<String>();
// source folder where to write the files // source folder where to write the files
protected String sourceFolder = "client"; protected String sourceFolder = "client";
protected String apiVersion = "1.0.0"; protected String apiVersion = "1.0.0";
protected final String PREFIX = "SWG";
protected Map<String, String> namespaces = new HashMap<String, String>(); protected Map<String, String> namespaces = new HashMap<String, String>();
protected Set<String> systemIncludes = new HashSet<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() { public Qt5CPPGenerator() {
super(); super();
@ -145,12 +132,41 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
systemIncludes.add("QList"); 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 @Override
public String toModelImport(String name) { public String toModelImport(String name) {
if (namespaces.containsKey(name)) { if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";"; return "using " + namespaces.get(name) + ";";
} } else if (systemIncludes.contains(name)) {
else if(systemIncludes.contains(name)) {
return "#include <" + name + ">"; return "#include <" + name + ">";
} }
return "#include \"" + name + ".h\""; return "#include \"" + name + ".h\"";
@ -208,46 +224,45 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*"; return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
} } else if (p instanceof MapProperty) {
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties(); Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*"; return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
} }
if(foundationClasses.contains(swaggerType)) if (foundationClasses.contains(swaggerType)) {
return swaggerType + "*"; return swaggerType + "*";
else if(languageSpecificPrimitives.contains(swaggerType)) } else if (languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType); return toModelName(swaggerType);
else } else {
return swaggerType + "*"; return swaggerType + "*";
} }
}
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
if(p instanceof StringProperty) if (p instanceof StringProperty) {
return "new QString(\"\")"; return "new QString(\"\")";
else if (p instanceof BooleanProperty) } else if (p instanceof BooleanProperty) {
return "false"; return "false";
else if(p instanceof DateProperty) } else if (p instanceof DateProperty) {
return "NULL"; return "NULL";
else if(p instanceof DateTimeProperty) } else if (p instanceof DateTimeProperty) {
return "NULL"; return "NULL";
else if (p instanceof DoubleProperty) } else if (p instanceof DoubleProperty) {
return "0.0"; return "0.0";
else if (p instanceof FloatProperty) } else if (p instanceof FloatProperty) {
return "0.0f"; return "0.0f";
else if (p instanceof IntegerProperty) } else if (p instanceof IntegerProperty) {
return "0"; return "0";
else if (p instanceof LongProperty) } else if (p instanceof LongProperty) {
return "0L"; return "0L";
else if (p instanceof DecimalProperty) } else if (p instanceof DecimalProperty) {
return "0.0"; return "0.0";
else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return "new QMap<QString, " + inner + ">()"; return "new QMap<QString, " + inner + ">()";
} } else if (p instanceof ArrayProperty) {
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems()); String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) { if (!languageSpecificPrimitives.contains(inner)) {
@ -277,13 +292,15 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type)) if (languageSpecificPrimitives.contains(type)) {
return toModelName(type); return toModelName(type);
if(foundationClasses.contains(type)) }
if (foundationClasses.contains(type)) {
return type; return type;
} }
else } else {
type = swaggerType; type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
@ -295,8 +312,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
defaultIncludes.contains(type) || defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) { languageSpecificPrimitives.contains(type)) {
return type; return type;
} } else {
else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,11 +1,20 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenOperation;
import io.swagger.util.Json; 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.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 { public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client"; 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 artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; 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() { public ScalatraServerCodegen() {
super(); super();
outputFolder = "generated-code/scalatra"; outputFolder = "generated-code/scalatra";
@ -121,6 +118,18 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
importMapping.put("LocalTime", "org.joda.time.LocalTime"); 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 @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; return "_" + name;
@ -152,8 +161,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} } else if (p instanceof MapProperty) {
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties(); Property inner = mp.getAdditionalProperties();
@ -168,11 +176,12 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type)) if (languageSpecificPrimitives.contains(type)) {
return toModelName(type); return toModelName(type);
} }
else } else {
type = swaggerType; type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
} }

View File

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

View File

@ -1,9 +1,10 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenConfig;
import io.swagger.models.properties.*; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import java.util.*;
import java.io.File; import java.io.File;
public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { 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 artifactVersion = "1.0.0";
protected String sourceFolder = "docs"; 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() { public StaticDocCodegen() {
super(); super();
outputFolder = "docs"; outputFolder = "docs";
@ -60,6 +49,18 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("map", "HashMap"); 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 @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; return "_" + name;

View File

@ -1,12 +1,20 @@
package io.swagger.codegen.languages; 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.Operation;
import io.swagger.models.properties.*; import io.swagger.models.properties.ArrayProperty;
import io.swagger.util.Json; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.util.*; import java.util.ArrayList;
import java.io.File; import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
private static final String ALL_OPERATIONS = ""; 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 artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala"; 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() { public StaticHtmlGenerator() {
super(); super();
outputFolder = "docs"; outputFolder = "docs";
@ -53,14 +49,25 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
importMapping = new HashMap<String, String>(); 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 @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems(); Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
} } else if (p instanceof MapProperty) {
else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p; MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties(); Property inner = mp.getAdditionalProperties();

View File

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

View File

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

View File

@ -3,17 +3,29 @@ package io.swagger.codegen.languages;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterators; import com.google.common.collect.Iterators;
import com.google.common.collect.Lists; 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.Model;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.HeaderParameter;
import io.swagger.models.parameters.Parameter; 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 org.apache.commons.lang.StringUtils;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.*;
import java.io.File; 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.Matcher;
import java.util.regex.Pattern; 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_]+\\}"); private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
protected String sourceFolder = "Classes/Swaggers"; 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() { public SwiftGenerator() {
super(); super();
outputFolder = "generated-code/swift"; outputFolder = "generated-code/swift";
@ -119,6 +119,45 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
importMapping = new HashMap<String, String>(); 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 @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name return "_" + name; // add an underscore to the name
@ -154,10 +193,12 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) if (languageSpecificPrimitives.contains(type)) {
return toModelName(type); return toModelName(type);
} else }
} else {
type = swaggerType; type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
@ -202,8 +243,9 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
@Override @Override
public String toApiName(String name) { public String toApiName(String name) {
if(name.length() == 0) if (name.length() == 0) {
return "DefaultAPI"; return "DefaultAPI";
}
return initialCaps(name) + "API"; return initialCaps(name) + "API";
} }
@ -220,31 +262,4 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
operation.setParameters(parameters); operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions); 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; package io.swagger.codegen.languages;
import io.swagger.util.Json; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.*; import io.swagger.codegen.CodegenType;
import io.swagger.models.properties.*; 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.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 { public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
protected static String PREFIX = "Sami";
protected Set<String> foundationClasses = new HashSet<String>(); protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client"; protected String sourceFolder = "client";
protected static String PREFIX = "Sami";
protected Map<String, String> namespaces = new HashMap<String, String>(); 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() { public TizenClientCodegen() {
super(); super();
outputFolder = "generated-code/tizen"; 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")); 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 @Override
public String toInstantiationType(Property p) { public String toInstantiationType(Property p) {
if (p instanceof MapProperty) { if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return instantiationTypes.get("map"); return instantiationTypes.get("map");
} } else if (p instanceof ArrayProperty) {
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems()); String inner = getSwaggerType(ap.getItems());
return instantiationTypes.get("array"); return instantiationTypes.get("array");
} } else {
else
return null; return null;
} }
}
@Override @Override
public String getTypeDeclaration(String name) { public String getTypeDeclaration(String name) {
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
return name; return name;
else } else {
return name + "*"; return name + "*";
} }
}
@Override @Override
public String getSwaggerType(Property p) { public String getSwaggerType(Property p) {
@ -132,22 +150,24 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
return toModelName(type); return toModelName(type);
} }
else } else {
type = swaggerType; type = swaggerType;
}
return toModelName(type); return toModelName(type);
} }
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p); String swaggerType = getSwaggerType(p);
if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
return toModelName(swaggerType); return toModelName(swaggerType);
else } else {
return swaggerType + "*"; return swaggerType + "*";
} }
}
@Override @Override
public String toModelName(String type) { public String toModelName(String type) {
@ -158,8 +178,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
defaultIncludes.contains(type) || defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) { languageSpecificPrimitives.contains(type)) {
return type; return type;
} } else {
else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
} }
} }
@ -174,30 +193,29 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
if(p instanceof StringProperty) if (p instanceof StringProperty) {
return "new String()"; return "new String()";
else if (p instanceof BooleanProperty) } else if (p instanceof BooleanProperty) {
return "new Boolean(false)"; return "new Boolean(false)";
else if(p instanceof DateProperty) } else if (p instanceof DateProperty) {
return "new DateTime()"; return "new DateTime()";
else if(p instanceof DateTimeProperty) } else if (p instanceof DateTimeProperty) {
return "new DateTime()"; return "new DateTime()";
else if (p instanceof DoubleProperty) } else if (p instanceof DoubleProperty) {
return "new Double()"; return "new Double()";
else if (p instanceof FloatProperty) } else if (p instanceof FloatProperty) {
return "new Float()"; return "new Float()";
else if (p instanceof IntegerProperty) } else if (p instanceof IntegerProperty) {
return "new Integer()"; return "new Integer()";
else if (p instanceof LongProperty) } else if (p instanceof LongProperty) {
return "new Long()"; return "new Long()";
else if (p instanceof DecimalProperty) } else if (p instanceof DecimalProperty) {
return "new Long()"; return "new Long()";
else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p; MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties()); String inner = getSwaggerType(ap.getAdditionalProperties());
return "new HashMap()"; return "new HashMap()";
} } else if (p instanceof ArrayProperty) {
else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p; ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems()); String inner = getSwaggerType(ap.getItems());
return "new ArrayList()"; return "new ArrayList()";
@ -248,8 +266,9 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return$ // 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"); throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
// add_pet_by_id => addPetById // add_pet_by_id => addPetById
return camelize(operationId, true); return camelize(operationId, true);

View File

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

View File

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

View File

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

View File

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

View File

@ -39,7 +39,9 @@ public class ApiKeyAuth implements Authentication {
} }
@Override @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; String value;
if (apiKeyPrefix != null) { if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey; value = apiKeyPrefix + " " + apiKey;

View File

@ -4,5 +4,7 @@ import java.util.Map;
public interface Authentication { public interface Authentication {
/** Apply authentication settings to header and query params. */ /** 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 @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); String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
try { try {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); 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 { public class OAuth implements Authentication {
@Override @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 // TODO: support oauth
} }
} }

View File

@ -77,7 +77,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
src/main/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -89,7 +90,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/test/java</source> <source>
src/test/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>
1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </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> <modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId> <groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId> <artifactId>{{artifactId}}</artifactId>
@ -75,7 +76,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/gen/java</source> <source>
src/gen/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" <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" 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"> >
<servlet> <servlet>
<servlet-name>jersey</servlet-name> <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> <modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId> <groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId> <artifactId>{{artifactId}}</artifactId>
@ -31,7 +32,8 @@
<version>${jetty-version}</version> <version>${jetty-version}</version>
<configuration> <configuration>
<webAppConfig> <webAppConfig>
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath> <contextPath>{{^contextPath}}
/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
</webAppConfig> </webAppConfig>
<webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory> <webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory>
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml> <webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
@ -95,7 +97,8 @@
<outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory> <outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
<resources> <resources>
<resource> <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> <filtering>true</filtering>
<excludes> <excludes>
<exclude>index.html</exclude> <exclude>index.html</exclude>

View File

@ -64,7 +64,8 @@ object ApiInvoker {
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
invoker.execute(request) 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] 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] { extends Serializer[E#Value] {
import JsonDSL._ 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}}; String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map
<String, String> queryParams = new HashMap
<String, String>();
// header params // header params
Map<String, String> headerParams = new HashMap<String, String>(); Map
<String, String> headerParams = new HashMap
<String, String>();
// form params // form params
Map<String, String> formParams = new HashMap<String, String>(); Map
<String, String> formParams = new HashMap
<String, String>();
{{#queryParams}}if ({{paramName}} != null) {{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));

View File

@ -53,7 +53,9 @@ import com.google.gson.JsonParseException;
public class ApiInvoker { public class ApiInvoker {
private static ApiInvoker INSTANCE = new 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; 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); HttpClient client = getClient(host);
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
@ -200,7 +205,9 @@ public class ApiInvoker {
} }
String url = host + path + b.toString(); 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()) { for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key)); headers.put(key, headerParams.get(key));

View File

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

View File

@ -77,7 +77,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
src/main/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -89,7 +90,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/test/java</source> <source>
src/test/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>
1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </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 * Reserved words. Override this with reserved words specific to your language
*/ */
reservedWords = new HashSet<String> ( reservedWords = new HashSet
<String> (
Arrays.asList( Arrays.asList(
"sample1", // replace with static values "sample1", // replace with static values
"sample2") "sample2")
@ -112,7 +113,8 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig
* Language Specific Primitives. These types will not trigger imports by * Language Specific Primitives. These types will not trigger imports by
* the client generator * the client generator
*/ */
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet
<String>(
Arrays.asList( Arrays.asList(
"Type1", // replace these with your types "Type1", // replace these with your types
"Type2") "Type2")

View File

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

View File

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

View File

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

View File

@ -7,40 +7,61 @@ using System.Text;
using {{invokerPackage}}; using {{invokerPackage}};
namespace {{invokerPackage}} { namespace {{invokerPackage}} {
/// <summary> ///
<summary>
/// Represents a set of configuration settings /// Represents a set of configuration settings
/// </summary> ///
</summary>
public class Configuration{ public class Configuration{
/// <summary> ///
<summary>
/// Gets or sets the API client. This is the default API client for making HTTP calls. /// 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(); public static ApiClient apiClient = new ApiClient();
/// <summary> ///
<summary>
/// Gets or sets the username (HTTP basic authentication) /// Gets or sets the username (HTTP basic authentication)
/// </summary> ///
/// <value>The username.</value> </summary>
///
<value>The username.</value>
public static String username { get; set; } public static String username { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the password (HTTP basic authentication) /// Gets or sets the password (HTTP basic authentication)
/// </summary> ///
/// <value>The password.</value> </summary>
///
<value>The password.</value>
public static String password { get; set; } public static String password { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the API key based on the authentication name /// Gets or sets the API key based on the authentication name
/// </summary> ///
/// <value>The API key.</value> </summary>
public static Dictionary<String, String> apiKey = new Dictionary<String, String>(); ///
<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 /// 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> </summary>
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>(); ///
<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}} { public interface I{{classname}} {
{{#operation}} {{#operation}}
/// <summary> ///
<summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> ///
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}} </summary>
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns> {{#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}}); {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
/// <summary> ///
<summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> ///
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}} </summary>
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns> {{#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}}); {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}} {{/operation}}
} }
/// <summary> ///
<summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// </summary> ///
</summary>
public class {{classname}} : I{{classname}} { public class {{classname}} : I{{classname}} {
/// <summary> ///
/// Initializes a new instance of the <see cref="{{classname}}"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="apiClient"> an instance of ApiClient (optional) <see cref="{{classname}}"/>
/// <returns></returns> class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public {{classname}}(ApiClient apiClient = null) { public {{classname}}(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient; this.apiClient = Configuration.apiClient;
@ -46,44 +62,62 @@ namespace {{package}} {
} }
} }
/// <summary> ///
/// Initializes a new instance of the <see cref="{{classname}}"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <returns></returns> <see cref="{{classname}}"/>
class.
///
</summary>
///
<returns></returns>
public {{classname}}(String basePath) public {{classname}}(String basePath)
{ {
this.apiClient = new ApiClient(basePath); this.apiClient = new ApiClient(basePath);
} }
/// <summary> ///
<summary>
/// Sets the base path of the API client. /// 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) { public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath; this.apiClient.basePath = basePath;
} }
/// <summary> ///
<summary>
/// Gets the base path of the API client. /// 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) { public String GetBasePath(String basePath) {
return this.apiClient.basePath; return this.apiClient.basePath;
} }
/// <summary> ///
<summary>
/// Gets or sets the API client. /// Gets or sets the API client.
/// </summary> ///
/// <value>The API client</value> </summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;} public ApiClient apiClient {get; set;}
{{#operation}} {{#operation}}
/// <summary> ///
<summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> ///
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}} </summary>
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns> {{#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}}) { public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
@ -96,10 +130,14 @@ namespace {{package}} {
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}}));
{{/pathParams}} {{/pathParams}}
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter
@ -124,11 +162,15 @@ namespace {{package}} {
return;{{/returnType}} return;{{/returnType}}
} }
/// <summary> ///
<summary>
/// {{summary}} {{notes}} /// {{summary}} {{notes}}
/// </summary> ///
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>{{/allParams}} </summary>
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns> {{#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}}) { public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
@ -141,10 +183,14 @@ namespace {{package}} {
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}}));
{{/pathParams}} {{/pathParams}}
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter

View File

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

View File

@ -1,8 +1,4 @@
package io.swagger.event { 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. * 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 * 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 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 * The Response object which contains response info
*/ */
@ -28,9 +27,5 @@ public class ApiClientEvent extends Event{
* Any additional info * Any additional info
*/ */
public var message:String; 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 package io.swagger.exception {
{ public class ApiError extends Error {
public class ApiError extends Error public function ApiError(id:* = 0, message:* = "") {
{
public function ApiError(id:*=0, message:*="")
{
super(message, id); super(message, id);
} }
} }

View File

@ -1,7 +1,5 @@
package io.swagger.exception package io.swagger.exception {
{ public class ApiErrorCodes {
public class ApiErrorCodes
{
/** /**
* System exception. * 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 { package io.swagger.common {
import io.swagger.common.ApiUserCredentials;
/** /**
* @private * @private
* Internal class for the Rest client * Internal class for the Rest client

View File

@ -5,41 +5,6 @@ package io.swagger.common {
* *
*/ */
public class ApiUserCredentials { 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 * Constructor of ApiUserCredentials
* @param apiToken An apitoken that is passed along with the requests * @param apiToken An apitoken that is passed along with the requests
@ -58,6 +23,37 @@ public class ApiUserCredentials {
this.apiProxyServerUrl = apiProxyServerUrl; this.apiProxyServerUrl = apiProxyServerUrl;
this.proxyPath = proxyPath; 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 package io.swagger.common {
{ public interface ListWrapper {
public interface ListWrapper
{
function getList():Array; function getList():Array;

View File

@ -6,33 +6,8 @@ package io.swagger.event {
*/ */
public class Response { 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: "; 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 { private static function getFriendlyMessage(errorMessage:String):String {
var result:String = errorMessage; var result:String = errorMessage;
if (errorMessage == null) if (errorMessage == null)
@ -49,6 +24,28 @@ public class Response {
return result; 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 { public function toString():String {
return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")"; return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")";
} }

View File

@ -1,50 +1,5 @@
package io.swagger.common package io.swagger.common {
{ public class SwaggerApi extends EventDispatcher {
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();
}
/** /**
* Method for returning the path value * Method for returning the path value
@ -71,5 +26,38 @@ package io.swagger.common
return objects.join(","); 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 package io.swagger.common {
{ public class XMLWriter {
public class XMLWriter public function XMLWriter() {
{
public var xml:XML;
public function XMLWriter()
{
xml = <obj/>; xml = <obj/>;
} }
public var xml:XML;
public function reset():void { public function reset():void {
xml = new XML(); 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> </head>
<body> <body>
<h1>{{{appName}}}</h1> <h1>{{{appName}}}</h1>
<div class="app-desc">{{{appDescription}}} for {{partner}}</div> <div class="app-desc">{{{appDescription}}} for {{partner}}</div>
{{#infoUrl}}<div class="app-desc">More information: <a href="{{{infoUrl}}}">{{{infoUrl}}}</a></div>{{/infoUrl}} {{#infoUrl}}
{{#infoEmail}}<div class="app-desc">Contact Info: <a href="{{{infoEmail}}}">{{{infoEmail}}}</a></div>{{/infoEmail}} <div class="app-desc">More information: <a href="{{{infoUrl}}}">{{{infoUrl}}}</a></div>{{/infoUrl}}
{{#version}}<div class="app-desc">Version: {{{version}}}</div>{{/version}} {{#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-info">{{{licenseInfo}}}</div>
<div class="license-url">{{{licenseUrl}}}</div> <div class="license-url">{{{licenseUrl}}}</div>
<h2>Access</h2> <h2>Access</h2>
<div class="method-summary">Customize this message as you see fit!</div> <div class="method-summary">Customize this message as you see fit!</div>
<h2>Methods</h2> <h2>Methods</h2>
{{#apiInfo}} {{#apiInfo}}
{{#apis}} {{#apis}}
{{#operations}}{{#operation}} {{#operations}}{{#operation}}
<div class="method"> <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-tags"> {{#tags}}<span class="method-tag">{{this}}</span>{{/tags}}</div>
<div class="method-summary"><span class="nickname">{{nickname}}</span> {{summary}}</div> <div class="method-summary"><span class="nickname">{{nickname}}</span> {{summary}}</div>
<div class="method-notes">{{notes}}</div> <div class="method-notes">{{notes}}</div>
<h3 class="field-label">Parameters</h3> <h3 class="field-label">Parameters</h3>
<div class="field-items"> <div class="field-items">
{{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}}
{{/allParams}} {{/allParams}}
</div> <!-- field-items --> </div>
<!-- field-items -->
<h3 class="field-label">Return type</h3> <h3 class="field-label">Return type</h3>
<div class="return-type"><a href="#{{returnContainer}}">{{{returnType}}}</a></div> <div class="return-type"><a href="#{{returnContainer}}">{{{returnType}}}</a></div>
{{#examples}} {{#examples}}
<h3 class="field-label">Example data</h3> <h3 class="field-label">Example data</h3>
<div class="example-data-content-type">Content-Type: {{{contentType}}}</div> <div class="example-data-content-type">Content-Type: {{{contentType}}}</div>
<pre class="example"><code>{{example}}</code></pre> <pre class="example"><code>{{example}}</code></pre>
{{/examples}} {{/examples}}
</div> <!-- method --> </div>
<!-- method -->
<hr> <hr>
{{/operation}}{{/operations}} {{/operation}}{{/operations}}
{{/apis}}{{/apiInfo}} {{/apis}}{{/apiInfo}}
@ -47,10 +58,14 @@
{{#model}} {{#model}}
<div class="model"> <div class="model">
<h3 class="field-label"><a name="{{classname}}">{{classname}}</a></h3> <h3 class="field-label"><a name="{{classname}}">{{classname}}</a></h3>
<div class="field-items"> <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}} {{/vars}}
</div> <!-- field-items --> </div>
<!-- field-items -->
</div> </div>
{{/model}} {{/model}}
{{/models}} {{/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 @interface SWGConfiguration : NSObject

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,14 @@
#ifndef SWGHELPERS_H #ifndef SWGHELPERS_H
#define SWGHELPERS_H #define SWGHELPERS_H
#include <QJsonValue> #include
<QJsonValue>
namespace Swagger { namespace Swagger {
void setValue(void* value, QJsonValue obj, QString type, QString complexType); 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); void toJsonValue(QString name, void* value, QJsonObject* output, QString type);
bool isCompatibleJsonValue(QString type); bool isCompatibleJsonValue(QString type);
QString stringValue(QString* value); QString stringValue(QString* value);

View File

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

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