mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-07-03 22:20:56 +00:00
Code reformatting
This commit is contained in:
parent
22d7db2cb4
commit
1c2d0656b0
@ -1,4 +1,4 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>io.swagger</groupId>
|
||||
@ -62,7 +62,8 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
@ -1,17 +1,17 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.airlift.airline.Cli;
|
||||
import io.airlift.airline.Help;
|
||||
import io.swagger.codegen.cmd.ConfigHelp;
|
||||
import io.swagger.codegen.cmd.Generate;
|
||||
import io.swagger.codegen.cmd.Langs;
|
||||
import io.swagger.codegen.cmd.Meta;
|
||||
import io.airlift.airline.Cli;
|
||||
import io.airlift.airline.Help;
|
||||
|
||||
/**
|
||||
* User: lanwen
|
||||
* Date: 24.03.15
|
||||
* Time: 17:56
|
||||
*
|
||||
* <p/>
|
||||
* Command line interface for swagger codegen
|
||||
* use `swagger-codegen-cli.jar help` for more info
|
||||
*
|
||||
|
@ -1,10 +1,12 @@
|
||||
package io.swagger.codegen.cmd;
|
||||
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
import static java.util.ServiceLoader.load;
|
||||
|
||||
@Command(name = "config-help", description = "Config help for chosen lang")
|
||||
@ -14,20 +16,9 @@ public class ConfigHelp implements Runnable {
|
||||
description = "language to get config help for")
|
||||
private String lang;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println();
|
||||
CodegenConfig config = forName(lang);
|
||||
System.out.println("CONFIG OPTIONS");
|
||||
for (CliOption langCliOption : config.cliOptions()) {
|
||||
System.out.println("\t" + langCliOption.getOpt());
|
||||
System.out.println("\t " + langCliOption.getDescription());
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to load config class with SPI first, then with class name directly from classpath
|
||||
*
|
||||
* @param name name of config, or full qualified class name in classpath
|
||||
* @return config class
|
||||
*/
|
||||
@ -46,4 +37,16 @@ public class ConfigHelp implements Runnable {
|
||||
throw new RuntimeException("Can't load config class with name ".concat(name), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println();
|
||||
CodegenConfig config = forName(lang);
|
||||
System.out.println("CONFIG OPTIONS");
|
||||
for (CliOption langCliOption : config.cliOptions()) {
|
||||
System.out.println("\t" + langCliOption.getOpt());
|
||||
System.out.println("\t " + langCliOption.getDescription());
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,15 @@
|
||||
package io.swagger.codegen.cmd;
|
||||
|
||||
import config.Config;
|
||||
import config.ConfigParser;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.ClientOptInput;
|
||||
import io.swagger.codegen.ClientOpts;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.DefaultGenerator;
|
||||
import io.swagger.models.Swagger;
|
||||
import config.Config;
|
||||
import config.ConfigParser;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import io.swagger.parser.SwaggerParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -57,15 +57,37 @@ public class Generate implements Runnable {
|
||||
"Pass in a URL-encoded string of name:header with a comma separating multiple values")
|
||||
private String auth;
|
||||
|
||||
@Option( name= {"-D"}, title = "system properties", description = "sets specified system properties in " +
|
||||
@Option(name = {"-D"}, title = "system properties", description = "sets specified system properties in " +
|
||||
"the format of name=value,name=value")
|
||||
private String systemProperties;
|
||||
|
||||
@Option( name= {"-c", "--config"}, title = "configuration file", description = "Path to json configuration file. " +
|
||||
@Option(name = {"-c", "--config"}, title = "configuration file", description = "Path to json configuration file. " +
|
||||
"File content should be in a json format {\"optionKey\":\"optionValue\", \"optionKey1\":\"optionValue1\"...} " +
|
||||
"Supported options can be different for each language. Run config-help -l {lang} command for language specific config options.")
|
||||
private String configFile;
|
||||
|
||||
/**
|
||||
* Tries to load config class with SPI first, then with class name directly from classpath
|
||||
*
|
||||
* @param name name of config, or full qualified class name in classpath
|
||||
* @return config class
|
||||
*/
|
||||
private static CodegenConfig forName(String name) {
|
||||
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
|
||||
for (CodegenConfig config : loader) {
|
||||
if (config.getName().equals(name)) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
// else try to load directly
|
||||
try {
|
||||
return (CodegenConfig) Class.forName(name).newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Can't load config class with name ".concat(name), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
verbosed(verbose);
|
||||
@ -85,7 +107,7 @@ public class Generate implements Runnable {
|
||||
config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath());
|
||||
}
|
||||
|
||||
if(null != configFile){
|
||||
if (null != configFile) {
|
||||
Config genConfig = ConfigParser.read(configFile);
|
||||
if (null != genConfig) {
|
||||
for (CliOption langCliOption : config.cliOptions()) {
|
||||
@ -103,11 +125,11 @@ public class Generate implements Runnable {
|
||||
}
|
||||
|
||||
private void setSystemProperties() {
|
||||
if( systemProperties != null && systemProperties.length() > 0 ){
|
||||
for( String property : systemProperties.split(",")) {
|
||||
if (systemProperties != null && systemProperties.length() > 0) {
|
||||
for (String property : systemProperties.split(",")) {
|
||||
int ix = property.indexOf('=');
|
||||
if( ix > 0 && ix < property.length()-1 ){
|
||||
System.setProperty( property.substring(0, ix), property.substring(ix+1) );
|
||||
if (ix > 0 && ix < property.length() - 1) {
|
||||
System.setProperty(property.substring(0, ix), property.substring(ix + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -115,6 +137,7 @@ public class Generate implements Runnable {
|
||||
|
||||
/**
|
||||
* If true parameter, adds system properties which enables debug mode in generator
|
||||
*
|
||||
* @param verbose - if true, enables debug mode
|
||||
*/
|
||||
private void verbosed(boolean verbose) {
|
||||
@ -132,25 +155,4 @@ public class Generate implements Runnable {
|
||||
System.setProperty("debugOperations", "");
|
||||
System.setProperty("debugSupportingFiles", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to load config class with SPI first, then with class name directly from classpath
|
||||
* @param name name of config, or full qualified class name in classpath
|
||||
* @return config class
|
||||
*/
|
||||
private static CodegenConfig forName(String name) {
|
||||
ServiceLoader<CodegenConfig> loader = load(CodegenConfig.class);
|
||||
for (CodegenConfig config : loader) {
|
||||
if (config.getName().equals(name)) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
// else try to load directly
|
||||
try {
|
||||
return (CodegenConfig) Class.forName(name).newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Can't load config class with name ".concat(name), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
package io.swagger.codegen.cmd;
|
||||
|
||||
import ch.lambdaj.collection.LambdaIterable;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.airlift.airline.Command;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
|
||||
import static ch.lambdaj.Lambda.on;
|
||||
import static ch.lambdaj.collection.LambdaCollections.with;
|
||||
|
@ -4,10 +4,10 @@ import ch.lambdaj.function.convert.Converter;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import io.swagger.codegen.DefaultGenerator;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.airlift.airline.Command;
|
||||
import io.airlift.airline.Option;
|
||||
import io.swagger.codegen.DefaultGenerator;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
@ -81,6 +81,7 @@ public class Meta implements Runnable {
|
||||
/**
|
||||
* Converter method to process supporting files: execute with mustache,
|
||||
* or simply copy to destination directory
|
||||
*
|
||||
* @param targetDir - destination directory
|
||||
* @param data - map with additional params needed to process templates
|
||||
* @return converter object to pass to lambdaj
|
||||
@ -121,6 +122,7 @@ public class Meta implements Runnable {
|
||||
|
||||
/**
|
||||
* Creates mustache loader for template using classpath loader
|
||||
*
|
||||
* @param generator - class with reader getter
|
||||
* @return loader for template
|
||||
*/
|
||||
@ -135,6 +137,7 @@ public class Meta implements Runnable {
|
||||
|
||||
/**
|
||||
* Converts package name to path on file system
|
||||
*
|
||||
* @param packageName - package name to convert
|
||||
* @return relative path
|
||||
*/
|
||||
|
@ -7,6 +7,6 @@
|
||||
</appender>
|
||||
<logger name="io.swagger" level="debug"/>
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT" />
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
||||
|
@ -1,4 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-codegen-project</artifactId>
|
||||
@ -244,7 +245,7 @@
|
||||
<link>http://java.sun.com/javaee/5/docs/api</link>
|
||||
<link>http://java.sun.com/j2se/1.5.0/docs/api</link>
|
||||
</links>
|
||||
<excludePackageNames />
|
||||
<excludePackageNames/>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
@ -1,6 +1,7 @@
|
||||
package config;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@ -19,15 +20,15 @@ public class Config {
|
||||
return ImmutableMap.copyOf(options);
|
||||
}
|
||||
|
||||
public boolean hasOption(String opt){
|
||||
public boolean hasOption(String opt) {
|
||||
return options.containsKey(opt);
|
||||
}
|
||||
|
||||
public String getOption(String opt){
|
||||
public String getOption(String opt) {
|
||||
return options.get(opt);
|
||||
}
|
||||
|
||||
public void setOption(String opt, String value){
|
||||
public void setOption(String opt, String value) {
|
||||
options.put(opt, value);
|
||||
}
|
||||
}
|
||||
|
@ -2,6 +2,7 @@ package config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
@ -23,15 +24,13 @@ public class ConfigParser {
|
||||
while (optionNodes.hasNext()) {
|
||||
Map.Entry<String, JsonNode> optionNode = (Map.Entry<String, JsonNode>) optionNodes.next();
|
||||
|
||||
if(optionNode.getValue().isValueNode()){
|
||||
if (optionNode.getValue().isValueNode()) {
|
||||
config.setOption(optionNode.getKey(), optionNode.getValue().asText());
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
System.out.println("omitting non-value node " + optionNode.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
@ -1,9 +1,16 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import com.samskivert.mustache.*;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.util.regex.Pattern;
|
||||
import java.io.*;
|
||||
|
||||
public abstract class AbstractGenerator {
|
||||
|
||||
@ -11,7 +18,7 @@ public abstract class AbstractGenerator {
|
||||
System.out.println("writing file " + filename);
|
||||
File output = new File(filename);
|
||||
|
||||
if(output.getParent() != null && !new File(output.getParent()).exists()) {
|
||||
if (output.getParent() != null && !new File(output.getParent()).exists()) {
|
||||
File parent = new File(output.getParent());
|
||||
parent.mkdirs();
|
||||
}
|
||||
@ -24,37 +31,39 @@ public abstract class AbstractGenerator {
|
||||
}
|
||||
|
||||
public String readTemplate(String name) {
|
||||
try{
|
||||
try {
|
||||
Reader reader = getTemplateReader(name);
|
||||
if(reader == null)
|
||||
if (reader == null) {
|
||||
throw new RuntimeException("no file found");
|
||||
}
|
||||
java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A");
|
||||
return s.hasNext() ? s.next() : "";
|
||||
}
|
||||
catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
public Reader getTemplateReader(String name) {
|
||||
try{
|
||||
try {
|
||||
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
|
||||
if(is == null)
|
||||
if (is == null) {
|
||||
is = new FileInputStream(new File(name));
|
||||
if(is == null)
|
||||
throw new RuntimeException("no file found");
|
||||
return new InputStreamReader(is);
|
||||
}
|
||||
catch(Exception e) {
|
||||
if (is == null) {
|
||||
throw new RuntimeException("no file found");
|
||||
}
|
||||
return new InputStreamReader(is);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
throw new RuntimeException("can't load template " + name);
|
||||
}
|
||||
|
||||
private String getCPResourcePath(String name) {
|
||||
if (!"/".equals(File.separator))
|
||||
if (!"/".equals(File.separator)) {
|
||||
return name.replaceAll(Pattern.quote(File.separator), "/");
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
@ -1,63 +1,66 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.codegen.ClientOpts;
|
||||
import io.swagger.annotations.*;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.models.auth.AuthorizationValue;
|
||||
|
||||
import java.util.*;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ClientOptInput {
|
||||
protected CodegenConfig config;
|
||||
private ClientOpts opts;
|
||||
private Swagger swagger;
|
||||
private List<AuthorizationValue> auths;
|
||||
protected CodegenConfig config;
|
||||
|
||||
public ClientOptInput swagger(Swagger swagger) {
|
||||
this.setSwagger(swagger);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ClientOptInput opts(ClientOpts opts) {
|
||||
this.setOpts(opts);
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getAuth() {
|
||||
if (auths != null) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (AuthorizationValue v : auths) {
|
||||
try {
|
||||
if (b.toString().length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
|
||||
.append(":")
|
||||
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
// continue
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAuth(String urlEncodedAuthString) {
|
||||
List<AuthorizationValue> auths = new ArrayList<AuthorizationValue>();
|
||||
if(urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
|
||||
if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) {
|
||||
String[] parts = urlEncodedAuthString.split(",");
|
||||
for(String part : parts) {
|
||||
for (String part : parts) {
|
||||
String[] kvPair = part.split(":");
|
||||
if(kvPair.length == 2) {
|
||||
if (kvPair.length == 2) {
|
||||
auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header"));
|
||||
}
|
||||
}
|
||||
}
|
||||
this.auths = auths;
|
||||
}
|
||||
public String getAuth() {
|
||||
if(auths != null) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(AuthorizationValue v : auths) {
|
||||
try {
|
||||
if(b.toString().length() > 0)
|
||||
b.append(",");
|
||||
b.append(URLEncoder.encode(v.getKeyName(), "UTF-8"))
|
||||
.append(":")
|
||||
.append(URLEncoder.encode(v.getValue(), "UTF-8"));
|
||||
}
|
||||
catch (Exception e) {
|
||||
// continue
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<AuthorizationValue> getAuthorizationValues() {
|
||||
return auths;
|
||||
}
|
||||
@ -65,24 +68,25 @@ public class ClientOptInput {
|
||||
public CodegenConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public void setConfig(CodegenConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public void setOpts(ClientOpts opts) {
|
||||
this.opts = opts;
|
||||
}
|
||||
|
||||
public ClientOpts getOpts() {
|
||||
return opts;
|
||||
}
|
||||
|
||||
public void setSwagger(Swagger swagger) {
|
||||
this.swagger = swagger;
|
||||
public void setOpts(ClientOpts opts) {
|
||||
this.opts = opts;
|
||||
}
|
||||
|
||||
@ApiModelProperty(dataType="Object")
|
||||
@ApiModelProperty(dataType = "Object")
|
||||
public Swagger getSwagger() {
|
||||
return swagger;
|
||||
}
|
||||
|
||||
public void setSwagger(Swagger swagger) {
|
||||
this.swagger = swagger;
|
||||
}
|
||||
}
|
@ -1,8 +1,9 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.codegen.auth.*;
|
||||
import io.swagger.codegen.auth.AuthMethod;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ClientOpts {
|
||||
protected String uri;
|
||||
@ -14,6 +15,7 @@ public class ClientOpts {
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
@ -21,6 +23,7 @@ public class ClientOpts {
|
||||
public String getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
public void setTarget(String target) {
|
||||
this.target = target;
|
||||
}
|
||||
@ -28,6 +31,7 @@ public class ClientOpts {
|
||||
public Map<String, String> getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
public void setProperties(Map<String, String> properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
@ -35,6 +39,7 @@ public class ClientOpts {
|
||||
public String getOutputDirectory() {
|
||||
return outputDirectory;
|
||||
}
|
||||
|
||||
public void setOutputDirectory(String outputDirectory) {
|
||||
this.outputDirectory = outputDirectory;
|
||||
}
|
||||
|
@ -1,16 +1,19 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.codegen.languages.*;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.models.auth.AuthorizationValue;
|
||||
import io.swagger.util.*;
|
||||
|
||||
import io.swagger.parser.SwaggerParser;
|
||||
import org.apache.commons.cli.BasicParser;
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Options;
|
||||
|
||||
import org.apache.commons.cli.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
/**
|
||||
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
|
||||
@ -20,24 +23,12 @@ import java.util.*;
|
||||
public class Codegen extends DefaultGenerator {
|
||||
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
|
||||
static String configString;
|
||||
static {
|
||||
List<CodegenConfig> extensions = getExtensions();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(CodegenConfig config : extensions) {
|
||||
if(sb.toString().length() != 0)
|
||||
sb.append(", ");
|
||||
sb.append(config.getName());
|
||||
configs.put(config.getName(), config);
|
||||
configString = sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" +
|
||||
"\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" +
|
||||
"\n -DdebugModels prints models passed to the template engine" +
|
||||
"\n -DdebugOperations prints operations passed to the template engine" +
|
||||
"\n -DdebugSupportingFiles prints additional data passed to the template engine";
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
@ -66,20 +57,22 @@ public class Codegen extends DefaultGenerator {
|
||||
System.out.println(debugInfoOptions);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("a"))
|
||||
if (cmd.hasOption("a")) {
|
||||
clientOptInput.setAuth(cmd.getOptionValue("a"));
|
||||
if (cmd.hasOption("l"))
|
||||
}
|
||||
if (cmd.hasOption("l")) {
|
||||
clientOptInput.setConfig(getConfig(cmd.getOptionValue("l")));
|
||||
else {
|
||||
} else {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("o"))
|
||||
if (cmd.hasOption("o")) {
|
||||
clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o"));
|
||||
}
|
||||
if (cmd.hasOption("h")) {
|
||||
if(cmd.hasOption("l")) {
|
||||
if (cmd.hasOption("l")) {
|
||||
config = getConfig(String.valueOf(cmd.getOptionValue("l")));
|
||||
if(config != null) {
|
||||
if (config != null) {
|
||||
options.addOption("h", "help", true, config.getHelp());
|
||||
usage(options);
|
||||
return;
|
||||
@ -88,22 +81,22 @@ public class Codegen extends DefaultGenerator {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("i"))
|
||||
if (cmd.hasOption("i")) {
|
||||
swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true);
|
||||
if (cmd.hasOption("t"))
|
||||
}
|
||||
if (cmd.hasOption("t")) {
|
||||
clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t")));
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
try{
|
||||
try {
|
||||
clientOptInput
|
||||
.opts(clientOpts)
|
||||
.swagger(swagger);
|
||||
new Codegen().opts(clientOptInput).generate();
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
@ -112,7 +105,7 @@ public class Codegen extends DefaultGenerator {
|
||||
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
|
||||
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
|
||||
Iterator<CodegenConfig> itr = loader.iterator();
|
||||
while(itr.hasNext()) {
|
||||
while (itr.hasNext()) {
|
||||
output.add(itr.next());
|
||||
}
|
||||
return output;
|
||||
@ -120,24 +113,36 @@ public class Codegen extends DefaultGenerator {
|
||||
|
||||
static void usage(Options options) {
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
formatter.printHelp( "Codegen", options );
|
||||
formatter.printHelp("Codegen", options);
|
||||
}
|
||||
|
||||
public static CodegenConfig getConfig(String name) {
|
||||
if(configs.containsKey(name)) {
|
||||
if (configs.containsKey(name)) {
|
||||
return configs.get(name);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
// see if it's a class
|
||||
try {
|
||||
System.out.println("loading class " + name);
|
||||
Class customClass = Class.forName(name);
|
||||
System.out.println("loaded");
|
||||
return (CodegenConfig)customClass.newInstance();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return (CodegenConfig) customClass.newInstance();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("can't load class " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
List<CodegenConfig> extensions = getExtensions();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (CodegenConfig config : extensions) {
|
||||
if (sb.toString().length() != 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(config.getName());
|
||||
configs.put(config.getName(), config);
|
||||
configString = sb.toString();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,61 +1,102 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public interface CodegenConfig {
|
||||
CodegenType getTag();
|
||||
|
||||
String getName();
|
||||
|
||||
String getHelp();
|
||||
|
||||
Map<String, Object> additionalProperties();
|
||||
|
||||
String apiPackage();
|
||||
|
||||
String apiFileFolder();
|
||||
|
||||
String fileSuffix();
|
||||
|
||||
String outputFolder();
|
||||
|
||||
String templateDir();
|
||||
|
||||
String modelFileFolder();
|
||||
|
||||
String modelPackage();
|
||||
|
||||
String toApiName(String name);
|
||||
|
||||
String toApiVarName(String name);
|
||||
|
||||
String toModelName(String name);
|
||||
|
||||
String toParamName(String name);
|
||||
|
||||
String escapeText(String text);
|
||||
|
||||
String escapeReservedWord(String name);
|
||||
|
||||
String getTypeDeclaration(Property p);
|
||||
|
||||
String getTypeDeclaration(String name);
|
||||
|
||||
void processOpts();
|
||||
|
||||
List<CliOption> cliOptions();
|
||||
|
||||
String generateExamplePath(String path, Operation operation);
|
||||
|
||||
Set<String> reservedWords();
|
||||
|
||||
List<SupportingFile> supportingFiles();
|
||||
|
||||
void setOutputDir(String dir);
|
||||
String getOutputDir();
|
||||
|
||||
void setOutputDir(String dir);
|
||||
|
||||
CodegenModel fromModel(String name, Model model);
|
||||
|
||||
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
|
||||
|
||||
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
|
||||
|
||||
Set<String> defaultIncludes();
|
||||
|
||||
Map<String, String> typeMapping();
|
||||
|
||||
Map<String, String> instantiationTypes();
|
||||
|
||||
Map<String, String> importMapping();
|
||||
|
||||
Map<String, String> apiTemplateFiles();
|
||||
|
||||
Map<String, String> modelTemplateFiles();
|
||||
|
||||
void processSwagger(Swagger swagger);
|
||||
|
||||
String toApiFilename(String name);
|
||||
|
||||
String toModelFilename(String name);
|
||||
|
||||
String toModelImport(String name);
|
||||
|
||||
String toApiImport(String name);
|
||||
|
||||
void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations);
|
||||
|
||||
Map<String, Object> postProcessModels(Map<String, Object> objs);
|
||||
|
||||
Map<String, Object> postProcessOperations(Map<String, Object> objs);
|
||||
|
||||
Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs);
|
||||
|
||||
String apiFilename(String templateName, String tag);
|
||||
|
@ -1,9 +1,11 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.ExternalDocs;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class CodegenModel {
|
||||
public String parent;
|
||||
|
@ -9,6 +9,7 @@ public final class CodegenModelFactory {
|
||||
|
||||
/**
|
||||
* Configure a different implementation class.
|
||||
*
|
||||
* @param type the type that shall be replaced
|
||||
* @param implementation the implementation class must extend the default class and must provide a public no-arg constructor
|
||||
*/
|
||||
|
@ -1,16 +1,20 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.models.ExternalDocs;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class CodegenOperation {
|
||||
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
|
||||
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
|
||||
returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
|
||||
hasMore = Boolean.TRUE, isMultipart;
|
||||
public String path, operationId, returnType, httpMethod, returnBaseType,
|
||||
returnContainer, summary, notes, baseName, defaultResponse;
|
||||
|
||||
public List<Map<String, String>> consumes, produces;
|
||||
public CodegenParameter bodyParam;
|
||||
public List<CodegenParameter> allParams = new ArrayList<CodegenParameter>();
|
||||
@ -22,7 +26,6 @@ public class CodegenOperation {
|
||||
public List<CodegenSecurity> authMethods;
|
||||
public List<String> tags;
|
||||
public List<CodegenResponse> responses = new ArrayList<CodegenResponse>();
|
||||
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
|
||||
public Set<String> imports = new HashSet<String>();
|
||||
public List<Map<String, String>> examples;
|
||||
public ExternalDocs externalDocs;
|
||||
|
@ -1,18 +1,27 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class CodegenProperty {
|
||||
public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum,
|
||||
name, min, max, defaultValue, baseType, containerType;
|
||||
|
||||
/** maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */
|
||||
/**
|
||||
* maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1
|
||||
*/
|
||||
public Integer maxLength;
|
||||
/** minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 */
|
||||
/**
|
||||
* minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2
|
||||
*/
|
||||
public Integer minLength;
|
||||
/** pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 */
|
||||
/**
|
||||
* pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3
|
||||
*/
|
||||
public String pattern;
|
||||
/** A free-form property to include an example of an instance for this schema. */
|
||||
/**
|
||||
* A free-form property to include an example of an instance for this schema.
|
||||
*/
|
||||
public String example;
|
||||
|
||||
public String jsonSchema;
|
||||
|
@ -5,10 +5,10 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class CodegenResponse {
|
||||
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
|
||||
public String code, message;
|
||||
public Boolean hasMore;
|
||||
public List<Map<String, Object>> examples;
|
||||
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
|
||||
public String dataType, baseType, containerType;
|
||||
public Boolean isDefault;
|
||||
public Boolean simpleType;
|
||||
@ -17,5 +17,8 @@ public class CodegenResponse {
|
||||
public Boolean isListContainer;
|
||||
public Object schema;
|
||||
public String jsonSchema;
|
||||
public boolean isWildcard() { return "0".equals(code) || "default".equals(code); }
|
||||
|
||||
public boolean isWildcard() {
|
||||
return "0".equals(code) || "default".equals(code);
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,16 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import com.fasterxml.jackson.annotation.*;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public enum CodegenType {
|
||||
CLIENT, SERVER, DOCUMENTATION, OTHER;
|
||||
|
||||
private static Map<String, CodegenType> names = new HashMap<String, CodegenType>();
|
||||
|
||||
static {
|
||||
names.put("client", CLIENT);
|
||||
names.put("server", SERVER);
|
||||
names.put("documentation", DOCUMENTATION);
|
||||
names.put("other", OTHER);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static CodegenType forValue(String value) {
|
||||
return names.get(value.toLowerCase());
|
||||
@ -25,10 +19,18 @@ public enum CodegenType {
|
||||
@JsonValue
|
||||
public String toValue() {
|
||||
for (Map.Entry<String, CodegenType> entry : names.entrySet()) {
|
||||
if (entry.getValue() == this)
|
||||
if (entry.getValue() == this) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
|
||||
return null; // or fail
|
||||
}
|
||||
|
||||
static {
|
||||
names.put("client", CLIENT);
|
||||
names.put("server", SERVER);
|
||||
names.put("documentation", DOCUMENTATION);
|
||||
names.put("other", OTHER);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -11,17 +11,14 @@ import io.swagger.models.Path;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import io.swagger.util.Json;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Reader;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@ -180,8 +177,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
|
||||
for (String templateName : config.apiTemplateFiles().keySet()) {
|
||||
|
||||
String filename = config.apiFilename( templateName, tag );
|
||||
if( new File( filename ).exists() && !config.shouldOverwrite( filename )){
|
||||
String filename = config.apiFilename(templateName, tag);
|
||||
if (new File(filename).exists() && !config.shouldOverwrite(filename)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -267,23 +264,24 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
|
||||
try {
|
||||
in = new FileInputStream(config.templateDir() + File.separator + support.templateFile);
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
// continue
|
||||
}
|
||||
if(in == null) {
|
||||
if (in == null) {
|
||||
in = this.getClass().getClassLoader().getResourceAsStream(config.templateDir() + File.separator + support.templateFile);
|
||||
}
|
||||
File outputFile = new File(outputFilename);
|
||||
OutputStream out = new FileOutputStream(outputFile, false);
|
||||
if(in != null && out != null)
|
||||
IOUtils.copy(in,out);
|
||||
else {
|
||||
if(in == null)
|
||||
if (in != null && out != null) {
|
||||
IOUtils.copy(in, out);
|
||||
} else {
|
||||
if (in == null) {
|
||||
System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input");
|
||||
if(out == null)
|
||||
}
|
||||
if (out == null) {
|
||||
System.out.println("can't open " + outputFile + " for output");
|
||||
}
|
||||
}
|
||||
|
||||
files.add(outputFile);
|
||||
}
|
||||
@ -297,17 +295,16 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
}
|
||||
|
||||
private void processMimeTypes(List<String> mimeTypeList, Map<String, Object> operation, String source) {
|
||||
if(mimeTypeList != null && mimeTypeList.size() > 0) {
|
||||
if (mimeTypeList != null && mimeTypeList.size() > 0) {
|
||||
List<Map<String, String>> c = new ArrayList<Map<String, String>>();
|
||||
int count = 0;
|
||||
for(String key: mimeTypeList) {
|
||||
for (String key : mimeTypeList) {
|
||||
Map<String, String> mediaType = new HashMap<String, String>();
|
||||
mediaType.put("mediaType", key);
|
||||
count += 1;
|
||||
if (count < mimeTypeList.size()) {
|
||||
mediaType.put("hasMore", "true");
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
mediaType.put("hasMore", null);
|
||||
}
|
||||
c.add(mediaType);
|
||||
@ -399,10 +396,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
// check for operationId uniqueness
|
||||
Set<String> opIds = new HashSet<String>();
|
||||
int counter = 0;
|
||||
for(CodegenOperation op : ops) {
|
||||
for (CodegenOperation op : ops) {
|
||||
String opId = op.nickname;
|
||||
if(opIds.contains(opId)) {
|
||||
counter ++;
|
||||
if (opIds.contains(opId)) {
|
||||
counter++;
|
||||
op.nickname += "_" + counter;
|
||||
}
|
||||
opIds.add(opId);
|
||||
|
@ -1,11 +1,10 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.models.Swagger;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
public interface Generator {
|
||||
Generator opts(ClientOptInput opts);
|
||||
|
||||
List<File> generate();
|
||||
}
|
@ -1,20 +1,23 @@
|
||||
package io.swagger.codegen;
|
||||
|
||||
import io.swagger.codegen.languages.*;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import com.samskivert.mustache.Template;
|
||||
import io.swagger.models.Swagger;
|
||||
import io.swagger.models.auth.AuthorizationValue;
|
||||
import io.swagger.util.*;
|
||||
|
||||
import io.swagger.parser.SwaggerParser;
|
||||
|
||||
import com.samskivert.mustache.*;
|
||||
|
||||
import org.apache.commons.cli.*;
|
||||
import org.apache.commons.cli.BasicParser;
|
||||
import org.apache.commons.cli.CommandLine;
|
||||
import org.apache.commons.cli.CommandLineParser;
|
||||
import org.apache.commons.cli.HelpFormatter;
|
||||
import org.apache.commons.cli.Options;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Reader;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
/**
|
||||
* @deprecated use instead {@link io.swagger.codegen.DefaultGenerator}
|
||||
@ -24,23 +27,35 @@ import java.util.*;
|
||||
public class MetaGenerator extends AbstractGenerator {
|
||||
static Map<String, CodegenConfig> configs = new HashMap<String, CodegenConfig>();
|
||||
static String configString;
|
||||
static {
|
||||
List<CodegenConfig> extensions = getExtensions();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for(CodegenConfig config : extensions) {
|
||||
if(sb.toString().length() != 0)
|
||||
sb.append(", ");
|
||||
sb.append(config.getName());
|
||||
configs.put(config.getName(), config);
|
||||
configString = sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new MetaGenerator().generate(args);
|
||||
}
|
||||
|
||||
public static List<CodegenConfig> getExtensions() {
|
||||
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
|
||||
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
|
||||
Iterator<CodegenConfig> itr = loader.iterator();
|
||||
while (itr.hasNext()) {
|
||||
output.add(itr.next());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
static void usage(Options options) {
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
formatter.printHelp("MetaGenerator. Generator for creating a new template set " +
|
||||
"and configuration for Codegen. The output will be based on the language you " +
|
||||
"specify, and includes default templates to include.", options);
|
||||
}
|
||||
|
||||
public static CodegenConfig getConfig(String name) {
|
||||
if (configs.containsKey(name)) {
|
||||
return configs.get(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void generate(String[] args) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String targetLanguage = null;
|
||||
@ -67,39 +82,43 @@ public class MetaGenerator extends AbstractGenerator {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("n"))
|
||||
if (cmd.hasOption("n")) {
|
||||
name = cmd.getOptionValue("n");
|
||||
else {
|
||||
} else {
|
||||
System.out.println("name is required");
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
if (cmd.hasOption("l"))
|
||||
if (cmd.hasOption("l")) {
|
||||
targetLanguage = cmd.getOptionValue("l");
|
||||
if (cmd.hasOption("p"))
|
||||
}
|
||||
if (cmd.hasOption("p")) {
|
||||
targetPackage = cmd.getOptionValue("p");
|
||||
if (cmd.hasOption("o"))
|
||||
}
|
||||
if (cmd.hasOption("o")) {
|
||||
outputFolder = cmd.getOptionValue("o");
|
||||
else {
|
||||
} else {
|
||||
System.out.println("output folder is required");
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
} catch (Exception e) {
|
||||
usage(options);
|
||||
return;
|
||||
}
|
||||
System.out.println("writing to folder " + outputFolder);
|
||||
File outputFolderLocation = new File(outputFolder);
|
||||
if(!outputFolderLocation.exists())
|
||||
if (!outputFolderLocation.exists()) {
|
||||
outputFolderLocation.mkdirs();
|
||||
}
|
||||
File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar));
|
||||
if(!sourceFolder.exists())
|
||||
if (!sourceFolder.exists()) {
|
||||
sourceFolder.mkdirs();
|
||||
}
|
||||
File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services");
|
||||
if(!resourcesFolder.exists())
|
||||
if (!resourcesFolder.exists()) {
|
||||
resourcesFolder.mkdirs();
|
||||
}
|
||||
|
||||
String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator";
|
||||
|
||||
@ -122,64 +141,56 @@ public class MetaGenerator extends AbstractGenerator {
|
||||
data.put("name", name);
|
||||
data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass);
|
||||
|
||||
for(SupportingFile support : supportingFiles) {
|
||||
for (SupportingFile support : supportingFiles) {
|
||||
try {
|
||||
String destinationFolder = outputFolder;
|
||||
if(support.folder != null && !"".equals(support.folder))
|
||||
if (support.folder != null && !"".equals(support.folder)) {
|
||||
destinationFolder += File.separator + support.folder;
|
||||
}
|
||||
File of = new File(destinationFolder);
|
||||
if(!of.isDirectory())
|
||||
if (!of.isDirectory()) {
|
||||
of.mkdirs();
|
||||
}
|
||||
String outputFilename = destinationFolder + File.separator + support.destinationFilename;
|
||||
|
||||
if(support.templateFile.endsWith("mustache")) {
|
||||
if (support.templateFile.endsWith("mustache")) {
|
||||
String template = readTemplate(templateDir + File.separator + support.templateFile);
|
||||
Template tmpl = Mustache.compiler()
|
||||
.withLoader(new Mustache.TemplateLoader() {
|
||||
public Reader getTemplate (String name) {
|
||||
public Reader getTemplate(String name) {
|
||||
return getTemplateReader(templateDir + File.separator + name + ".mustache");
|
||||
};
|
||||
}
|
||||
|
||||
;
|
||||
})
|
||||
.defaultValue("")
|
||||
.compile(template);
|
||||
|
||||
writeToFile(outputFilename, tmpl.execute(data));
|
||||
files.add(new File(outputFilename));
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
String template = readTemplate(templateDir + File.separator + support.templateFile);
|
||||
FileUtils.writeStringToFile(new File(outputFilename), template);
|
||||
System.out.println("copying file to " + outputFilename);
|
||||
files.add(new File(outputFilename));
|
||||
}
|
||||
}
|
||||
catch (java.io.IOException e) {
|
||||
} catch (java.io.IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<CodegenConfig> getExtensions() {
|
||||
ServiceLoader<CodegenConfig> loader = ServiceLoader.load(CodegenConfig.class);
|
||||
List<CodegenConfig> output = new ArrayList<CodegenConfig>();
|
||||
Iterator<CodegenConfig> itr = loader.iterator();
|
||||
while(itr.hasNext()) {
|
||||
output.add(itr.next());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
static {
|
||||
List<CodegenConfig> extensions = getExtensions();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
static void usage(Options options) {
|
||||
HelpFormatter formatter = new HelpFormatter();
|
||||
formatter.printHelp( "MetaGenerator. Generator for creating a new template set " +
|
||||
"and configuration for Codegen. The output will be based on the language you " +
|
||||
"specify, and includes default templates to include.", options );
|
||||
for (CodegenConfig config : extensions) {
|
||||
if (sb.toString().length() != 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
|
||||
public static CodegenConfig getConfig(String name) {
|
||||
if(configs.containsKey(name)) {
|
||||
return configs.get(name);
|
||||
sb.append(config.getName());
|
||||
configs.put(config.getName(), config);
|
||||
configString = sb.toString();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -2,5 +2,6 @@ package io.swagger.codegen.auth;
|
||||
|
||||
public interface AuthMethod {
|
||||
String getType();
|
||||
|
||||
void setType(String type);
|
||||
}
|
@ -1,14 +1,5 @@
|
||||
package io.swagger.codegen.examples;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.ModelImpl;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
@ -29,6 +20,15 @@ import io.swagger.models.properties.StringProperty;
|
||||
import io.swagger.models.properties.UUIDProperty;
|
||||
import io.swagger.util.Json;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class ExampleGenerator {
|
||||
protected Map<String, Model> examples;
|
||||
|
||||
@ -39,40 +39,38 @@ public class ExampleGenerator {
|
||||
public List<Map<String, String>> generate(Map<String, Object> examples, List<String> mediaTypes, Property property) {
|
||||
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
|
||||
Set<String> processedModels = new HashSet<String>();
|
||||
if(examples == null ) {
|
||||
if(mediaTypes == null) {
|
||||
if (examples == null) {
|
||||
if (mediaTypes == null) {
|
||||
// assume application/json for this
|
||||
mediaTypes = Arrays.asList("application/json");
|
||||
}
|
||||
for(String mediaType : mediaTypes) {
|
||||
for (String mediaType : mediaTypes) {
|
||||
Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("contentType", mediaType);
|
||||
if(property != null && mediaType.startsWith("application/json")) {
|
||||
if (property != null && mediaType.startsWith("application/json")) {
|
||||
String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels));
|
||||
|
||||
if(example != null) {
|
||||
if (example != null) {
|
||||
kv.put("example", example);
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
else if(property != null && mediaType.startsWith("application/xml")) {
|
||||
} else if (property != null && mediaType.startsWith("application/xml")) {
|
||||
String example = new XmlExampleGenerator(this.examples).toXml(property);
|
||||
if(example != null) {
|
||||
if (example != null) {
|
||||
kv.put("example", example);
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
for(Map.Entry<String, Object> entry: examples.entrySet()) {
|
||||
} else {
|
||||
for (Map.Entry<String, Object> entry : examples.entrySet()) {
|
||||
final Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("contentType", entry.getKey());
|
||||
kv.put("example", Json.pretty(entry.getValue()));
|
||||
output.add(kv);
|
||||
}
|
||||
}
|
||||
if(output.size() == 0) {
|
||||
if (output.size() == 0) {
|
||||
Map<String, String> kv = new HashMap<String, String>();
|
||||
kv.put("output", "none");
|
||||
output.add(kv);
|
||||
@ -81,70 +79,55 @@ public class ExampleGenerator {
|
||||
}
|
||||
|
||||
protected Object resolvePropertyToExample(String mediaType, Property property, Set<String> processedModels) {
|
||||
if(property.getExample() != null) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
}
|
||||
else if(property instanceof StringProperty) {
|
||||
} else if (property instanceof StringProperty) {
|
||||
return "aeiou";
|
||||
}
|
||||
else if(property instanceof BooleanProperty) {
|
||||
} else if (property instanceof BooleanProperty) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
else if(property instanceof ArrayProperty) {
|
||||
Property innerType = ((ArrayProperty)property).getItems();
|
||||
if(innerType != null) {
|
||||
} else if (property instanceof ArrayProperty) {
|
||||
Property innerType = ((ArrayProperty) property).getItems();
|
||||
if (innerType != null) {
|
||||
Object[] output = new Object[]{
|
||||
resolvePropertyToExample(mediaType, innerType, processedModels)
|
||||
};
|
||||
return output;
|
||||
}
|
||||
}
|
||||
else if(property instanceof DateProperty) {
|
||||
} else if (property instanceof DateProperty) {
|
||||
return new java.util.Date(System.currentTimeMillis());
|
||||
}
|
||||
else if(property instanceof DateTimeProperty) {
|
||||
} else if (property instanceof DateTimeProperty) {
|
||||
return new java.util.Date(System.currentTimeMillis());
|
||||
}
|
||||
else if(property instanceof DecimalProperty) {
|
||||
} else if (property instanceof DecimalProperty) {
|
||||
return new BigDecimal(1.3579);
|
||||
}
|
||||
else if(property instanceof DoubleProperty) {
|
||||
} else if (property instanceof DoubleProperty) {
|
||||
return new Double(3.149);
|
||||
}
|
||||
else if(property instanceof FileProperty) {
|
||||
} else if (property instanceof FileProperty) {
|
||||
return ""; // TODO
|
||||
}
|
||||
else if(property instanceof FloatProperty) {
|
||||
} else if (property instanceof FloatProperty) {
|
||||
return new Float(1.23);
|
||||
}
|
||||
else if(property instanceof IntegerProperty) {
|
||||
} else if (property instanceof IntegerProperty) {
|
||||
return new Integer(123);
|
||||
}
|
||||
else if(property instanceof LongProperty) {
|
||||
} else if (property instanceof LongProperty) {
|
||||
return new Long(123456789);
|
||||
}
|
||||
else if(property instanceof MapProperty) {
|
||||
} else if (property instanceof MapProperty) {
|
||||
Map<String, Object> mp = new HashMap<String, Object>();
|
||||
if(property.getName() != null) {
|
||||
if (property.getName() != null) {
|
||||
mp.put(property.getName(),
|
||||
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
|
||||
}
|
||||
else {
|
||||
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
|
||||
} else {
|
||||
mp.put("key",
|
||||
resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels));
|
||||
resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels));
|
||||
}
|
||||
return mp;
|
||||
}
|
||||
else if(property instanceof ObjectProperty) {
|
||||
} else if (property instanceof ObjectProperty) {
|
||||
return "{}";
|
||||
}
|
||||
else if(property instanceof RefProperty) {
|
||||
String simpleName = ((RefProperty)property).getSimpleRef();
|
||||
} else if (property instanceof RefProperty) {
|
||||
String simpleName = ((RefProperty) property).getSimpleRef();
|
||||
Model model = examples.get(simpleName);
|
||||
if(model != null)
|
||||
if (model != null) {
|
||||
return resolveModelToExample(simpleName, mediaType, model, processedModels);
|
||||
}
|
||||
else if(property instanceof UUIDProperty) {
|
||||
} else if (property instanceof UUIDProperty) {
|
||||
return "046b6c7f-0b8a-43b9-b35d-6489e6daee91";
|
||||
}
|
||||
|
||||
@ -152,16 +135,16 @@ public class ExampleGenerator {
|
||||
}
|
||||
|
||||
public Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
|
||||
if(processedModels.contains(name)) {
|
||||
if (processedModels.contains(name)) {
|
||||
return "";
|
||||
}
|
||||
if(model instanceof ModelImpl) {
|
||||
if (model instanceof ModelImpl) {
|
||||
processedModels.add(name);
|
||||
ModelImpl impl = (ModelImpl) model;
|
||||
Map<String, Object> values = new HashMap<String, Object>();
|
||||
|
||||
if(impl != null && impl.getProperties() != null) {
|
||||
for(String propertyName : impl.getProperties().keySet()) {
|
||||
if (impl != null && impl.getProperties() != null) {
|
||||
for (String propertyName : impl.getProperties().keySet()) {
|
||||
Property property = impl.getProperties().get(propertyName);
|
||||
values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels));
|
||||
}
|
||||
|
@ -1,43 +1,60 @@
|
||||
package io.swagger.codegen.examples;
|
||||
|
||||
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.ModelImpl;
|
||||
import io.swagger.models.RefModel;
|
||||
import io.swagger.models.Xml;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.RefProperty;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
import org.codehaus.plexus.util.StringUtils;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
import org.codehaus.plexus.util.StringUtils;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class XmlExampleGenerator {
|
||||
public static String NEWLINE = "\n";
|
||||
public static String TAG_START = "<";
|
||||
public static String CLOSE_TAG = ">";
|
||||
public static String TAG_END = "</";
|
||||
private static String EMPTY = "";
|
||||
protected Map<String, Model> examples;
|
||||
protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
private static String EMPTY = "";
|
||||
|
||||
public XmlExampleGenerator(Map<String, Model> examples) {
|
||||
this.examples = examples;
|
||||
if(examples == null)
|
||||
if (examples == null) {
|
||||
examples = new HashMap<String, Model>();
|
||||
}
|
||||
}
|
||||
|
||||
public String toXml(Property property) {
|
||||
return toXml(null, property, 0, Collections.<String>emptySet());
|
||||
}
|
||||
|
||||
protected String toXml(Model model, int indent, Collection<String> path) {
|
||||
if(model instanceof RefModel) {
|
||||
if (model instanceof RefModel) {
|
||||
RefModel ref = (RefModel) model;
|
||||
Model actualModel = examples.get(ref.getSimpleRef());
|
||||
if(actualModel instanceof ModelImpl)
|
||||
if (actualModel instanceof ModelImpl) {
|
||||
return modelImplToXml((ModelImpl) actualModel, indent, path);
|
||||
}
|
||||
else if(model instanceof ModelImpl) {
|
||||
} else if (model instanceof ModelImpl) {
|
||||
return modelImplToXml((ModelImpl) model, indent, path);
|
||||
}
|
||||
return null;
|
||||
@ -62,26 +79,28 @@ public class XmlExampleGenerator {
|
||||
Boolean wrapped;
|
||||
|
||||
Xml xml = model.getXml();
|
||||
if(xml != null) {
|
||||
if(xml.getName() != null)
|
||||
if (xml != null) {
|
||||
if (xml.getName() != null) {
|
||||
name = xml.getName();
|
||||
}
|
||||
for(String pName : model.getProperties().keySet()) {
|
||||
}
|
||||
for (String pName : model.getProperties().keySet()) {
|
||||
Property p = model.getProperties().get(pName);
|
||||
if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute())
|
||||
if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) {
|
||||
attributes.put(pName, p);
|
||||
else
|
||||
} else {
|
||||
elements.put(pName, p);
|
||||
}
|
||||
}
|
||||
sb.append(indent(indent)).append(TAG_START);
|
||||
sb.append(name);
|
||||
for(String pName : attributes.keySet()) {
|
||||
for (String pName : attributes.keySet()) {
|
||||
Property p = attributes.get(pName);
|
||||
sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath)));
|
||||
}
|
||||
sb.append(CLOSE_TAG);
|
||||
sb.append(NEWLINE);
|
||||
for(String pName : elements.keySet()) {
|
||||
for (String pName : elements.keySet()) {
|
||||
Property p = elements.get(pName);
|
||||
final String asXml = toXml(pName, p, indent + 1, selfPath);
|
||||
if (StringUtils.isEmpty(asXml)) {
|
||||
@ -100,20 +119,21 @@ public class XmlExampleGenerator {
|
||||
}
|
||||
|
||||
protected String toXml(String name, Property property, int indent, Collection<String> path) {
|
||||
if(property == null) {
|
||||
if (property == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if(property instanceof ArrayProperty) {
|
||||
if (property instanceof ArrayProperty) {
|
||||
ArrayProperty p = (ArrayProperty) property;
|
||||
Property inner = p.getItems();
|
||||
boolean wrapped = false;
|
||||
if(property.getXml() != null && property.getXml().getWrapped())
|
||||
if (property.getXml() != null && property.getXml().getWrapped()) {
|
||||
wrapped = true;
|
||||
if(wrapped) {
|
||||
}
|
||||
if (wrapped) {
|
||||
String prefix = EMPTY;
|
||||
if(name != null) {
|
||||
if (name != null) {
|
||||
sb.append(indent(indent));
|
||||
sb.append(openTag(name));
|
||||
prefix = NEWLINE;
|
||||
@ -122,69 +142,69 @@ public class XmlExampleGenerator {
|
||||
if (StringUtils.isNotEmpty(asXml)) {
|
||||
sb.append(prefix).append(asXml);
|
||||
}
|
||||
if(name != null) {
|
||||
if (name != null) {
|
||||
sb.append(NEWLINE);
|
||||
sb.append(indent(indent));
|
||||
sb.append(closeTag(name));
|
||||
}
|
||||
}
|
||||
else
|
||||
} else {
|
||||
sb.append(toXml(name, inner, indent, path));
|
||||
}
|
||||
else if(property instanceof RefProperty) {
|
||||
} else if (property instanceof RefProperty) {
|
||||
RefProperty ref = (RefProperty) property;
|
||||
Model actualModel = examples.get(ref.getSimpleRef());
|
||||
sb.append(toXml(actualModel, indent, path));
|
||||
}
|
||||
else {
|
||||
if(name != null) {
|
||||
} else {
|
||||
if (name != null) {
|
||||
sb.append(indent(indent));
|
||||
sb.append(openTag(name));
|
||||
}
|
||||
sb.append(getExample(property));
|
||||
if(name != null)
|
||||
if (name != null) {
|
||||
sb.append(closeTag(name));
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
protected String getExample(Property property) {
|
||||
if(property instanceof DateTimeProperty) {
|
||||
if(property.getExample() != null)
|
||||
if (property instanceof DateTimeProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return dtFormat.format(new Date());
|
||||
}
|
||||
else if(property instanceof StringProperty) {
|
||||
if(property.getExample() != null)
|
||||
} else if (property instanceof StringProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return "string";
|
||||
}
|
||||
else if(property instanceof DateProperty) {
|
||||
if(property.getExample() != null)
|
||||
} else if (property instanceof DateProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return dateFormat.format(new Date());
|
||||
}
|
||||
else if(property instanceof IntegerProperty) {
|
||||
if(property.getExample() != null)
|
||||
} else if (property instanceof IntegerProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return "0";
|
||||
}
|
||||
else if(property instanceof BooleanProperty) {
|
||||
if(property.getExample() != null)
|
||||
} else if (property instanceof BooleanProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return "true";
|
||||
}
|
||||
else if(property instanceof LongProperty) {
|
||||
if(property.getExample() != null)
|
||||
} else if (property instanceof LongProperty) {
|
||||
if (property.getExample() != null) {
|
||||
return property.getExample();
|
||||
else
|
||||
} else {
|
||||
return "123456";
|
||||
}
|
||||
}
|
||||
return "not implemented " + property;
|
||||
}
|
||||
|
||||
@ -198,7 +218,7 @@ public class XmlExampleGenerator {
|
||||
|
||||
protected String indent(int indent) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(int i = 0; i < indent; i++) {
|
||||
for (int i = 0; i < indent; i++) {
|
||||
sb.append(" ");
|
||||
}
|
||||
return sb.toString();
|
||||
|
@ -3,9 +3,26 @@ package io.swagger.codegen.languages;
|
||||
import com.google.common.base.CaseFormat;
|
||||
import com.samskivert.mustache.Mustache;
|
||||
import com.samskivert.mustache.Template;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenProperty;
|
||||
import io.swagger.codegen.CodegenResponse;
|
||||
import io.swagger.codegen.CodegenSecurity;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.auth.SecuritySchemeDefinition;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -14,13 +31,16 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
|
||||
|
||||
protected String mainPackage = "io.swagger.client";
|
||||
|
||||
protected String invokerPackage = mainPackage + ".core";
|
||||
protected String groupId = "io.swagger";
|
||||
protected String artifactId = "swagger-client";
|
||||
@ -30,7 +50,6 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
protected String configKey = "apiRequest";
|
||||
protected int defaultTimeoutInMs = 5000;
|
||||
protected String configKeyPath = mainPackage;
|
||||
|
||||
protected boolean registerNonStandardStatusCodes = true;
|
||||
protected boolean renderJavadoc = true;
|
||||
protected boolean removeOAuthSecurities = true;
|
||||
@ -41,18 +60,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
* unmarshalling problems and any other RuntimeException will be considered as ApiErrors.
|
||||
*/
|
||||
protected boolean onlyOneSuccess = true;
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "akka-scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala client library base on Akka/Spray.";
|
||||
}
|
||||
Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class);
|
||||
|
||||
public AkkaScalaClientCodegen() {
|
||||
super();
|
||||
@ -79,8 +87,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
additionalProperties.put("configKey", configKey);
|
||||
additionalProperties.put("configKeyPath", configKeyPath);
|
||||
additionalProperties.put("defaultTimeout", defaultTimeoutInMs);
|
||||
if (renderJavadoc)
|
||||
if (renderJavadoc) {
|
||||
additionalProperties.put("javadocRenderer", new JavadocLambda());
|
||||
}
|
||||
additionalProperties.put("fnCapitalize", new CapitalizeLambda());
|
||||
additionalProperties.put("fnCamelize", new CamelizeLambda(false));
|
||||
additionalProperties.put("fnEnumEntry", new EnumEntryLambda());
|
||||
@ -139,6 +148,18 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
instantiationTypes.put("map", "Map");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "akka-scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala client library base on Akka/Spray.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "`" + name + "`";
|
||||
@ -162,8 +183,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
HashSet<Integer> unknownCodes = new HashSet<Integer>();
|
||||
for (CodegenOperation operation : opsMap.get("operation")) {
|
||||
for (CodegenResponse response : operation.responses) {
|
||||
if ("default".equals(response.code))
|
||||
if ("default".equals(response.code)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
int code = Integer.parseInt(response.code);
|
||||
if (code >= 600) {
|
||||
@ -202,16 +224,18 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
@Override
|
||||
public List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes) {
|
||||
final List<CodegenSecurity> codegenSecurities = super.fromSecurity(schemes);
|
||||
if (!removeOAuthSecurities)
|
||||
if (!removeOAuthSecurities) {
|
||||
return codegenSecurities;
|
||||
}
|
||||
|
||||
// Remove OAuth securities
|
||||
Iterator<CodegenSecurity> it = codegenSecurities.iterator();
|
||||
while (it.hasNext()) {
|
||||
final CodegenSecurity security = it.next();
|
||||
if (security.isOAuth)
|
||||
if (security.isOAuth) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
// Adapt 'hasMore'
|
||||
it = codegenSecurities.iterator();
|
||||
while (it.hasNext()) {
|
||||
@ -219,8 +243,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
security.hasMore = it.hasNext();
|
||||
}
|
||||
|
||||
if (codegenSecurities.isEmpty())
|
||||
if (codegenSecurities.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return codegenSecurities;
|
||||
}
|
||||
|
||||
@ -231,15 +256,19 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
|
||||
private String formatIdentifier(String name, boolean capitalized) {
|
||||
String identifier = camelize(name, true);
|
||||
if (capitalized)
|
||||
if (capitalized) {
|
||||
identifier = StringUtils.capitalize(identifier);
|
||||
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier))
|
||||
}
|
||||
if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) {
|
||||
return identifier;
|
||||
}
|
||||
return escapeReservedWord(identifier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toParamName(String name) { return formatIdentifier(name, false); }
|
||||
public String toParamName(String name) {
|
||||
return formatIdentifier(name, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
@ -247,8 +276,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toEnumName(CodegenProperty property)
|
||||
{
|
||||
public String toEnumName(CodegenProperty property) {
|
||||
return formatIdentifier(property.baseName, true);
|
||||
}
|
||||
|
||||
@ -258,10 +286,12 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
String type;
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if (languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
} else
|
||||
}
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -275,30 +305,32 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array") + "[" + inner + "]";
|
||||
} else
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
if (!p.getRequired())
|
||||
if (!p.getRequired()) {
|
||||
return "None";
|
||||
if (p instanceof StringProperty)
|
||||
}
|
||||
if (p instanceof StringProperty) {
|
||||
return "null";
|
||||
else if (p instanceof BooleanProperty)
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "null";
|
||||
else if (p instanceof DateProperty)
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "null";
|
||||
else if (p instanceof DateTimeProperty)
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "null";
|
||||
else if (p instanceof DoubleProperty)
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "null";
|
||||
else if (p instanceof FloatProperty)
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "null";
|
||||
else if (p instanceof IntegerProperty)
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "null";
|
||||
else if (p instanceof LongProperty)
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "null";
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "Map[String, " + inner + "].empty ";
|
||||
@ -306,9 +338,10 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return "Seq[" + inner + "].empty ";
|
||||
} else
|
||||
} else {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
private static abstract class CustomLambda implements Mustache.Lambda {
|
||||
@Override
|
||||
@ -317,6 +350,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon
|
||||
frag.execute(tempWriter);
|
||||
out.write(formatFragment(tempWriter.toString()));
|
||||
}
|
||||
|
||||
public abstract String formatFragment(String fragment);
|
||||
}
|
||||
|
||||
|
@ -1,10 +1,17 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -15,18 +22,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
protected String sourceFolder = projectFolder + "/java";
|
||||
protected Boolean useAndroidMavenGradlePlugin = true;
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "android";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Android client library.";
|
||||
}
|
||||
|
||||
public AndroidClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/android";
|
||||
@ -36,7 +31,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "continue", "for", "new", "switch", "assert",
|
||||
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
|
||||
@ -69,6 +64,18 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true."));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "android";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Android client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -85,12 +92,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -103,13 +109,14 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -119,16 +126,18 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -142,8 +151,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -159,8 +169,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
@ -169,46 +180,41 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if(additionalProperties.containsKey("invokerPackage")) {
|
||||
this.setInvokerPackage((String)additionalProperties.get("invokerPackage"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("invokerPackage")) {
|
||||
this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
|
||||
} else {
|
||||
//not set, use default to be passed to template
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("groupId")) {
|
||||
this.setGroupId((String)additionalProperties.get("groupId"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("groupId")) {
|
||||
this.setGroupId((String) additionalProperties.get("groupId"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("groupId", groupId);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("artifactId")) {
|
||||
this.setArtifactId((String)additionalProperties.get("artifactId"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("artifactId")) {
|
||||
this.setArtifactId((String) additionalProperties.get("artifactId"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("artifactVersion")) {
|
||||
this.setArtifactVersion((String)additionalProperties.get("artifactVersion"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("artifactVersion")) {
|
||||
this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
|
||||
if (additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("useAndroidMavenGradlePlugin")) {
|
||||
this.setUseAndroidMavenGradlePlugin((Boolean)additionalProperties.get("useAndroidMavenGradlePlugin"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) {
|
||||
this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin"));
|
||||
} else {
|
||||
additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin);
|
||||
}
|
||||
|
||||
|
@ -1,10 +1,25 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -17,18 +32,6 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
protected boolean authPreemptive = false;
|
||||
protected boolean asyncHttpClient = !authScheme.isEmpty();
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "async-scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Asynchronous Scala client library.";
|
||||
}
|
||||
|
||||
public AsyncScalaClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/async-scala";
|
||||
@ -38,7 +41,7 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "case", "catch", "class", "def", "do", "else", "extends",
|
||||
"false", "final", "finally", "for", "forSome", "if", "implicit",
|
||||
@ -101,6 +104,18 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "async-scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Asynchronous Scala client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -117,12 +132,11 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -135,13 +149,14 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -151,44 +166,42 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return instantiationTypes.get("map") + "[String, " + inner + "]";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array") + "[" + inner + "]";
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
if(p instanceof StringProperty)
|
||||
if (p instanceof StringProperty) {
|
||||
return "null";
|
||||
else if (p instanceof BooleanProperty)
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "null";
|
||||
else if(p instanceof DateProperty)
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "null";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "null";
|
||||
else if (p instanceof DoubleProperty)
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "null";
|
||||
else if (p instanceof FloatProperty)
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "null";
|
||||
else if (p instanceof IntegerProperty)
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "null";
|
||||
else if (p instanceof LongProperty)
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "null";
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "new HashMap[String, " + inner + "]() ";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return "new ListBuffer[" + inner + "]() ";
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
}
|
@ -1,10 +1,17 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "IO.Swagger.Client";
|
||||
@ -13,18 +20,6 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/csharp";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "csharp";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a CSharp client library.";
|
||||
}
|
||||
|
||||
public CSharpClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/csharp";
|
||||
@ -34,7 +29,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
apiPackage = "IO.Swagger.Api";
|
||||
modelPackage = "IO.Swagger.Model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while")
|
||||
);
|
||||
@ -92,6 +87,18 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "csharp";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a CSharp client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -112,16 +119,18 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize the variable name
|
||||
// pet_id => PetId
|
||||
name = camelize(name);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -135,8 +144,9 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -152,12 +162,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -170,21 +179,23 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType.toLowerCase())) {
|
||||
if (typeMapping.containsKey(swaggerType.toLowerCase())) {
|
||||
type = typeMapping.get(swaggerType.toLowerCase());
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId);
|
||||
}
|
||||
|
@ -1,10 +1,17 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -13,18 +20,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "java";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java client library.";
|
||||
}
|
||||
|
||||
public JavaClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/java";
|
||||
@ -34,7 +29,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "continue", "for", "new", "switch", "assert",
|
||||
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
|
||||
@ -66,44 +61,52 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
cliOptions.add(new CliOption("sourceFolder", "source folder for generated code"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "java";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if(additionalProperties.containsKey("invokerPackage")) {
|
||||
this.setInvokerPackage((String)additionalProperties.get("invokerPackage"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("invokerPackage")) {
|
||||
this.setInvokerPackage((String) additionalProperties.get("invokerPackage"));
|
||||
} else {
|
||||
//not set, use default to be passed to template
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("groupId")) {
|
||||
this.setGroupId((String)additionalProperties.get("groupId"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("groupId")) {
|
||||
this.setGroupId((String) additionalProperties.get("groupId"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("groupId", groupId);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("artifactId")) {
|
||||
this.setArtifactId((String)additionalProperties.get("artifactId"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("artifactId")) {
|
||||
this.setArtifactId((String) additionalProperties.get("artifactId"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("artifactVersion")) {
|
||||
this.setArtifactVersion((String)additionalProperties.get("artifactVersion"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("artifactVersion")) {
|
||||
this.setArtifactVersion((String) additionalProperties.get("artifactVersion"));
|
||||
} else {
|
||||
//not set, use to be passed to template
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
|
||||
if (additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
|
||||
}
|
||||
|
||||
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
|
||||
@ -122,7 +125,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -143,16 +145,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -166,8 +170,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -182,12 +187,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -200,21 +204,23 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
@ -1,11 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.api";
|
||||
@ -14,32 +23,20 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String title = "Swagger Server";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "jaxrs";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java JAXRS Server application.";
|
||||
}
|
||||
|
||||
public JaxRSServerCodegen() {
|
||||
super.processOpts();
|
||||
|
||||
sourceFolder = "src/gen/java";
|
||||
|
||||
outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" );
|
||||
outputFolder = System.getProperty("swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS");
|
||||
modelTemplateFiles.put("model.mustache", ".java");
|
||||
apiTemplateFiles.put("api.mustache", ".java");
|
||||
apiTemplateFiles.put("apiService.mustache", ".java");
|
||||
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
|
||||
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
|
||||
templateDir = "JavaJaxRS";
|
||||
apiPackage = System.getProperty( "swagger.codegen.jaxrs.apipackage", "io.swagger.api") ;
|
||||
modelPackage = System.getProperty( "swagger.codegen.jaxrs.modelpackage", "io.swagger.model" );
|
||||
apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api");
|
||||
modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model");
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
@ -60,6 +57,17 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
);
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "jaxrs";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java JAXRS Server application.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
@ -83,12 +91,11 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -100,21 +107,24 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
String basePath = resourcePath;
|
||||
if(basePath.startsWith("/"))
|
||||
if (basePath.startsWith("/")) {
|
||||
basePath = basePath.substring(1);
|
||||
}
|
||||
int pos = basePath.indexOf("/");
|
||||
if(pos > 0)
|
||||
if (pos > 0) {
|
||||
basePath = basePath.substring(0, pos);
|
||||
}
|
||||
|
||||
if(basePath == "")
|
||||
if (basePath == "") {
|
||||
basePath = "default";
|
||||
else {
|
||||
if(co.path.startsWith("/" + basePath))
|
||||
} else {
|
||||
if (co.path.startsWith("/" + basePath)) {
|
||||
co.path = co.path.substring(("/" + basePath).length());
|
||||
}
|
||||
co.subresourceOperation = !co.path.isEmpty();
|
||||
}
|
||||
List<CodegenOperation> opList = operations.get(basePath);
|
||||
if(opList == null) {
|
||||
if (opList == null) {
|
||||
opList = new ArrayList<CodegenOperation>();
|
||||
operations.put(basePath, opList);
|
||||
}
|
||||
@ -123,32 +133,30 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
}
|
||||
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>)objs.get("operations");
|
||||
if(operations != null) {
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
if (operations != null) {
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation operation : ops) {
|
||||
if(operation.returnType == null)
|
||||
for (CodegenOperation operation : ops) {
|
||||
if (operation.returnType == null) {
|
||||
operation.returnType = "Void";
|
||||
else if(operation.returnType.startsWith("List")) {
|
||||
} else if (operation.returnType.startsWith("List")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("List<".length(), end);
|
||||
operation.returnContainer = "List";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Map")) {
|
||||
} else if (operation.returnType.startsWith("Map")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("Map<".length(), end);
|
||||
operation.returnContainer = "Map";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Set")) {
|
||||
} else if (operation.returnType.startsWith("Set")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("Set<".length(), end);
|
||||
operation.returnContainer = "Set";
|
||||
}
|
||||
@ -163,25 +171,23 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
|
||||
String result = super.apiFilename(templateName, tag);
|
||||
|
||||
if( templateName.endsWith( "Impl.mustache")){
|
||||
int ix = result.lastIndexOf( '/' );
|
||||
result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java";
|
||||
if (templateName.endsWith("Impl.mustache")) {
|
||||
int ix = result.lastIndexOf('/');
|
||||
result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java";
|
||||
|
||||
String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" );
|
||||
if( output != null ){
|
||||
result = result.replace( apiFileFolder(), implFileFolder(output));
|
||||
String output = System.getProperty("swagger.codegen.jaxrs.impl.source");
|
||||
if (output != null) {
|
||||
result = result.replace(apiFileFolder(), implFileFolder(output));
|
||||
}
|
||||
}
|
||||
else if( templateName.endsWith( "Factory.mustache")){
|
||||
int ix = result.lastIndexOf( '/' );
|
||||
result = result.substring( 0, ix ) + "/factories" + result.substring( ix, result.length()-5 ) + "ServiceFactory.java";
|
||||
} else if (templateName.endsWith("Factory.mustache")) {
|
||||
int ix = result.lastIndexOf('/');
|
||||
result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java";
|
||||
|
||||
String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" );
|
||||
if( output != null ){
|
||||
result = result.replace( apiFileFolder(), implFileFolder(output));
|
||||
String output = System.getProperty("swagger.codegen.jaxrs.impl.source");
|
||||
if (output != null) {
|
||||
result = result.replace(apiFileFolder(), implFileFolder(output));
|
||||
}
|
||||
}
|
||||
else if( templateName.endsWith( "Service.mustache")) {
|
||||
} else if (templateName.endsWith("Service.mustache")) {
|
||||
int ix = result.lastIndexOf('.');
|
||||
result = result.substring(0, ix) + "Service.java";
|
||||
}
|
||||
@ -193,8 +199,8 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf
|
||||
return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
}
|
||||
|
||||
public boolean shouldOverwrite( String filename ){
|
||||
public boolean shouldOverwrite(String filename) {
|
||||
|
||||
return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java");
|
||||
return !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
|
||||
}
|
||||
}
|
@ -1,12 +1,5 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenParameter;
|
||||
@ -15,46 +8,18 @@ import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String apiVersion = "1.0.0";
|
||||
protected int serverPort = 8080;
|
||||
protected String projectName = "swagger-server";
|
||||
|
||||
public String apiPackage() {
|
||||
return "controllers";
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see io.swagger.codegen.CodegenType
|
||||
*/
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -l flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
public String getName() {
|
||||
return "nodejs";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
public String getHelp() {
|
||||
return "Generates a nodejs server library using the swagger-tools project. By default, " +
|
||||
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
|
||||
}
|
||||
|
||||
public NodeJSServerCodegen() {
|
||||
super();
|
||||
|
||||
@ -87,7 +52,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
/**
|
||||
* Reserved words. Override this with reserved words specific to your language
|
||||
*/
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"break", "case", "class", "catch", "const", "continue", "debugger",
|
||||
"default", "delete", "do", "else", "export", "extends", "finally",
|
||||
@ -124,17 +89,53 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
"",
|
||||
"package.json")
|
||||
);
|
||||
if(System.getProperty("noservice") == null) {
|
||||
if (System.getProperty("noservice") == null) {
|
||||
apiTemplateFiles.put(
|
||||
"service.mustache", // the template to use
|
||||
"Service.js"); // the extension for each file to write
|
||||
}
|
||||
}
|
||||
|
||||
public String apiPackage() {
|
||||
return "controllers";
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see io.swagger.codegen.CodegenType
|
||||
*/
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -l flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
public String getName() {
|
||||
return "nodejs";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
public String getHelp() {
|
||||
return "Generates a nodejs server library using the swagger-tools project. By default, " +
|
||||
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultController";
|
||||
}
|
||||
return initialCaps(name);
|
||||
}
|
||||
|
||||
@ -142,6 +143,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String toApiFilename(String name) {
|
||||
return toApiName(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
|
||||
* those terms here. This logic is only called if a variable matches the reseved words
|
||||
@ -168,21 +170,23 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig
|
||||
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
|
||||
for(CodegenOperation operation : operations) {
|
||||
for (CodegenOperation operation : operations) {
|
||||
operation.httpMethod = operation.httpMethod.toLowerCase();
|
||||
List<CodegenParameter> params = operation.allParams;
|
||||
if(params != null && params.size() == 0)
|
||||
if (params != null && params.size() == 0) {
|
||||
operation.allParams = null;
|
||||
}
|
||||
List<CodegenResponse> responses = operation.responses;
|
||||
if(responses != null) {
|
||||
for(CodegenResponse resp : responses) {
|
||||
if("0".equals(resp.code))
|
||||
if (responses != null) {
|
||||
for (CodegenResponse resp : responses) {
|
||||
if ("0".equals(resp.code)) {
|
||||
resp.code = "default";
|
||||
}
|
||||
}
|
||||
if(operation.examples != null && !operation.examples.isEmpty()) {
|
||||
}
|
||||
if (operation.examples != null && !operation.examples.isEmpty()) {
|
||||
// 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(); ) {
|
||||
final Map<String, String> example = it.next();
|
||||
final String contentType = example.get("contentType");
|
||||
if (contentType == null || !contentType.startsWith("application/json")) {
|
||||
|
@ -1,10 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CliOption;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenProperty;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected Set<String> foundationClasses = new HashSet<String>();
|
||||
@ -12,18 +22,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String classPrefix = "SWG";
|
||||
protected String projectName = "swaggerClient";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "objc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Objective-C client library.";
|
||||
}
|
||||
|
||||
public ObjcClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code" + File.separator + "objc";
|
||||
@ -92,9 +90,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("List", "NSArray");
|
||||
typeMapping.put("object", "NSObject");
|
||||
|
||||
importMapping = new HashMap<String, String> ();
|
||||
importMapping = new HashMap<String, String>();
|
||||
|
||||
foundationClasses = new HashSet<String> (
|
||||
foundationClasses = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"NSNumber",
|
||||
"NSObject",
|
||||
@ -111,22 +109,33 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "objc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates an Objective-C client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
|
||||
if(additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String)additionalProperties.get("sourceFolder"));
|
||||
if (additionalProperties.containsKey("sourceFolder")) {
|
||||
this.setSourceFolder((String) additionalProperties.get("sourceFolder"));
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("classPrefix")) {
|
||||
this.setClassPrefix((String)additionalProperties.get("classPrefix"));
|
||||
if (additionalProperties.containsKey("classPrefix")) {
|
||||
this.setClassPrefix((String) additionalProperties.get("classPrefix"));
|
||||
}
|
||||
|
||||
if(additionalProperties.containsKey("projectName")) {
|
||||
this.setProjectName((String)additionalProperties.get("projectName"));
|
||||
}
|
||||
else{
|
||||
if (additionalProperties.containsKey("projectName")) {
|
||||
this.setProjectName((String) additionalProperties.get("projectName"));
|
||||
} else {
|
||||
additionalProperties.put("projectName", projectName);
|
||||
}
|
||||
|
||||
@ -151,35 +160,36 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return instantiationTypes.get("map");
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array");
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(String name) {
|
||||
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name))
|
||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
||||
return name;
|
||||
else
|
||||
} else {
|
||||
return name + "*";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -192,19 +202,20 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
// In this codition, type of property p is array of primitive,
|
||||
// return container type with pointer, e.g. `NSArray*'
|
||||
if (languageSpecificPrimitives.contains(innerType))
|
||||
if (languageSpecificPrimitives.contains(innerType)) {
|
||||
return getSwaggerType(p) + "*";
|
||||
}
|
||||
|
||||
// In this codition, type of property p is array of model,
|
||||
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
|
||||
String innerTypeDeclaration = getTypeDeclaration(inner);
|
||||
|
||||
if (innerTypeDeclaration.endsWith("*"))
|
||||
if (innerTypeDeclaration.endsWith("*")) {
|
||||
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
|
||||
}
|
||||
|
||||
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
|
||||
// In this codition, type of p is objective-c primitive type, e.g. `NSSNumber',
|
||||
@ -231,7 +242,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
type = type.replaceAll("[^0-9a-zA-Z_]", "_");
|
||||
|
||||
// language build-in classes
|
||||
if(typeMapping.keySet().contains(type) ||
|
||||
if (typeMapping.keySet().contains(type) ||
|
||||
foundationClasses.contains(type) ||
|
||||
importMapping.values().contains(type) ||
|
||||
defaultIncludes.contains(type) ||
|
||||
@ -253,21 +264,21 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
protected void setNonArrayMapProperty(CodegenProperty property, String type) {
|
||||
super.setNonArrayMapProperty(property, type);
|
||||
if("NSDictionary".equals(type)) {
|
||||
if ("NSDictionary".equals(type)) {
|
||||
property.setter = "initWithDictionary";
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
property.setter = "initWithValues";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
if("".equals(modelPackage()))
|
||||
if ("".equals(modelPackage())) {
|
||||
return name;
|
||||
else
|
||||
} else {
|
||||
return modelPackage() + "." + name;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Property p) {
|
||||
@ -297,19 +308,21 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String toVarName(String name) {
|
||||
// replace non-word characters to `_`
|
||||
// e.g. `created-at` to `created_at`
|
||||
name = name.replaceAll("[^a-zA-Z0-9_]","_");
|
||||
name = name.replaceAll("[^a-zA-Z0-9_]", "_");
|
||||
|
||||
// if it's all upper case, do noting
|
||||
if (name.matches("^[A-Z_]$"))
|
||||
if (name.matches("^[A-Z_]$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// e.g. `pet_id` to `petId`
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, prepend `_`
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -327,8 +340,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
@ -1,11 +1,16 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "SwaggerClient";
|
||||
@ -13,18 +18,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "perl";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Perl client library.";
|
||||
}
|
||||
|
||||
public PerlClientCodegen() {
|
||||
super();
|
||||
modelPackage = File.separatorChar + "Object";
|
||||
@ -36,7 +29,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.clear();
|
||||
languageSpecificPrimitives.clear();
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"else", "lock", "qw",
|
||||
"__END__", "elsif", "lt", "qx",
|
||||
@ -83,6 +76,18 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "perl";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Perl client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -99,12 +104,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
|
||||
@ -116,16 +120,17 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
if(type == null)
|
||||
}
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@ -156,8 +161,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
escapeReservedWord(name); // e.g. return => _return
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -181,8 +187,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultApi";
|
||||
}
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
@ -190,8 +197,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return underscore(operationId);
|
||||
}
|
||||
|
@ -1,11 +1,17 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -13,18 +19,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "php";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a PHP client library.";
|
||||
}
|
||||
|
||||
public PhpClientCodegen() {
|
||||
super();
|
||||
|
||||
@ -39,7 +33,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
apiTemplateFiles.put("api.mustache", ".php");
|
||||
templateDir = "php";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor")
|
||||
);
|
||||
@ -91,6 +85,18 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "php";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a PHP client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -107,12 +113,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
|
||||
@ -124,19 +129,19 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
} else if (instantiationTypes.containsKey(type)) {
|
||||
return type;
|
||||
}
|
||||
else if (instantiationTypes.containsKey(type)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
if(type == null)
|
||||
}
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -167,8 +172,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
escapeReservedWord(name); // e.g. return => _return
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
|
@ -1,26 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
String module = "client";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "python3";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Python3 client library.";
|
||||
}
|
||||
|
||||
public Python3ClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/python3";
|
||||
@ -52,7 +46,7 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
typeMapping.put("date", "datetime");
|
||||
|
||||
// from https://docs.python.org/release/2.5.4/ref/keywords.html
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
|
||||
"assert", "else", "if", "pass", "yield", "break", "except", "import",
|
||||
@ -64,6 +58,18 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "python3";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Python3 client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -80,12 +86,11 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -98,14 +103,14 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@ -120,16 +125,18 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, convert to lower case
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
name = name.toLowerCase();
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// petId => pet_id
|
||||
name = underscore(name);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -143,8 +150,9 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -154,8 +162,9 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber.rb => phone_number.rb
|
||||
@ -173,24 +182,27 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultApi";
|
||||
}
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiVarName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "default_api";
|
||||
}
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return underscore(operationId);
|
||||
}
|
||||
|
@ -1,28 +1,22 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String module = "SwaggerPetstore";
|
||||
protected String invokerPackage;
|
||||
protected String eggPackage;
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "python";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Python client library.";
|
||||
}
|
||||
|
||||
public PythonClientCodegen() {
|
||||
super();
|
||||
|
||||
@ -58,7 +52,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
typeMapping.put("date", "datetime");
|
||||
|
||||
// from https://docs.python.org/release/2.5.4/ref/keywords.html
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"and", "del", "from", "not", "while", "as", "elif", "global", "or", "with",
|
||||
"assert", "else", "if", "pass", "yield", "break", "except", "import",
|
||||
@ -77,6 +71,22 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
|
||||
}
|
||||
|
||||
private static String dropDots(String str) {
|
||||
return str.replaceAll("\\.", "_");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "python";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Python client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -93,12 +103,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -111,9 +120,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
} else {
|
||||
@ -133,22 +142,20 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, convert to lower case
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
name = name.toLowerCase();
|
||||
}
|
||||
|
||||
// underscore the variable name
|
||||
// petId => pet_id
|
||||
name = underscore(dropDots(name));
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String dropDots(String str) {
|
||||
return str.replaceAll("\\.", "_");
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -160,8 +167,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -171,8 +179,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber => phone_number
|
||||
@ -190,24 +199,27 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultApi";
|
||||
}
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiVarName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "default_api";
|
||||
}
|
||||
return underscore(name) + "_api";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return underscore(operationId);
|
||||
}
|
||||
|
@ -1,52 +1,39 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DecimalProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.RefProperty;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
protected final String PREFIX = "SWG";
|
||||
protected Set<String> foundationClasses = new HashSet<String>();
|
||||
|
||||
// source folder where to write the files
|
||||
protected String sourceFolder = "client";
|
||||
protected String apiVersion = "1.0.0";
|
||||
protected final String PREFIX = "SWG";
|
||||
protected Map<String, String> namespaces = new HashMap<String, String>();
|
||||
protected Set<String> systemIncludes = new HashSet<String>();
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see io.swagger.codegen.CodegenType
|
||||
*/
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -l flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
public String getName() {
|
||||
return "qt5cpp";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
public String getHelp() {
|
||||
return "Generates a qt5 C++ client library.";
|
||||
}
|
||||
|
||||
public Qt5CPPGenerator() {
|
||||
super();
|
||||
|
||||
@ -89,7 +76,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
/**
|
||||
* Reserved words. Override this with reserved words specific to your language
|
||||
*/
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"sample1", // replace with static values
|
||||
"sample2")
|
||||
@ -137,7 +124,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\"");
|
||||
|
||||
namespaces = new HashMap<String, String> ();
|
||||
namespaces = new HashMap<String, String>();
|
||||
|
||||
foundationClasses.add("QString");
|
||||
|
||||
@ -145,12 +132,41 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
systemIncludes.add("QList");
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures the type of generator.
|
||||
*
|
||||
* @return the CodegenType for this generator
|
||||
* @see io.swagger.codegen.CodegenType
|
||||
*/
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a friendly name for the generator. This will be used by the generator
|
||||
* to select the library with the -l flag.
|
||||
*
|
||||
* @return the friendly name for the generator
|
||||
*/
|
||||
public String getName() {
|
||||
return "qt5cpp";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns human-friendly help for the generator. Provide the consumer with help
|
||||
* tips, parameters here
|
||||
*
|
||||
* @return A string value for the help message
|
||||
*/
|
||||
public String getHelp() {
|
||||
return "Generates a qt5 C++ client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
if(namespaces.containsKey(name)) {
|
||||
if (namespaces.containsKey(name)) {
|
||||
return "using " + namespaces.get(name) + ";";
|
||||
}
|
||||
else if(systemIncludes.contains(name)) {
|
||||
} else if (systemIncludes.contains(name)) {
|
||||
return "#include <" + name + ">";
|
||||
}
|
||||
return "#include \"" + name + ".h\"";
|
||||
@ -204,59 +220,58 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
public String getTypeDeclaration(Property p) {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
return getSwaggerType(p) + "<QString, " + getTypeDeclaration(inner) + ">*";
|
||||
}
|
||||
if(foundationClasses.contains(swaggerType))
|
||||
if (foundationClasses.contains(swaggerType)) {
|
||||
return swaggerType + "*";
|
||||
else if(languageSpecificPrimitives.contains(swaggerType))
|
||||
} else if (languageSpecificPrimitives.contains(swaggerType)) {
|
||||
return toModelName(swaggerType);
|
||||
else
|
||||
} else {
|
||||
return swaggerType + "*";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Property p) {
|
||||
if(p instanceof StringProperty)
|
||||
if (p instanceof StringProperty) {
|
||||
return "new QString(\"\")";
|
||||
else if (p instanceof BooleanProperty)
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "false";
|
||||
else if(p instanceof DateProperty)
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "NULL";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "NULL";
|
||||
else if (p instanceof DoubleProperty)
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "0.0";
|
||||
else if (p instanceof FloatProperty)
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "0.0f";
|
||||
else if (p instanceof IntegerProperty)
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "0";
|
||||
else if (p instanceof LongProperty)
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "0L";
|
||||
else if (p instanceof DecimalProperty)
|
||||
} else if (p instanceof DecimalProperty) {
|
||||
return "0.0";
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "new QMap<QString, " + inner + ">()";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
if(!languageSpecificPrimitives.contains(inner)) {
|
||||
if (!languageSpecificPrimitives.contains(inner)) {
|
||||
inner += "*";
|
||||
}
|
||||
return "new QList<" + inner + ">()";
|
||||
}
|
||||
// else
|
||||
if(p instanceof RefProperty) {
|
||||
if (p instanceof RefProperty) {
|
||||
RefProperty rp = (RefProperty) p;
|
||||
return "new " + toModelName(rp.getSimpleRef()) + "()";
|
||||
}
|
||||
@ -275,28 +290,29 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
if(foundationClasses.contains(type))
|
||||
}
|
||||
if (foundationClasses.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelName(String type) {
|
||||
if(typeMapping.keySet().contains(type) ||
|
||||
if (typeMapping.keySet().contains(type) ||
|
||||
typeMapping.values().contains(type) ||
|
||||
importMapping.values().contains(type) ||
|
||||
defaultIncludes.contains(type) ||
|
||||
languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,19 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -14,18 +22,6 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/java";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "retrofit";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Retrofit client library.";
|
||||
}
|
||||
|
||||
public RetrofitClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/java";
|
||||
@ -35,7 +31,7 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "continue", "for", "new", "switch", "assert",
|
||||
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
|
||||
@ -70,6 +66,18 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "retrofit";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Retrofit client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -90,16 +98,18 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, do nothing
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// pet_id => petId
|
||||
name = camelize(name, true);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -113,8 +123,9 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -130,12 +141,11 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -148,30 +158,32 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>)objs.get("operations");
|
||||
if(operations != null) {
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
if (operations != null) {
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation operation : ops) {
|
||||
for (CodegenOperation operation : ops) {
|
||||
if (operation.hasConsumes == Boolean.TRUE) {
|
||||
Map<String, String> firstType = operation.consumes.get(0);
|
||||
if (firstType != null) {
|
||||
@ -180,7 +192,7 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf
|
||||
}
|
||||
}
|
||||
}
|
||||
if(operation.returnType == null) {
|
||||
if (operation.returnType == null) {
|
||||
operation.returnType = "Void";
|
||||
}
|
||||
}
|
||||
|
@ -1,36 +1,22 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String gemName = "swagger_client";
|
||||
protected String moduleName = null;
|
||||
protected String libFolder = "lib";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "ruby";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Ruby client library.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
|
||||
*/
|
||||
public String generateModuleName() {
|
||||
return camelize(gemName.replaceAll("[^\\w]+", "_"));
|
||||
}
|
||||
|
||||
public RubyClientCodegen() {
|
||||
super();
|
||||
moduleName = generateModuleName();
|
||||
@ -44,7 +30,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.clear();
|
||||
languageSpecificPrimitives.clear();
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
|
||||
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
|
||||
@ -83,6 +69,25 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "ruby";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Ruby client library.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
|
||||
*/
|
||||
public String generateModuleName() {
|
||||
return camelize(gemName.replaceAll("[^\\w]+", "_"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -99,12 +104,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
|
||||
@ -116,16 +120,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type)) {
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
if(type == null)
|
||||
}
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@ -139,16 +144,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
name = name.replaceAll("-", "_");
|
||||
|
||||
// if it's all uppper case, convert to lower case
|
||||
if (name.matches("^[A-Z_]*$"))
|
||||
if (name.matches("^[A-Z_]*$")) {
|
||||
name = name.toLowerCase();
|
||||
}
|
||||
|
||||
// camelize (lower first character) the variable name
|
||||
// petId => pet_id
|
||||
name = underscore(name);
|
||||
|
||||
// for reserved word or word starting with number, append _
|
||||
if(reservedWords.contains(name) || name.matches("^\\d.*"))
|
||||
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
|
||||
name = escapeReservedWord(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@ -162,8 +169,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
@ -173,8 +181,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toModelFilename(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
if (reservedWords.contains(name)) {
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
}
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber.rb => phone_number.rb
|
||||
@ -192,8 +201,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultApi";
|
||||
}
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
@ -201,8 +211,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return underscore(operationId);
|
||||
}
|
||||
|
@ -1,10 +1,25 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -16,18 +31,6 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
protected boolean authPreemptive = false;
|
||||
protected boolean asyncHttpClient = !authScheme.isEmpty();
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala client library.";
|
||||
}
|
||||
|
||||
public ScalaClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/scala";
|
||||
@ -37,7 +40,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
apiPackage = "io.swagger.client.api";
|
||||
modelPackage = "io.swagger.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "case", "catch", "class", "def", "do", "else", "extends",
|
||||
"false", "final", "finally", "for", "forSome", "if", "implicit",
|
||||
@ -99,6 +102,18 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "scala";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -115,12 +130,11 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -133,13 +147,14 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -149,53 +164,52 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return instantiationTypes.get("map") + "[String, " + inner + "]";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array") + "[" + inner + "]";
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String toDefaultValue(Property p) {
|
||||
if(p instanceof StringProperty)
|
||||
if (p instanceof StringProperty) {
|
||||
return "null";
|
||||
else if (p instanceof BooleanProperty)
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "null";
|
||||
else if(p instanceof DateProperty)
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "null";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "null";
|
||||
else if (p instanceof DoubleProperty)
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "null";
|
||||
else if (p instanceof FloatProperty)
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "null";
|
||||
else if (p instanceof IntegerProperty)
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "null";
|
||||
else if (p instanceof LongProperty)
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "null";
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "new HashMap[String, " + inner + "]() ";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return "new ListBuffer[" + inner + "]() ";
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return "null";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
return camelize(operationId, true);
|
||||
}
|
||||
|
@ -1,11 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.client";
|
||||
@ -14,18 +23,6 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "scalatra";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala server application with Scalatra.";
|
||||
}
|
||||
|
||||
public ScalatraServerCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/scalatra";
|
||||
@ -35,7 +32,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
apiPackage = "com.wordnik.client.api";
|
||||
modelPackage = "com.wordnik.client.model";
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
reservedWords = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"abstract", "continue", "for", "new", "switch", "assert",
|
||||
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
|
||||
@ -105,7 +102,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
instantiationTypes.put("array", "ArrayList");
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
|
||||
importMapping = new HashMap<String, String> ();
|
||||
importMapping = new HashMap<String, String>();
|
||||
importMapping.put("BigDecimal", "java.math.BigDecimal");
|
||||
importMapping.put("UUID", "java.util.UUID");
|
||||
importMapping.put("File", "java.io.File");
|
||||
@ -121,6 +118,18 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
importMapping.put("LocalTime", "org.joda.time.LocalTime");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "scalatra";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Scala server application with Scalatra.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
@ -139,7 +148,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation op: operationList) {
|
||||
for (CodegenOperation op : operationList) {
|
||||
op.httpMethod = op.httpMethod.toLowerCase();
|
||||
}
|
||||
return objs;
|
||||
@ -148,12 +157,11 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -166,13 +174,14 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
}
|
@ -1,13 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.Path;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "io.swagger.api";
|
||||
@ -19,18 +26,6 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
|
||||
|
||||
protected String configPackage = "";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "spring-mvc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
|
||||
}
|
||||
|
||||
public SpringMVCServerCodegen() {
|
||||
super.processOpts();
|
||||
outputFolder = "generated-code/javaSpringMVC";
|
||||
@ -62,6 +57,18 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
|
||||
);
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.SERVER;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "spring-mvc";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Java Spring-MVC Server application using the SpringFox integration.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processOpts() {
|
||||
super.processOpts();
|
||||
@ -93,12 +100,11 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -110,21 +116,24 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
String basePath = resourcePath;
|
||||
if(basePath.startsWith("/"))
|
||||
if (basePath.startsWith("/")) {
|
||||
basePath = basePath.substring(1);
|
||||
}
|
||||
int pos = basePath.indexOf("/");
|
||||
if(pos > 0)
|
||||
if (pos > 0) {
|
||||
basePath = basePath.substring(0, pos);
|
||||
}
|
||||
|
||||
if(basePath == "")
|
||||
if (basePath == "") {
|
||||
basePath = "default";
|
||||
else {
|
||||
if(co.path.startsWith("/" + basePath))
|
||||
} else {
|
||||
if (co.path.startsWith("/" + basePath)) {
|
||||
co.path = co.path.substring(("/" + basePath).length());
|
||||
}
|
||||
co.subresourceOperation = !co.path.isEmpty();
|
||||
}
|
||||
List<CodegenOperation> opList = operations.get(basePath);
|
||||
if(opList == null) {
|
||||
if (opList == null) {
|
||||
opList = new ArrayList<CodegenOperation>();
|
||||
operations.put(basePath, opList);
|
||||
}
|
||||
@ -133,32 +142,30 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
|
||||
}
|
||||
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>)objs.get("operations");
|
||||
if(operations != null) {
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
if (operations != null) {
|
||||
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation operation : ops) {
|
||||
if(operation.returnType == null)
|
||||
for (CodegenOperation operation : ops) {
|
||||
if (operation.returnType == null) {
|
||||
operation.returnType = "Void";
|
||||
else if(operation.returnType.startsWith("List")) {
|
||||
} else if (operation.returnType.startsWith("List")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("List<".length(), end);
|
||||
operation.returnContainer = "List";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Map")) {
|
||||
} else if (operation.returnType.startsWith("Map")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("Map<".length(), end);
|
||||
operation.returnContainer = "Map";
|
||||
}
|
||||
}
|
||||
else if(operation.returnType.startsWith("Set")) {
|
||||
} else if (operation.returnType.startsWith("Set")) {
|
||||
String rt = operation.returnType;
|
||||
int end = rt.lastIndexOf(">");
|
||||
if(end > 0) {
|
||||
if (end > 0) {
|
||||
operation.returnType = rt.substring("Set<".length(), end);
|
||||
operation.returnContainer = "Set";
|
||||
}
|
||||
|
@ -1,9 +1,10 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
@ -13,18 +14,6 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "docs";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "dynamic-html";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a dynamic HTML site.";
|
||||
}
|
||||
|
||||
public StaticDocCodegen() {
|
||||
super();
|
||||
outputFolder = "docs";
|
||||
@ -60,6 +49,18 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
instantiationTypes.put("map", "HashMap");
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "dynamic-html";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a dynamic HTML site.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name;
|
||||
|
@ -1,12 +1,20 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
private static final String ALL_OPERATIONS = "";
|
||||
@ -16,18 +24,6 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String sourceFolder = "src/main/scala";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "html";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a static HTML file.";
|
||||
}
|
||||
|
||||
public StaticHtmlGenerator() {
|
||||
super();
|
||||
outputFolder = "docs";
|
||||
@ -50,17 +46,28 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
reservedWords = new HashSet<String>();
|
||||
|
||||
languageSpecificPrimitives = new HashSet<String>();
|
||||
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
|
||||
public String getTypeDeclaration(Property p) {
|
||||
if(p instanceof ArrayProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
Property inner = ap.getItems();
|
||||
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
|
||||
}
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty mp = (MapProperty) p;
|
||||
Property inner = mp.getAdditionalProperties();
|
||||
|
||||
@ -73,7 +80,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
|
||||
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
|
||||
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
|
||||
for(CodegenOperation op: operationList) {
|
||||
for (CodegenOperation op : operationList) {
|
||||
op.httpMethod = op.httpMethod.toLowerCase();
|
||||
}
|
||||
return objs;
|
||||
@ -82,11 +89,11 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
|
||||
List<CodegenOperation> opList = operations.get(ALL_OPERATIONS);
|
||||
if(opList == null) {
|
||||
if (opList == null) {
|
||||
opList = new ArrayList<CodegenOperation>();
|
||||
operations.put(ALL_OPERATIONS, opList);
|
||||
}
|
||||
for (CodegenOperation addedOperation: opList){
|
||||
for (CodegenOperation addedOperation : opList) {
|
||||
if (addedOperation.operationId.equals(co.operationId) && addedOperation.path.equals(co.path) && addedOperation.httpMethod.equals(co.httpMethod)) {
|
||||
addedOperation.tags.addAll(co.tags);
|
||||
return;
|
||||
|
@ -1,14 +1,24 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Swagger;
|
||||
|
||||
import io.swagger.util.Json;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
public SwaggerGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
@ -21,24 +31,15 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
return "Creates a static swagger.json file.";
|
||||
}
|
||||
|
||||
public SwaggerGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processSwagger(Swagger swagger) {
|
||||
String swaggerString = Json.pretty(swagger);
|
||||
|
||||
try{
|
||||
try {
|
||||
String outputFile = outputFolder + File.separator + "swagger.json";
|
||||
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
|
||||
System.out.println("wrote file to " + outputFile);
|
||||
}
|
||||
catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,24 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.util.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Swagger;
|
||||
|
||||
import io.swagger.util.Yaml;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
public SwaggerYamlGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.DOCUMENTATION;
|
||||
}
|
||||
@ -21,23 +31,14 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi
|
||||
return "Creates a static swagger.yaml file.";
|
||||
}
|
||||
|
||||
public SwaggerYamlGenerator() {
|
||||
super();
|
||||
templateDir = "swagger";
|
||||
outputFolder = "generated-code/swagger";
|
||||
|
||||
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processSwagger(Swagger swagger) {
|
||||
try{
|
||||
try {
|
||||
String swaggerString = Yaml.mapper().writeValueAsString(swagger);
|
||||
String outputFile = outputFolder + File.separator + "swagger.yaml";
|
||||
FileUtils.writeStringToFile(new File(outputFile), swaggerString);
|
||||
System.out.println("wrote file to " + outputFile);
|
||||
}
|
||||
catch(Exception e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
@ -3,17 +3,29 @@ package io.swagger.codegen.languages;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterators;
|
||||
import com.google.common.collect.Lists;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenOperation;
|
||||
import io.swagger.codegen.CodegenProperty;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.Model;
|
||||
import io.swagger.models.Operation;
|
||||
import io.swagger.models.parameters.HeaderParameter;
|
||||
import io.swagger.models.parameters.Parameter;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ -21,18 +33,6 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}");
|
||||
protected String sourceFolder = "Classes/Swaggers";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "swift";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a swift client library.";
|
||||
}
|
||||
|
||||
public SwiftGenerator() {
|
||||
super();
|
||||
outputFolder = "generated-code/swift";
|
||||
@ -119,6 +119,45 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
importMapping = new HashMap<String, String>();
|
||||
}
|
||||
|
||||
private static String normalizePath(String path) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
int cursor = 0;
|
||||
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
|
||||
boolean found = matcher.find();
|
||||
while (found) {
|
||||
String stringBeforeMatch = path.substring(cursor, matcher.start());
|
||||
builder.append(stringBeforeMatch);
|
||||
|
||||
String group = matcher.group().substring(1, matcher.group().length() - 1);
|
||||
group = camelize(group, true);
|
||||
builder
|
||||
.append("{")
|
||||
.append(group)
|
||||
.append("}");
|
||||
|
||||
cursor = matcher.end();
|
||||
found = matcher.find();
|
||||
}
|
||||
|
||||
String stringAfterMatch = path.substring(cursor);
|
||||
builder.append(stringAfterMatch);
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "swift";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a swift client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String escapeReservedWord(String name) {
|
||||
return "_" + name; // add an underscore to the name
|
||||
@ -154,10 +193,12 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
String type = null;
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if (languageSpecificPrimitives.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type)) {
|
||||
return toModelName(type);
|
||||
} else
|
||||
}
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@ -202,8 +243,9 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
if (name.length() == 0) {
|
||||
return "DefaultAPI";
|
||||
}
|
||||
return initialCaps(name) + "API";
|
||||
}
|
||||
|
||||
@ -220,31 +262,4 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig {
|
||||
operation.setParameters(parameters);
|
||||
return super.fromOperation(path, httpMethod, operation, definitions);
|
||||
}
|
||||
|
||||
private static String normalizePath(String path) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
int cursor = 0;
|
||||
Matcher matcher = PATH_PARAM_PATTERN.matcher(path);
|
||||
boolean found = matcher.find();
|
||||
while (found) {
|
||||
String stringBeforeMatch = path.substring(cursor, matcher.start());
|
||||
builder.append(stringBeforeMatch);
|
||||
|
||||
String group = matcher.group().substring(1, matcher.group().length() - 1);
|
||||
group = camelize(group, true);
|
||||
builder
|
||||
.append("{")
|
||||
.append(group)
|
||||
.append("}");
|
||||
|
||||
cursor = matcher.end();
|
||||
found = matcher.find();
|
||||
}
|
||||
|
||||
String stringAfterMatch = path.substring(cursor);
|
||||
builder.append(stringAfterMatch);
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
@ -1,30 +1,36 @@
|
||||
package io.swagger.codegen.languages;
|
||||
|
||||
import io.swagger.util.Json;
|
||||
import io.swagger.codegen.*;
|
||||
import io.swagger.models.properties.*;
|
||||
import io.swagger.codegen.CodegenConfig;
|
||||
import io.swagger.codegen.CodegenType;
|
||||
import io.swagger.codegen.DefaultCodegen;
|
||||
import io.swagger.codegen.SupportingFile;
|
||||
import io.swagger.models.properties.ArrayProperty;
|
||||
import io.swagger.models.properties.BooleanProperty;
|
||||
import io.swagger.models.properties.DateProperty;
|
||||
import io.swagger.models.properties.DateTimeProperty;
|
||||
import io.swagger.models.properties.DecimalProperty;
|
||||
import io.swagger.models.properties.DoubleProperty;
|
||||
import io.swagger.models.properties.FloatProperty;
|
||||
import io.swagger.models.properties.IntegerProperty;
|
||||
import io.swagger.models.properties.LongProperty;
|
||||
import io.swagger.models.properties.MapProperty;
|
||||
import io.swagger.models.properties.Property;
|
||||
import io.swagger.models.properties.RefProperty;
|
||||
import io.swagger.models.properties.StringProperty;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected static String PREFIX = "Sami";
|
||||
protected Set<String> foundationClasses = new HashSet<String>();
|
||||
protected String sourceFolder = "client";
|
||||
protected static String PREFIX = "Sami";
|
||||
protected Map<String, String> namespaces = new HashMap<String, String>();
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "tizen";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Samsung Tizen C++ client library.";
|
||||
}
|
||||
|
||||
public TizenClientCodegen() {
|
||||
super();
|
||||
outputFolder = "generated-code/tizen";
|
||||
@ -71,7 +77,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
importMapping = new HashMap<String, String>();
|
||||
|
||||
namespaces = new HashMap<String, String> ();
|
||||
namespaces = new HashMap<String, String>();
|
||||
namespaces.put("DateTime", "Tizen::Base::DateTime");
|
||||
namespaces.put("Integer", "Tizen::Base::Integer");
|
||||
namespaces.put("Long", "Tizen::Base::Long");
|
||||
@ -85,7 +91,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
namespaces.put("JsonNumber", "Tizen::Web::Json");
|
||||
namespaces.put("JsonString", "Tizen::Web::Json");
|
||||
|
||||
foundationClasses = new HashSet<String> (
|
||||
foundationClasses = new HashSet<String>(
|
||||
Arrays.asList(
|
||||
"String",
|
||||
"Integer",
|
||||
@ -102,71 +108,84 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp"));
|
||||
}
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return "tizen";
|
||||
}
|
||||
|
||||
public String getHelp() {
|
||||
return "Generates a Samsung Tizen C++ client library.";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toInstantiationType(Property p) {
|
||||
if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return instantiationTypes.get("map");
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return instantiationTypes.get("array");
|
||||
}
|
||||
else
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(String name) {
|
||||
if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name))
|
||||
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
|
||||
return name;
|
||||
else
|
||||
} else {
|
||||
return name + "*";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getSwaggerType(Property p) {
|
||||
String swaggerType = super.getSwaggerType(p);
|
||||
String type = null;
|
||||
if(typeMapping.containsKey(swaggerType)) {
|
||||
if (typeMapping.containsKey(swaggerType)) {
|
||||
type = typeMapping.get(swaggerType);
|
||||
if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type))
|
||||
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
|
||||
return toModelName(type);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
type = swaggerType;
|
||||
}
|
||||
return toModelName(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTypeDeclaration(Property p) {
|
||||
String swaggerType = getSwaggerType(p);
|
||||
if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType))
|
||||
if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
|
||||
return toModelName(swaggerType);
|
||||
else
|
||||
} else {
|
||||
return swaggerType + "*";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelName(String type) {
|
||||
if(typeMapping.keySet().contains(type) ||
|
||||
if (typeMapping.keySet().contains(type) ||
|
||||
typeMapping.values().contains(type) ||
|
||||
foundationClasses.contains(type) ||
|
||||
importMapping.values().contains(type) ||
|
||||
defaultIncludes.contains(type) ||
|
||||
languageSpecificPrimitives.contains(type)) {
|
||||
return type;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
if(namespaces.containsKey(name)) {
|
||||
if (namespaces.containsKey(name)) {
|
||||
return "using " + namespaces.get(name) + ";";
|
||||
}
|
||||
return "#include \"" + name + ".h\"";
|
||||
@ -174,36 +193,35 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String toDefaultValue(Property p) {
|
||||
if(p instanceof StringProperty)
|
||||
if (p instanceof StringProperty) {
|
||||
return "new String()";
|
||||
else if (p instanceof BooleanProperty)
|
||||
} else if (p instanceof BooleanProperty) {
|
||||
return "new Boolean(false)";
|
||||
else if(p instanceof DateProperty)
|
||||
} else if (p instanceof DateProperty) {
|
||||
return "new DateTime()";
|
||||
else if(p instanceof DateTimeProperty)
|
||||
} else if (p instanceof DateTimeProperty) {
|
||||
return "new DateTime()";
|
||||
else if (p instanceof DoubleProperty)
|
||||
} else if (p instanceof DoubleProperty) {
|
||||
return "new Double()";
|
||||
else if (p instanceof FloatProperty)
|
||||
} else if (p instanceof FloatProperty) {
|
||||
return "new Float()";
|
||||
else if (p instanceof IntegerProperty)
|
||||
} else if (p instanceof IntegerProperty) {
|
||||
return "new Integer()";
|
||||
else if (p instanceof LongProperty)
|
||||
} else if (p instanceof LongProperty) {
|
||||
return "new Long()";
|
||||
else if (p instanceof DecimalProperty)
|
||||
} else if (p instanceof DecimalProperty) {
|
||||
return "new Long()";
|
||||
else if (p instanceof MapProperty) {
|
||||
} else if (p instanceof MapProperty) {
|
||||
MapProperty ap = (MapProperty) p;
|
||||
String inner = getSwaggerType(ap.getAdditionalProperties());
|
||||
return "new HashMap()";
|
||||
}
|
||||
else if (p instanceof ArrayProperty) {
|
||||
} else if (p instanceof ArrayProperty) {
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
String inner = getSwaggerType(ap.getItems());
|
||||
return "new ArrayList()";
|
||||
}
|
||||
// else
|
||||
if(p instanceof RefProperty) {
|
||||
if (p instanceof RefProperty) {
|
||||
RefProperty rp = (RefProperty) p;
|
||||
return "new " + toModelName(rp.getSimpleRef()) + "()";
|
||||
}
|
||||
@ -236,7 +254,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
|
||||
@Override
|
||||
public String toVarName(String name) {
|
||||
String paramName = name.replaceAll("[^a-zA-Z0-9_]","");
|
||||
String paramName = name.replaceAll("[^a-zA-Z0-9_]", "");
|
||||
paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
|
||||
return "p" + paramName;
|
||||
}
|
||||
@ -248,8 +266,9 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
|
||||
@Override
|
||||
public String toOperationId(String operationId) {
|
||||
// method name cannot use reserved keyword, e.g. return$
|
||||
if(reservedWords.contains(operationId))
|
||||
if (reservedWords.contains(operationId)) {
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
}
|
||||
|
||||
// add_pet_by_id => addPetById
|
||||
return camelize(operationId, true);
|
||||
|
@ -8,43 +8,43 @@ import static java.net.URI.create;
|
||||
|
||||
class ApiUtils {
|
||||
|
||||
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
|
||||
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
|
||||
println "url=$url uriPath=$uriPath"
|
||||
def http = new HTTPBuilder(url)
|
||||
http.request( Method.valueOf(method), JSON ) {
|
||||
uri.path = uriPath
|
||||
uri.query = queryParams
|
||||
response.success = { resp, json ->
|
||||
if (type != null) {
|
||||
onSuccess(parse(json, container, type))
|
||||
}
|
||||
}
|
||||
response.failure = { resp ->
|
||||
onFailure(resp.status, resp.statusLine.reasonPhrase)
|
||||
}
|
||||
}
|
||||
}
|
||||
def invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, method, container, type) {
|
||||
def (url, uriPath) = buildUrlAndUriPath(basePath, versionPath, resourcePath)
|
||||
println "url=$url uriPath=$uriPath"
|
||||
def http = new HTTPBuilder(url)
|
||||
http.request( Method.valueOf(method), JSON ) {
|
||||
uri.path = uriPath
|
||||
uri.query = queryParams
|
||||
response.success = { resp, json ->
|
||||
if (type != null) {
|
||||
onSuccess(parse(json, container, type))
|
||||
}
|
||||
}
|
||||
response.failure = { resp ->
|
||||
onFailure(resp.status, resp.statusLine.reasonPhrase)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
|
||||
// HTTPBuilder expects to get as its constructor parameter an URL,
|
||||
// without any other additions like path, therefore we need to cut the path
|
||||
// from the basePath as it is represented by swagger APIs
|
||||
// we use java.net.URI to manipulate the basePath
|
||||
// then the uriPath will hold the rest of the path
|
||||
URI baseUri = create(basePath)
|
||||
def pathOnly = baseUri.getPath()
|
||||
[basePath-pathOnly, pathOnly+versionPath+resourcePath]
|
||||
}
|
||||
def buildUrlAndUriPath(basePath, versionPath, resourcePath) {
|
||||
// HTTPBuilder expects to get as its constructor parameter an URL,
|
||||
// without any other additions like path, therefore we need to cut the path
|
||||
// from the basePath as it is represented by swagger APIs
|
||||
// we use java.net.URI to manipulate the basePath
|
||||
// then the uriPath will hold the rest of the path
|
||||
URI baseUri = create(basePath)
|
||||
def pathOnly = baseUri.getPath()
|
||||
[basePath-pathOnly, pathOnly+versionPath+resourcePath]
|
||||
}
|
||||
|
||||
|
||||
def parse(object, container, clazz) {
|
||||
if (container == "List") {
|
||||
return object.collect {parse(it, "", clazz)}
|
||||
} else {
|
||||
return clazz.newInstance(object)
|
||||
}
|
||||
}
|
||||
def parse(object, container, clazz) {
|
||||
if (container == "List") {
|
||||
return object.collect {parse(it, "", clazz)}
|
||||
} else {
|
||||
return clazz.newInstance(object)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,9 +1,6 @@
|
||||
package {{package}};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
import groovyx.net.http.*
|
||||
import static groovyx.net.http.ContentType.*
|
||||
import static groovyx.net.http.Method.*
|
||||
@ -17,7 +14,7 @@ import java.util.*;
|
||||
|
||||
@Mixin(ApiUtils)
|
||||
{{#operations}}
|
||||
class {{classname}} {
|
||||
class {{classname}} {
|
||||
String basePath = "{{basePath}}"
|
||||
String versionPath = "/api/v1"
|
||||
|
||||
@ -52,5 +49,5 @@ class {{classname}} {
|
||||
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
}
|
||||
{{/operations}}
|
@ -6,24 +6,24 @@ archivesBaseName = 'swagger-gen-groovy'
|
||||
version = '0.1'
|
||||
|
||||
buildscript {
|
||||
repositories {
|
||||
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
|
||||
}
|
||||
dependencies {
|
||||
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16')
|
||||
}
|
||||
repositories {
|
||||
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
|
||||
}
|
||||
dependencies {
|
||||
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.16')
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
mavenLocal()
|
||||
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
|
||||
maven { url "http://$artifactory:8080/artifactory/repo" }
|
||||
mavenCentral()
|
||||
mavenLocal()
|
||||
mavenCentral(artifactUrls: ['http://maven.springframework.org/milestone'])
|
||||
maven { url "http://$artifactory:8080/artifactory/repo" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
groovy "org.codehaus.groovy:groovy-all:2.0.5"
|
||||
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6'
|
||||
groovy "org.codehaus.groovy:groovy-all:2.0.5"
|
||||
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.6'
|
||||
|
||||
|
||||
}
|
||||
|
@ -4,9 +4,9 @@ import groovy.transform.Canonical
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
@Canonical
|
||||
class {{classname}} {
|
||||
{{#model}}
|
||||
@Canonical
|
||||
class {{classname}} {
|
||||
{{#vars}}
|
||||
|
||||
{{#description}}/* {{{description}}} */
|
||||
@ -15,7 +15,7 @@ class {{classname}} {
|
||||
{{/vars}}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
{{/model}}
|
||||
{{/model}}
|
||||
{{/models}}
|
@ -40,468 +40,482 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||
import {{invokerPackage}}.auth.OAuth;
|
||||
|
||||
public class ApiClient {
|
||||
private Map<String, Client> hostMap = new HashMap<String, Client>();
|
||||
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||
private boolean debugging = false;
|
||||
private String basePath = "{{basePath}}";
|
||||
private Map
|
||||
<String, Client> hostMap = new HashMap
|
||||
<String, Client>();
|
||||
private Map
|
||||
<String, String> defaultHeaderMap = new HashMap
|
||||
<String, String>();
|
||||
private boolean debugging = false;
|
||||
private String basePath = "{{basePath}}";
|
||||
|
||||
private Map<String, Authentication> authentications;
|
||||
private Map
|
||||
<String, Authentication> authentications;
|
||||
|
||||
private DateFormat dateFormat;
|
||||
private DateFormat dateFormat;
|
||||
|
||||
public ApiClient() {
|
||||
// Use ISO 8601 format for date and datetime.
|
||||
// See https://en.wikipedia.org/wiki/ISO_8601
|
||||
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
public ApiClient() {
|
||||
// Use ISO 8601 format for date and datetime.
|
||||
// See https://en.wikipedia.org/wiki/ISO_8601
|
||||
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
|
||||
// Use UTC as the default time zone.
|
||||
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
// Use UTC as the default time zone.
|
||||
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Java-Swagger");
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Java-Swagger");
|
||||
|
||||
// Setup authentications (key: authentication name, value: authentication).
|
||||
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
|
||||
// Setup authentications (key: authentication name, value: authentication).
|
||||
authentications = new HashMap
|
||||
<String, Authentication>();{{#authMethods}}{{#isBasic}}
|
||||
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
|
||||
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
|
||||
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
|
||||
// Prevent the authentications from being modified.
|
||||
authentications = Collections.unmodifiableMap(authentications);
|
||||
}
|
||||
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
public ApiClient setBasePath(String basePath) {
|
||||
this.basePath = basePath;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentications (key: authentication name, value: authentication).
|
||||
*/
|
||||
public Map<String, Authentication> getAuthentications() {
|
||||
return authentications;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication for the given name.
|
||||
*
|
||||
* @param authName The authentication name
|
||||
* @return The authentication, null if not found
|
||||
*/
|
||||
public Authentication getAuthentication(String authName) {
|
||||
return authentications.get(authName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set username for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setUsername(String username) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setUsername(username);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set password for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setPassword(password);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key value for the first API key authentication.
|
||||
*/
|
||||
public void setApiKey(String apiKey) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key prefix for the first API key authentication.
|
||||
*/
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the User-Agent header's value (by adding to the default header map).
|
||||
*/
|
||||
public ApiClient setUserAgent(String userAgent) {
|
||||
addDefaultHeader("User-Agent", userAgent);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a default header.
|
||||
*
|
||||
* @param key The header's key
|
||||
* @param value The header's value
|
||||
*/
|
||||
public ApiClient addDefaultHeader(String key, String value) {
|
||||
defaultHeaderMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that whether debugging is enabled for this API client.
|
||||
*/
|
||||
public boolean isDebugging() {
|
||||
return debugging;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable/disable debugging for this API client.
|
||||
*
|
||||
* @param debugging To enable (true) or disable (false) debugging
|
||||
*/
|
||||
public ApiClient setDebugging(boolean debugging) {
|
||||
this.debugging = debugging;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the date format used to parse/format date parameters.
|
||||
*/
|
||||
public DateFormat getDateFormat() {
|
||||
return dateFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the date format used to parse/format date parameters.
|
||||
*/
|
||||
public ApiClient getDateFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given string into Date object.
|
||||
*/
|
||||
public Date parseDate(String str) {
|
||||
try {
|
||||
return dateFormat.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDate(Date date) {
|
||||
return dateFormat.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given parameter object into string.
|
||||
*/
|
||||
public String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDate((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(Object o : (Collection)param) {
|
||||
if(b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Accept header's value from the given accepts array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use all of them (joining into a string)
|
||||
*
|
||||
* @param accepts The accepts array to select from
|
||||
* @return The Accept header to use. If the given array is empty,
|
||||
* null will be returned (not to set the Accept header explicitly).
|
||||
*/
|
||||
public String selectHeaderAccept(String[] accepts) {
|
||||
if (accepts.length == 0) return null;
|
||||
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
|
||||
return StringUtil.join(accepts, ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Content-Type header's value from the given array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use the first one of the array.
|
||||
*
|
||||
* @param contentTypes The Content-Type array to select from
|
||||
* @return The Content-Type header to use. If the given array is empty,
|
||||
* JSON will be used.
|
||||
*/
|
||||
public String selectHeaderContentType(String[] contentTypes) {
|
||||
if (contentTypes.length == 0) return "application/json";
|
||||
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
|
||||
return contentTypes[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape the given string to be used as URL query value.
|
||||
*/
|
||||
public String escapeString(String str) {
|
||||
try {
|
||||
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the given JSON string to Java object.
|
||||
*
|
||||
* @param json The JSON string
|
||||
* @param containerType The container type, one of "list", "array" or ""
|
||||
* @param cls The type of the Java object
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public Object deserialize(String json, String containerType, Class cls) throws ApiException {
|
||||
if(null != containerType) {
|
||||
containerType = containerType.toLowerCase();
|
||||
}
|
||||
try{
|
||||
if("list".equals(containerType) || "array".equals(containerType)) {
|
||||
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
|
||||
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
|
||||
return response;
|
||||
}
|
||||
else if(String.class.equals(cls)) {
|
||||
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
|
||||
return json.substring(1, json.length() - 2);
|
||||
else
|
||||
return json;
|
||||
}
|
||||
else {
|
||||
return JsonUtil.getJsonMapper().readValue(json, cls);
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new ApiException(500, e.getMessage(), null, json);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into JSON string.
|
||||
*/
|
||||
public String serialize(Object obj) throws ApiException {
|
||||
try {
|
||||
if (obj != null)
|
||||
return JsonUtil.getJsonMapper().writeValueAsString(obj);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new ApiException(500, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke API by sending HTTP request with the given options.
|
||||
*
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
* @param accept The request's Accept header
|
||||
* @param contentType The request's Content-Type header
|
||||
* @param authNames The authentications to apply
|
||||
* @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 {
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
Client client = getClient();
|
||||
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(String key : queryParams.keySet()) {
|
||||
String value = queryParams.get(key);
|
||||
if (value != null){
|
||||
if(b.toString().length() == 0)
|
||||
b.append("?");
|
||||
else
|
||||
b.append("&");
|
||||
b.append(escapeString(key)).append("=").append(escapeString(value));
|
||||
}
|
||||
}
|
||||
String querystring = b.toString();
|
||||
|
||||
Builder builder;
|
||||
if (accept == null)
|
||||
builder = client.resource(basePath + path + querystring).getRequestBuilder();
|
||||
else
|
||||
builder = client.resource(basePath + path + querystring).accept(accept);
|
||||
|
||||
for(String key : headerParams.keySet()) {
|
||||
builder = builder.header(key, headerParams.get(key));
|
||||
}
|
||||
for(String key : defaultHeaderMap.keySet()) {
|
||||
if(!headerParams.containsKey(key)) {
|
||||
builder = builder.header(key, defaultHeaderMap.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
ClientResponse response = null;
|
||||
|
||||
if("GET".equals(method)) {
|
||||
response = (ClientResponse) builder.get(ClientResponse.class);
|
||||
}
|
||||
else if ("POST".equals(method)) {
|
||||
if (contentType.startsWith("application/x-www-form-urlencoded")) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).post(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if (body == null) {
|
||||
response = builder.post(ClientResponse.class, null);
|
||||
} else if(body instanceof FormDataMultiPart) {
|
||||
response = builder.type(contentType).post(ClientResponse.class, body);
|
||||
}
|
||||
else
|
||||
response = builder.type(contentType).post(ClientResponse.class, serialize(body));
|
||||
}
|
||||
else if ("PUT".equals(method)) {
|
||||
if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).put(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if(body == null) {
|
||||
response = builder.put(ClientResponse.class, serialize(body));
|
||||
} else {
|
||||
response = builder.type(contentType).put(ClientResponse.class, serialize(body));
|
||||
}
|
||||
}
|
||||
else if ("DELETE".equals(method)) {
|
||||
if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).delete(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if(body == null) {
|
||||
response = builder.delete(ClientResponse.class);
|
||||
} else {
|
||||
response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new ApiException(500, "unknown method type " + method);
|
||||
}
|
||||
|
||||
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
|
||||
return null;
|
||||
}
|
||||
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
|
||||
if(response.hasEntity()) {
|
||||
return (String) response.getEntity(String.class);
|
||||
}
|
||||
else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
else {
|
||||
String message = "error";
|
||||
String respBody = null;
|
||||
if(response.hasEntity()) {
|
||||
try{
|
||||
respBody = String.valueOf(response.getEntity(String.class));
|
||||
message = respBody;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
// e.printStackTrace();
|
||||
}
|
||||
}
|
||||
throw new ApiException(
|
||||
response.getClientResponseStatus().getStatusCode(),
|
||||
message,
|
||||
response.getHeaders(),
|
||||
respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update query and header parameters based on authentication settings.
|
||||
*
|
||||
* @param authNames The authentications to apply
|
||||
*/
|
||||
private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
|
||||
for (String authName : authNames) {
|
||||
Authentication auth = authentications.get(authName);
|
||||
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the given form parameters as request body.
|
||||
*/
|
||||
private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
|
||||
StringBuilder formParamBuilder = new StringBuilder();
|
||||
|
||||
for (Entry<String, String> param : formParams.entrySet()) {
|
||||
String keyStr = parameterToString(param.getKey());
|
||||
String valueStr = parameterToString(param.getValue());
|
||||
|
||||
try {
|
||||
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
|
||||
.append("=")
|
||||
.append(URLEncoder.encode(valueStr, "utf8"));
|
||||
formParamBuilder.append("&");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
// move on to next
|
||||
}
|
||||
}
|
||||
String encodedFormParams = formParamBuilder.toString();
|
||||
if (encodedFormParams.endsWith("&")) {
|
||||
encodedFormParams = encodedFormParams.substring(0,
|
||||
encodedFormParams.length() - 1);
|
||||
}
|
||||
return encodedFormParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an existing client or create a new client to handle HTTP request.
|
||||
*/
|
||||
private Client getClient() {
|
||||
if(!hostMap.containsKey(basePath)) {
|
||||
Client client = Client.create();
|
||||
if (debugging)
|
||||
client.addFilter(new LoggingFilter());
|
||||
hostMap.put(basePath, client);
|
||||
}
|
||||
return hostMap.get(basePath);
|
||||
}
|
||||
// Prevent the authentications from being modified.
|
||||
authentications = Collections.unmodifiableMap(authentications);
|
||||
}
|
||||
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
public ApiClient setBasePath(String basePath) {
|
||||
this.basePath = basePath;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentications (key: authentication name, value: authentication).
|
||||
*/
|
||||
public Map
|
||||
<String, Authentication> getAuthentications() {
|
||||
return authentications;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication for the given name.
|
||||
*
|
||||
* @param authName The authentication name
|
||||
* @return The authentication, null if not found
|
||||
*/
|
||||
public Authentication getAuthentication(String authName) {
|
||||
return authentications.get(authName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set username for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setUsername(String username) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setUsername(username);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set password for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setPassword(password);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key value for the first API key authentication.
|
||||
*/
|
||||
public void setApiKey(String apiKey) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key prefix for the first API key authentication.
|
||||
*/
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the User-Agent header's value (by adding to the default header map).
|
||||
*/
|
||||
public ApiClient setUserAgent(String userAgent) {
|
||||
addDefaultHeader("User-Agent", userAgent);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a default header.
|
||||
*
|
||||
* @param key The header's key
|
||||
* @param value The header's value
|
||||
*/
|
||||
public ApiClient addDefaultHeader(String key, String value) {
|
||||
defaultHeaderMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that whether debugging is enabled for this API client.
|
||||
*/
|
||||
public boolean isDebugging() {
|
||||
return debugging;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable/disable debugging for this API client.
|
||||
*
|
||||
* @param debugging To enable (true) or disable (false) debugging
|
||||
*/
|
||||
public ApiClient setDebugging(boolean debugging) {
|
||||
this.debugging = debugging;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the date format used to parse/format date parameters.
|
||||
*/
|
||||
public DateFormat getDateFormat() {
|
||||
return dateFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the date format used to parse/format date parameters.
|
||||
*/
|
||||
public ApiClient getDateFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given string into Date object.
|
||||
*/
|
||||
public Date parseDate(String str) {
|
||||
try {
|
||||
return dateFormat.parse(str);
|
||||
} catch (java.text.ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDate(Date date) {
|
||||
return dateFormat.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given parameter object into string.
|
||||
*/
|
||||
public String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDate((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(Object o : (Collection)param) {
|
||||
if(b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Accept header's value from the given accepts array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use all of them (joining into a string)
|
||||
*
|
||||
* @param accepts The accepts array to select from
|
||||
* @return The Accept header to use. If the given array is empty,
|
||||
* null will be returned (not to set the Accept header explicitly).
|
||||
*/
|
||||
public String selectHeaderAccept(String[] accepts) {
|
||||
if (accepts.length == 0) return null;
|
||||
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
|
||||
return StringUtil.join(accepts, ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Content-Type header's value from the given array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use the first one of the array.
|
||||
*
|
||||
* @param contentTypes The Content-Type array to select from
|
||||
* @return The Content-Type header to use. If the given array is empty,
|
||||
* JSON will be used.
|
||||
*/
|
||||
public String selectHeaderContentType(String[] contentTypes) {
|
||||
if (contentTypes.length == 0) return "application/json";
|
||||
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
|
||||
return contentTypes[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape the given string to be used as URL query value.
|
||||
*/
|
||||
public String escapeString(String str) {
|
||||
try {
|
||||
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the given JSON string to Java object.
|
||||
*
|
||||
* @param json The JSON string
|
||||
* @param containerType The container type, one of "list", "array" or ""
|
||||
* @param cls The type of the Java object
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public Object deserialize(String json, String containerType, Class cls) throws ApiException {
|
||||
if(null != containerType) {
|
||||
containerType = containerType.toLowerCase();
|
||||
}
|
||||
try{
|
||||
if("list".equals(containerType) || "array".equals(containerType)) {
|
||||
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
|
||||
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
|
||||
return response;
|
||||
}
|
||||
else if(String.class.equals(cls)) {
|
||||
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
|
||||
return json.substring(1, json.length() - 2);
|
||||
else
|
||||
return json;
|
||||
}
|
||||
else {
|
||||
return JsonUtil.getJsonMapper().readValue(json, cls);
|
||||
}
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new ApiException(500, e.getMessage(), null, json);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into JSON string.
|
||||
*/
|
||||
public String serialize(Object obj) throws ApiException {
|
||||
try {
|
||||
if (obj != null)
|
||||
return JsonUtil.getJsonMapper().writeValueAsString(obj);
|
||||
else
|
||||
return null;
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new ApiException(500, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke API by sending HTTP request with the given options.
|
||||
*
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
* @param accept The request's Accept header
|
||||
* @param contentType The request's Content-Type header
|
||||
* @param authNames The authentications to apply
|
||||
* @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 {
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
Client client = getClient();
|
||||
|
||||
StringBuilder b = new StringBuilder();
|
||||
for(String key : queryParams.keySet()) {
|
||||
String value = queryParams.get(key);
|
||||
if (value != null){
|
||||
if(b.toString().length() == 0)
|
||||
b.append("?");
|
||||
else
|
||||
b.append("&");
|
||||
b.append(escapeString(key)).append("=").append(escapeString(value));
|
||||
}
|
||||
}
|
||||
String querystring = b.toString();
|
||||
|
||||
Builder builder;
|
||||
if (accept == null)
|
||||
builder = client.resource(basePath + path + querystring).getRequestBuilder();
|
||||
else
|
||||
builder = client.resource(basePath + path + querystring).accept(accept);
|
||||
|
||||
for(String key : headerParams.keySet()) {
|
||||
builder = builder.header(key, headerParams.get(key));
|
||||
}
|
||||
for(String key : defaultHeaderMap.keySet()) {
|
||||
if(!headerParams.containsKey(key)) {
|
||||
builder = builder.header(key, defaultHeaderMap.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
ClientResponse response = null;
|
||||
|
||||
if("GET".equals(method)) {
|
||||
response = (ClientResponse) builder.get(ClientResponse.class);
|
||||
}
|
||||
else if ("POST".equals(method)) {
|
||||
if (contentType.startsWith("application/x-www-form-urlencoded")) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).post(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if (body == null) {
|
||||
response = builder.post(ClientResponse.class, null);
|
||||
} else if(body instanceof FormDataMultiPart) {
|
||||
response = builder.type(contentType).post(ClientResponse.class, body);
|
||||
}
|
||||
else
|
||||
response = builder.type(contentType).post(ClientResponse.class, serialize(body));
|
||||
}
|
||||
else if ("PUT".equals(method)) {
|
||||
if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).put(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if(body == null) {
|
||||
response = builder.put(ClientResponse.class, serialize(body));
|
||||
} else {
|
||||
response = builder.type(contentType).put(ClientResponse.class, serialize(body));
|
||||
}
|
||||
}
|
||||
else if ("DELETE".equals(method)) {
|
||||
if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
String encodedFormParams = this
|
||||
.getXWWWFormUrlencodedParams(formParams);
|
||||
response = builder.type(contentType).delete(ClientResponse.class,
|
||||
encodedFormParams);
|
||||
} else if(body == null) {
|
||||
response = builder.delete(ClientResponse.class);
|
||||
} else {
|
||||
response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new ApiException(500, "unknown method type " + method);
|
||||
}
|
||||
|
||||
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
|
||||
return null;
|
||||
}
|
||||
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
|
||||
if(response.hasEntity()) {
|
||||
return (String) response.getEntity(String.class);
|
||||
}
|
||||
else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
else {
|
||||
String message = "error";
|
||||
String respBody = null;
|
||||
if(response.hasEntity()) {
|
||||
try{
|
||||
respBody = String.valueOf(response.getEntity(String.class));
|
||||
message = respBody;
|
||||
}
|
||||
catch (RuntimeException e) {
|
||||
// e.printStackTrace();
|
||||
}
|
||||
}
|
||||
throw new ApiException(
|
||||
response.getClientResponseStatus().getStatusCode(),
|
||||
message,
|
||||
response.getHeaders(),
|
||||
respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update query and header parameters based on authentication settings.
|
||||
*
|
||||
* @param authNames The authentications to apply
|
||||
*/
|
||||
private void updateParamsForAuth(String[] authNames, Map
|
||||
<String, String> queryParams, Map
|
||||
<String, String> headerParams) {
|
||||
for (String authName : authNames) {
|
||||
Authentication auth = authentications.get(authName);
|
||||
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the given form parameters as request body.
|
||||
*/
|
||||
private String getXWWWFormUrlencodedParams(Map
|
||||
<String, String> formParams) {
|
||||
StringBuilder formParamBuilder = new StringBuilder();
|
||||
|
||||
for (Entry
|
||||
<String, String> param : formParams.entrySet()) {
|
||||
String keyStr = parameterToString(param.getKey());
|
||||
String valueStr = parameterToString(param.getValue());
|
||||
|
||||
try {
|
||||
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
|
||||
.append("=")
|
||||
.append(URLEncoder.encode(valueStr, "utf8"));
|
||||
formParamBuilder.append("&");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
// move on to next
|
||||
}
|
||||
}
|
||||
String encodedFormParams = formParamBuilder.toString();
|
||||
if (encodedFormParams.endsWith("&")) {
|
||||
encodedFormParams = encodedFormParams.substring(0,
|
||||
encodedFormParams.length() - 1);
|
||||
}
|
||||
return encodedFormParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an existing client or create a new client to handle HTTP request.
|
||||
*/
|
||||
private Client getClient() {
|
||||
if(!hostMap.containsKey(basePath)) {
|
||||
Client client = Client.create();
|
||||
if (debugging)
|
||||
client.addFilter(new LoggingFilter());
|
||||
hostMap.put(basePath, client);
|
||||
}
|
||||
return hostMap.get(basePath);
|
||||
}
|
||||
}
|
||||
|
@ -1,21 +1,21 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
public class Configuration {
|
||||
private static ApiClient defaultApiClient = new ApiClient();
|
||||
private static ApiClient defaultApiClient = new ApiClient();
|
||||
|
||||
/**
|
||||
* Get the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static ApiClient getDefaultApiClient() {
|
||||
return defaultApiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static void setDefaultApiClient(ApiClient apiClient) {
|
||||
defaultApiClient = apiClient;
|
||||
}
|
||||
/**
|
||||
* Get the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static ApiClient getDefaultApiClient() {
|
||||
return defaultApiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static void setDefaultApiClient(ApiClient apiClient) {
|
||||
defaultApiClient = apiClient;
|
||||
}
|
||||
}
|
||||
|
@ -8,16 +8,16 @@ import com.fasterxml.jackson.core.JsonGenerator.Feature;
|
||||
import com.fasterxml.jackson.datatype.joda.*;
|
||||
|
||||
public class JsonUtil {
|
||||
public static ObjectMapper mapper;
|
||||
public static ObjectMapper mapper;
|
||||
|
||||
static {
|
||||
mapper = new ObjectMapper();
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
mapper.registerModule(new JodaModule());
|
||||
}
|
||||
|
||||
public static ObjectMapper getJsonMapper() {
|
||||
return mapper;
|
||||
}
|
||||
static {
|
||||
mapper = new ObjectMapper();
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
mapper.registerModule(new JodaModule());
|
||||
}
|
||||
|
||||
public static ObjectMapper getJsonMapper() {
|
||||
return mapper;
|
||||
}
|
||||
}
|
||||
|
@ -1,41 +1,41 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
public class StringUtil {
|
||||
/**
|
||||
* Check if the given array contains the given value (with case-insensitive comparison).
|
||||
*
|
||||
* @param array The array
|
||||
* @param value The value to search
|
||||
* @return true if the array contains the value
|
||||
*/
|
||||
public static boolean containsIgnoreCase(String[] array, String value) {
|
||||
for (String str : array) {
|
||||
if (value == null && str == null) return true;
|
||||
if (value != null && value.equalsIgnoreCase(str)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Check if the given array contains the given value (with case-insensitive comparison).
|
||||
*
|
||||
* @param array The array
|
||||
* @param value The value to search
|
||||
* @return true if the array contains the value
|
||||
*/
|
||||
public static boolean containsIgnoreCase(String[] array, String value) {
|
||||
for (String str : array) {
|
||||
if (value == null && str == null) return true;
|
||||
if (value != null && value.equalsIgnoreCase(str)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an array of strings with the given separator.
|
||||
* <p>
|
||||
/**
|
||||
* Join an array of strings with the given separator.
|
||||
* <p>
|
||||
* Note: This might be replaced by utility method from commons-lang or guava someday
|
||||
* if one of those libraries is added as dependency.
|
||||
* </p>
|
||||
*
|
||||
* @param array The array of strings
|
||||
* @param separator The separator
|
||||
* @return the resulting string
|
||||
*/
|
||||
public static String join(String[] array, String separator) {
|
||||
int len = array.length;
|
||||
if (len == 0) return "";
|
||||
*
|
||||
* @param array The array of strings
|
||||
* @param separator The separator
|
||||
* @return the resulting string
|
||||
*/
|
||||
public static String join(String[] array, String separator) {
|
||||
int len = array.length;
|
||||
if (len == 0) return "";
|
||||
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append(array[0]);
|
||||
for (int i = 1; i < len; i++) {
|
||||
out.append(separator).append(array[i]);
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append(array[0]);
|
||||
for (int i = 1; i < len; i++) {
|
||||
out.append(separator).append(array[i]);
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
|
@ -21,7 +21,7 @@ import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
public class {{classname}} {
|
||||
private ApiClient apiClient;
|
||||
|
||||
public {{classname}}() {
|
||||
@ -44,8 +44,8 @@ public class {{classname}} {
|
||||
/**
|
||||
* {{summary}}
|
||||
* {{notes}}
|
||||
{{#allParams}} * @param {{paramName}} {{description}}
|
||||
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
{{#allParams}} * @param {{paramName}} {{description}}
|
||||
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
*/
|
||||
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
|
||||
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
|
||||
@ -61,9 +61,15 @@ public class {{classname}} {
|
||||
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
|
||||
|
||||
// query params
|
||||
Map<String, String> queryParams = new HashMap<String, String>();
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
Map<String, String> formParams = new HashMap<String, String>();
|
||||
Map
|
||||
<String, String> queryParams = new HashMap
|
||||
<String, String>();
|
||||
Map
|
||||
<String, String> headerParams = new HashMap
|
||||
<String, String>();
|
||||
Map
|
||||
<String, String> formParams = new HashMap
|
||||
<String, String>();
|
||||
|
||||
{{#queryParams}}if ({{paramName}} != null)
|
||||
queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
|
||||
@ -121,5 +127,5 @@ public class {{classname}} {
|
||||
}
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -4,9 +4,11 @@ import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
public class ApiException extends Exception {
|
||||
private int code = 0;
|
||||
private String message = null;
|
||||
private Map<String, List<String>> responseHeaders = null;
|
||||
private int code = 0;
|
||||
private String message = null;
|
||||
private Map
|
||||
<String, List
|
||||
<String>> responseHeaders = null;
|
||||
private String responseBody = null;
|
||||
|
||||
public ApiException() {}
|
||||
@ -16,7 +18,10 @@ public class ApiException extends Exception {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
public ApiException(int code, String message, Map
|
||||
<String
|
||||
, List
|
||||
<String>> responseHeaders, String responseBody) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
this.responseHeaders = responseHeaders;
|
||||
@ -34,7 +39,10 @@ public class ApiException extends Exception {
|
||||
/**
|
||||
* Get the HTTP response headers.
|
||||
*/
|
||||
public Map<String, List<String>> getResponseHeaders() {
|
||||
public Map
|
||||
<String
|
||||
, List
|
||||
<String>> getResponseHeaders() {
|
||||
return responseHeaders;
|
||||
}
|
||||
|
||||
@ -44,4 +52,4 @@ public class ApiException extends Exception {
|
||||
public String getResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,53 +3,55 @@ package {{invokerPackage}}.auth;
|
||||
import java.util.Map;
|
||||
|
||||
public class ApiKeyAuth implements Authentication {
|
||||
private final String location;
|
||||
private final String paramName;
|
||||
private final String location;
|
||||
private final String paramName;
|
||||
|
||||
private String apiKey;
|
||||
private String apiKeyPrefix;
|
||||
private String apiKey;
|
||||
private String apiKeyPrefix;
|
||||
|
||||
public ApiKeyAuth(String location, String paramName) {
|
||||
this.location = location;
|
||||
this.paramName = paramName;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
public String getParamName() {
|
||||
return paramName;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getApiKeyPrefix() {
|
||||
return apiKeyPrefix;
|
||||
}
|
||||
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
this.apiKeyPrefix = apiKeyPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
|
||||
String value;
|
||||
if (apiKeyPrefix != null) {
|
||||
value = apiKeyPrefix + " " + apiKey;
|
||||
} else {
|
||||
value = apiKey;
|
||||
}
|
||||
if (location == "query") {
|
||||
queryParams.put(paramName, value);
|
||||
} else if (location == "header") {
|
||||
headerParams.put(paramName, value);
|
||||
}
|
||||
}
|
||||
public ApiKeyAuth(String location, String paramName) {
|
||||
this.location = location;
|
||||
this.paramName = paramName;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
public String getParamName() {
|
||||
return paramName;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getApiKeyPrefix() {
|
||||
return apiKeyPrefix;
|
||||
}
|
||||
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
this.apiKeyPrefix = apiKeyPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(Map
|
||||
<String, String> queryParams, Map
|
||||
<String, String> headerParams) {
|
||||
String value;
|
||||
if (apiKeyPrefix != null) {
|
||||
value = apiKeyPrefix + " " + apiKey;
|
||||
} else {
|
||||
value = apiKey;
|
||||
}
|
||||
if (location == "query") {
|
||||
queryParams.put(paramName, value);
|
||||
} else if (location == "header") {
|
||||
headerParams.put(paramName, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,6 +3,8 @@ package {{invokerPackage}}.auth;
|
||||
import java.util.Map;
|
||||
|
||||
public interface Authentication {
|
||||
/** Apply authentication settings to header and query params. */
|
||||
void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams);
|
||||
/** Apply authentication settings to header and query params. */
|
||||
void applyToParams(Map
|
||||
<String, String> queryParams, Map
|
||||
<String, String> headerParams);
|
||||
}
|
||||
|
@ -6,32 +6,34 @@ import java.io.UnsupportedEncodingException;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
public class HttpBasicAuth implements Authentication {
|
||||
private String username;
|
||||
private String password;
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
|
||||
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
|
||||
try {
|
||||
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(Map
|
||||
<String, String> queryParams, Map
|
||||
<String, String> headerParams) {
|
||||
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
|
||||
try {
|
||||
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,8 +3,10 @@ package {{invokerPackage}}.auth;
|
||||
import java.util.Map;
|
||||
|
||||
public class OAuth implements Authentication {
|
||||
@Override
|
||||
public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
|
||||
// TODO: support oauth
|
||||
}
|
||||
@Override
|
||||
public void applyToParams(Map
|
||||
<String, String> queryParams, Map
|
||||
<String, String> headerParams) {
|
||||
// TODO: support oauth
|
||||
}
|
||||
}
|
||||
|
@ -7,12 +7,12 @@ import io.swagger.annotations.*;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
{{#models}}
|
||||
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
* {{description}}
|
||||
**/{{/description}}
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{#vars}}{{#isEnum}}
|
||||
public enum {{datatypeWithEnum}} {
|
||||
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
|
||||
@ -46,6 +46,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{/vars}}sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
{{/model}}
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
@ -77,7 +77,8 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java</source>
|
||||
<source>
|
||||
src/main/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
@ -89,7 +90,8 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/test/java</source>
|
||||
<source>
|
||||
src/test/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
@ -100,7 +102,8 @@
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<source>
|
||||
1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
@ -1,9 +1,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class ApiException extends Exception{
|
||||
private int code;
|
||||
public ApiException (int code, String msg) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
private int code;
|
||||
public ApiException (int code, String msg) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
@ -6,21 +6,21 @@ import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class ApiOriginFilter implements javax.servlet.Filter {
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
}
|
@ -4,65 +4,65 @@ import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
@javax.xml.bind.annotation.XmlRootElement
|
||||
public class ApiResponseMessage {
|
||||
public static final int ERROR = 1;
|
||||
public static final int WARNING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int OK = 4;
|
||||
public static final int TOO_BUSY = 5;
|
||||
public static final int ERROR = 1;
|
||||
public static final int WARNING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int OK = 4;
|
||||
public static final int TOO_BUSY = 5;
|
||||
|
||||
int code;
|
||||
String type;
|
||||
String message;
|
||||
int code;
|
||||
String type;
|
||||
String message;
|
||||
|
||||
public ApiResponseMessage(){}
|
||||
public ApiResponseMessage(){}
|
||||
|
||||
public ApiResponseMessage(int code, String message){
|
||||
this.code = code;
|
||||
switch(code){
|
||||
case ERROR:
|
||||
setType("error");
|
||||
break;
|
||||
case WARNING:
|
||||
setType("warning");
|
||||
break;
|
||||
case INFO:
|
||||
setType("info");
|
||||
break;
|
||||
case OK:
|
||||
setType("ok");
|
||||
break;
|
||||
case TOO_BUSY:
|
||||
setType("too busy");
|
||||
break;
|
||||
default:
|
||||
setType("unknown");
|
||||
break;
|
||||
}
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@XmlTransient
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
public ApiResponseMessage(int code, String message){
|
||||
this.code = code;
|
||||
switch(code){
|
||||
case ERROR:
|
||||
setType("error");
|
||||
break;
|
||||
case WARNING:
|
||||
setType("warning");
|
||||
break;
|
||||
case INFO:
|
||||
setType("info");
|
||||
break;
|
||||
case OK:
|
||||
setType("ok");
|
||||
break;
|
||||
case TOO_BUSY:
|
||||
setType("too busy");
|
||||
break;
|
||||
default:
|
||||
setType("unknown");
|
||||
break;
|
||||
}
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@XmlTransient
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class NotFoundException extends ApiException {
|
||||
private int code;
|
||||
public NotFoundException (int code, String msg) {
|
||||
super(code, msg);
|
||||
this.code = code;
|
||||
}
|
||||
private int code;
|
||||
public NotFoundException (int code, String msg) {
|
||||
super(code, msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
@ -27,11 +27,11 @@ import javax.ws.rs.*;
|
||||
{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
|
||||
@io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
public class {{classname}} {
|
||||
|
||||
private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}();
|
||||
|
||||
{{#operation}}
|
||||
{{#operation}}
|
||||
@{{httpMethod}}
|
||||
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
|
||||
{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
|
||||
@ -46,7 +46,7 @@ public class {{classname}} {
|
||||
throws NotFoundException {
|
||||
return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}});
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
||||
|
||||
|
@ -19,10 +19,10 @@ import com.sun.jersey.multipart.FormDataParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
{{#operations}}
|
||||
public abstract class {{classname}}Service {
|
||||
public abstract class {{classname}}Service {
|
||||
{{#operation}}
|
||||
public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}})
|
||||
throws NotFoundException;
|
||||
{{/operation}}
|
||||
}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -5,10 +5,10 @@ import {{package}}.impl.{{classname}}ServiceImpl;
|
||||
|
||||
public class {{classname}}ServiceFactory {
|
||||
|
||||
private final static {{classname}}Service service = new {{classname}}ServiceImpl();
|
||||
private final static {{classname}}Service service = new {{classname}}ServiceImpl();
|
||||
|
||||
public static {{classname}}Service get{{classname}}()
|
||||
{
|
||||
return service;
|
||||
}
|
||||
public static {{classname}}Service get{{classname}}()
|
||||
{
|
||||
return service;
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ import com.sun.jersey.multipart.FormDataParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
{{#operations}}
|
||||
public class {{classname}}ServiceImpl extends {{classname}}Service {
|
||||
public class {{classname}}ServiceImpl extends {{classname}}Service {
|
||||
{{#operation}}
|
||||
@Override
|
||||
public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}})
|
||||
@ -28,5 +28,5 @@ public class {{classname}}ServiceImpl extends {{classname}}Service {
|
||||
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -1,2 +1,2 @@
|
||||
{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream,
|
||||
@ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}
|
||||
@ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}}
|
@ -7,12 +7,12 @@ import io.swagger.annotations.*;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
{{#models}}
|
||||
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
* {{description}}
|
||||
**/{{/description}}
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{#vars}}{{#isEnum}}
|
||||
public enum {{datatypeWithEnum}} {
|
||||
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
|
||||
@ -46,6 +46,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{/vars}}sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
{{/model}}
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
@ -1,4 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>{{groupId}}</groupId>
|
||||
<artifactId>{{artifactId}}</artifactId>
|
||||
@ -75,7 +76,8 @@
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/gen/java</source>
|
||||
<source>
|
||||
src/gen/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
|
||||
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>jersey</servlet-name>
|
||||
|
@ -31,7 +31,7 @@ import static org.springframework.http.MediaType.*;
|
||||
@RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE})
|
||||
@Api(value = "/{{baseName}}", description = "the {{baseName}} API")
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
public class {{classname}} {
|
||||
{{#operation}}
|
||||
|
||||
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}})
|
||||
@ -49,5 +49,5 @@ public class {{classname}} {
|
||||
}
|
||||
|
||||
{{/operation}}
|
||||
}
|
||||
}
|
||||
{{/operations}}
|
||||
|
@ -1,9 +1,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class ApiException extends Exception{
|
||||
private int code;
|
||||
public ApiException (int code, String msg) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
private int code;
|
||||
public ApiException (int code, String msg) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
@ -6,21 +6,21 @@ import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class ApiOriginFilter implements javax.servlet.Filter {
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse res = (HttpServletResponse) response;
|
||||
res.addHeader("Access-Control-Allow-Origin", "*");
|
||||
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
|
||||
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
}
|
@ -4,65 +4,65 @@ import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
@javax.xml.bind.annotation.XmlRootElement
|
||||
public class ApiResponseMessage {
|
||||
public static final int ERROR = 1;
|
||||
public static final int WARNING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int OK = 4;
|
||||
public static final int TOO_BUSY = 5;
|
||||
public static final int ERROR = 1;
|
||||
public static final int WARNING = 2;
|
||||
public static final int INFO = 3;
|
||||
public static final int OK = 4;
|
||||
public static final int TOO_BUSY = 5;
|
||||
|
||||
int code;
|
||||
String type;
|
||||
String message;
|
||||
int code;
|
||||
String type;
|
||||
String message;
|
||||
|
||||
public ApiResponseMessage(){}
|
||||
public ApiResponseMessage(){}
|
||||
|
||||
public ApiResponseMessage(int code, String message){
|
||||
this.code = code;
|
||||
switch(code){
|
||||
case ERROR:
|
||||
setType("error");
|
||||
break;
|
||||
case WARNING:
|
||||
setType("warning");
|
||||
break;
|
||||
case INFO:
|
||||
setType("info");
|
||||
break;
|
||||
case OK:
|
||||
setType("ok");
|
||||
break;
|
||||
case TOO_BUSY:
|
||||
setType("too busy");
|
||||
break;
|
||||
default:
|
||||
setType("unknown");
|
||||
break;
|
||||
}
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@XmlTransient
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
public ApiResponseMessage(int code, String message){
|
||||
this.code = code;
|
||||
switch(code){
|
||||
case ERROR:
|
||||
setType("error");
|
||||
break;
|
||||
case WARNING:
|
||||
setType("warning");
|
||||
break;
|
||||
case INFO:
|
||||
setType("info");
|
||||
break;
|
||||
case OK:
|
||||
setType("ok");
|
||||
break;
|
||||
case TOO_BUSY:
|
||||
setType("too busy");
|
||||
break;
|
||||
default:
|
||||
setType("unknown");
|
||||
break;
|
||||
}
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@XmlTransient
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
@ -1,2 +1,2 @@
|
||||
{{#isFormParam}}{{#notFile}}
|
||||
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}}
|
||||
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}}
|
@ -7,12 +7,12 @@ import io.swagger.annotations.*;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
{{#models}}
|
||||
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
* {{description}}
|
||||
**/{{/description}}
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{#vars}}{{#isEnum}}
|
||||
public enum {{datatypeWithEnum}} {
|
||||
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
|
||||
@ -46,6 +46,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
|
||||
{{/vars}}sb.append("}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
{{/model}}
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
@ -1,9 +1,9 @@
|
||||
package {{apiPackage}};
|
||||
|
||||
public class NotFoundException extends ApiException {
|
||||
private int code;
|
||||
public NotFoundException (int code, String msg) {
|
||||
super(code, msg);
|
||||
this.code = code;
|
||||
}
|
||||
private int code;
|
||||
public NotFoundException (int code, String msg) {
|
||||
super(code, msg);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>{{groupId}}</groupId>
|
||||
<artifactId>{{artifactId}}</artifactId>
|
||||
@ -31,7 +32,8 @@
|
||||
<version>${jetty-version}</version>
|
||||
<configuration>
|
||||
<webAppConfig>
|
||||
<contextPath>{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
|
||||
<contextPath>{{^contextPath}}
|
||||
/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}</contextPath>
|
||||
</webAppConfig>
|
||||
<webAppSourceDirectory>target/${project.artifactId}-${project-version}</webAppSourceDirectory>
|
||||
<webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
|
||||
@ -95,7 +97,8 @@
|
||||
<outputDirectory>target/${project.artifactId}-${project.version}</outputDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist</directory>
|
||||
<directory>${project.build.directory}/swagger-ui-${swagger-ui-version}/dist
|
||||
</directory>
|
||||
<filtering>true</filtering>
|
||||
<excludes>
|
||||
<exclude>index.html</exclude>
|
||||
|
@ -19,22 +19,22 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
@PropertySource("classpath:swagger.properties")
|
||||
@Import(SwaggerUiConfiguration.class)
|
||||
public class SwaggerConfig {
|
||||
@Bean
|
||||
ApiInfo apiInfo() {
|
||||
ApiInfo apiInfo = new ApiInfo(
|
||||
"{{appName}}",
|
||||
"{{{appDescription}}}",
|
||||
"{{appVersion}}",
|
||||
"{{infoUrl}}",
|
||||
"{{infoEmail}}",
|
||||
"{{licenseInfo}}",
|
||||
"{{licenseUrl}}" );
|
||||
return apiInfo;
|
||||
}
|
||||
@Bean
|
||||
ApiInfo apiInfo() {
|
||||
ApiInfo apiInfo = new ApiInfo(
|
||||
"{{appName}}",
|
||||
"{{{appDescription}}}",
|
||||
"{{appVersion}}",
|
||||
"{{infoUrl}}",
|
||||
"{{infoEmail}}",
|
||||
"{{licenseInfo}}",
|
||||
"{{licenseUrl}}" );
|
||||
return apiInfo;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Docket customImplementation(){
|
||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
|
||||
}
|
||||
@Bean
|
||||
public Docket customImplementation(){
|
||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
|
||||
}
|
||||
|
||||
}
|
@ -9,38 +9,38 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter {
|
||||
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
|
||||
private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };
|
||||
|
||||
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
|
||||
"classpath:/META-INF/resources/", "classpath:/resources/",
|
||||
"classpath:/static/", "classpath:/public/" };
|
||||
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
|
||||
"classpath:/META-INF/resources/", "classpath:/resources/",
|
||||
"classpath:/static/", "classpath:/public/" };
|
||||
|
||||
private static final String[] RESOURCE_LOCATIONS;
|
||||
static {
|
||||
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
|
||||
+ SERVLET_RESOURCE_LOCATIONS.length];
|
||||
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
|
||||
SERVLET_RESOURCE_LOCATIONS.length);
|
||||
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
|
||||
SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
|
||||
}
|
||||
private static final String[] RESOURCE_LOCATIONS;
|
||||
static {
|
||||
RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length
|
||||
+ SERVLET_RESOURCE_LOCATIONS.length];
|
||||
System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0,
|
||||
SERVLET_RESOURCE_LOCATIONS.length);
|
||||
System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS,
|
||||
SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);
|
||||
}
|
||||
|
||||
private static final String[] STATIC_INDEX_HTML_RESOURCES;
|
||||
static {
|
||||
STATIC_INDEX_HTML_RESOURCES = new String[RESOURCE_LOCATIONS.length];
|
||||
for (int i = 0; i < STATIC_INDEX_HTML_RESOURCES.length; i++) {
|
||||
STATIC_INDEX_HTML_RESOURCES[i] = RESOURCE_LOCATIONS[i] + "index.html";
|
||||
}
|
||||
}
|
||||
private static final String[] STATIC_INDEX_HTML_RESOURCES;
|
||||
static {
|
||||
STATIC_INDEX_HTML_RESOURCES = new String[RESOURCE_LOCATIONS.length];
|
||||
for (int i = 0; i < STATIC_INDEX_HTML_RESOURCES.length; i++) {
|
||||
STATIC_INDEX_HTML_RESOURCES[i] = RESOURCE_LOCATIONS[i] + "index.html";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
if (!registry.hasMappingForPattern("/webjars/**")) {
|
||||
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
if (!registry.hasMappingForPattern("/**")) {
|
||||
registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
if (!registry.hasMappingForPattern("/webjars/**")) {
|
||||
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
if (!registry.hasMappingForPattern("/**")) {
|
||||
registry.addResourceHandler("/**").addResourceLocations(RESOURCE_LOCATIONS);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,18 +4,18 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
|
||||
|
||||
public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { SwaggerConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class<?>[] { WebMvcConfiguration.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { SwaggerConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class<?>[] { WebMvcConfiguration.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
}
|
||||
|
@ -4,8 +4,8 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerCo
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
|
||||
|
||||
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
}
|
||||
|
@ -1,19 +1,19 @@
|
||||
package {{package}}
|
||||
|
||||
{{#imports}}
|
||||
import {{import}}
|
||||
import {{import}}
|
||||
{{/imports}}
|
||||
import {{invokerPackage}}._
|
||||
import {{invokerPackage}}.CollectionFormats._
|
||||
import {{invokerPackage}}.ApiKeyLocations._
|
||||
|
||||
{{#operations}}
|
||||
object {{classname}} {
|
||||
object {{classname}} {
|
||||
|
||||
{{#operation}}
|
||||
{{#javadocRenderer}}
|
||||
{{>javadoc}}
|
||||
{{/javadocRenderer}}
|
||||
{{#operation}}
|
||||
{{#javadocRenderer}}
|
||||
{{>javadoc}}
|
||||
{{/javadocRenderer}}
|
||||
def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] =
|
||||
ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}})
|
||||
{{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}})
|
||||
@ -32,12 +32,12 @@ object {{classname}} {
|
||||
def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}}
|
||||
}
|
||||
{{/responseHeaders.isEmpty}}
|
||||
{{/operation}}
|
||||
{{/operation}}
|
||||
|
||||
{{#unknownStatusCodes}}
|
||||
{{#unknownStatusCodes}}
|
||||
ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false)
|
||||
{{/unknownStatusCodes}}
|
||||
{{/unknownStatusCodes}}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
{{/operations}}
|
@ -33,291 +33,292 @@ import scala.util.control.NonFatal
|
||||
|
||||
object ApiInvoker {
|
||||
|
||||
def apply()(implicit system: ActorSystem): ApiInvoker =
|
||||
apply(DefaultFormats + DateTimeSerializer)
|
||||
def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
|
||||
apply(DefaultFormats + DateTimeSerializer ++ serializers)
|
||||
def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)
|
||||
def apply()(implicit system: ActorSystem): ApiInvoker =
|
||||
apply(DefaultFormats + DateTimeSerializer)
|
||||
def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
|
||||
apply(DefaultFormats + DateTimeSerializer ++ serializers)
|
||||
def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)
|
||||
|
||||
case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true)
|
||||
case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true)
|
||||
|
||||
def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess)
|
||||
def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess)
|
||||
|
||||
def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = {
|
||||
StatusCodes.getForKey(code) foreach { c =>
|
||||
StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true)
|
||||
}
|
||||
}
|
||||
def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = {
|
||||
StatusCodes.getForKey(code) foreach { c =>
|
||||
StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows request execution without calling apiInvoker.execute(request)
|
||||
* request.response can be used to get a future of the ApiResponse generated.
|
||||
* request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a
|
||||
* Future will failed with a ClassCastException
|
||||
* @param request the apiRequest to be executed
|
||||
*/
|
||||
implicit class ApiRequestImprovements[T](request: ApiRequest[T]) {
|
||||
/**
|
||||
* Allows request execution without calling apiInvoker.execute(request)
|
||||
* request.response can be used to get a future of the ApiResponse generated.
|
||||
* request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a
|
||||
* Future will failed with a ClassCastException
|
||||
* @param request the apiRequest to be executed
|
||||
*/
|
||||
implicit class ApiRequestImprovements[T](request: ApiRequest[T]) {
|
||||
|
||||
def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] =
|
||||
response(ec, system, invoker)
|
||||
def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] =
|
||||
response(ec, system, invoker)
|
||||
|
||||
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
|
||||
invoker.execute(request)
|
||||
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
|
||||
invoker.execute(request)
|
||||
|
||||
def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] =
|
||||
def result[U
|
||||
<: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U]=
|
||||
invoker.execute(request).map(_.content).mapTo[U]
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows transformation from ApiMethod to spray HttpMethods
|
||||
* @param method the ApiMethod to be converted
|
||||
*/
|
||||
implicit class ApiMethodExtensions(val method: ApiMethod) {
|
||||
def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
|
||||
}
|
||||
/**
|
||||
* Allows transformation from ApiMethod to spray HttpMethods
|
||||
* @param method the ApiMethod to be converted
|
||||
*/
|
||||
implicit class ApiMethodExtensions(val method: ApiMethod) {
|
||||
def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
|
||||
}
|
||||
|
||||
case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
|
||||
case JString(s) =>
|
||||
ISODateTimeFormat.dateTimeParser().parseDateTime(s)
|
||||
}, {
|
||||
case d: DateTime =>
|
||||
JString(ISODateTimeFormat.dateTimeParser().print(d))
|
||||
}))
|
||||
case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
|
||||
case JString(s) =>
|
||||
ISODateTimeFormat.dateTimeParser().parseDateTime(s)
|
||||
}, {
|
||||
case d: DateTime =>
|
||||
JString(ISODateTimeFormat.dateTimeParser().print(d))
|
||||
}))
|
||||
}
|
||||
|
||||
class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes {
|
||||
|
||||
import io.swagger.client.core.ApiInvoker._
|
||||
import io.swagger.client.core.ParametersMap._
|
||||
import io.swagger.client.core.ApiInvoker._
|
||||
import io.swagger.client.core.ParametersMap._
|
||||
|
||||
implicit val ec = system.dispatcher
|
||||
implicit val jsonFormats = formats
|
||||
implicit val ec = system.dispatcher
|
||||
implicit val jsonFormats = formats
|
||||
|
||||
def settings = ApiSettings(system)
|
||||
def settings = ApiSettings(system)
|
||||
|
||||
import spray.http.MessagePredicate._
|
||||
import spray.http.MessagePredicate._
|
||||
|
||||
val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) &&
|
||||
Encoder.DefaultFilter &&
|
||||
minEntitySize(settings.compressionSizeThreshold)
|
||||
val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) &&
|
||||
Encoder.DefaultFilter &&
|
||||
minEntitySize(settings.compressionSizeThreshold)
|
||||
|
||||
settings.customCodes.foreach(addCustomStatusCode)
|
||||
settings.customCodes.foreach(addCustomStatusCode)
|
||||
|
||||
private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer =
|
||||
request =>
|
||||
credentialsSeq.foldLeft(request) {
|
||||
case (req, BasicCredentials(login, password)) =>
|
||||
req ~> addCredentials(BasicHttpCredentials(login, password))
|
||||
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
|
||||
req ~> addHeader(RawHeader(keyName, keyValue.value))
|
||||
case (req, _) => req
|
||||
}
|
||||
private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer =
|
||||
request =>
|
||||
credentialsSeq.foldLeft(request) {
|
||||
case (req, BasicCredentials(login, password)) =>
|
||||
req ~> addCredentials(BasicHttpCredentials(login, password))
|
||||
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
|
||||
req ~> addHeader(RawHeader(keyName, keyValue.value))
|
||||
case (req, _) => req
|
||||
}
|
||||
|
||||
private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request =>
|
||||
private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request =>
|
||||
|
||||
val rawHeaders = for {
|
||||
(name, value) <- headers.asFormattedParams
|
||||
header = RawHeader(name, String.valueOf(value))
|
||||
} yield header
|
||||
val rawHeaders = for {
|
||||
(name, value) <- headers.asFormattedParams
|
||||
header = RawHeader(name, String.valueOf(value))
|
||||
} yield header
|
||||
|
||||
request.withHeaders(rawHeaders.toList)
|
||||
}
|
||||
request.withHeaders(rawHeaders.toList)
|
||||
}
|
||||
|
||||
private def bodyPart(name: String, value: Any): BodyPart = {
|
||||
value match {
|
||||
case f: File =>
|
||||
BodyPart(f, name)
|
||||
case v: String =>
|
||||
BodyPart(HttpEntity(String.valueOf(v)))
|
||||
case NumericValue(v) =>
|
||||
BodyPart(HttpEntity(String.valueOf(v)))
|
||||
case m: ApiModel =>
|
||||
BodyPart(HttpEntity(Serialization.write(m)))
|
||||
}
|
||||
}
|
||||
private def bodyPart(name: String, value: Any): BodyPart = {
|
||||
value match {
|
||||
case f: File =>
|
||||
BodyPart(f, name)
|
||||
case v: String =>
|
||||
BodyPart(HttpEntity(String.valueOf(v)))
|
||||
case NumericValue(v) =>
|
||||
BodyPart(HttpEntity(String.valueOf(v)))
|
||||
case m: ApiModel =>
|
||||
BodyPart(HttpEntity(Serialization.write(m)))
|
||||
}
|
||||
}
|
||||
|
||||
private def formDataContent(request: ApiRequest[_]) = {
|
||||
val params = request.formParams.asFormattedParams
|
||||
if (params.isEmpty)
|
||||
None
|
||||
else
|
||||
Some(
|
||||
normalizedContentType(request.contentType).mediaType match {
|
||||
case MediaTypes.`multipart/form-data` =>
|
||||
MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))})
|
||||
case MediaTypes.`application/x-www-form-urlencoded` =>
|
||||
FormData(params.mapValues(String.valueOf))
|
||||
case m: MediaType => // Default : application/x-www-form-urlencoded.
|
||||
FormData(params.mapValues(String.valueOf))
|
||||
}
|
||||
)
|
||||
}
|
||||
private def formDataContent(request: ApiRequest[_]) = {
|
||||
val params = request.formParams.asFormattedParams
|
||||
if (params.isEmpty)
|
||||
None
|
||||
else
|
||||
Some(
|
||||
normalizedContentType(request.contentType).mediaType match {
|
||||
case MediaTypes.`multipart/form-data` =>
|
||||
MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))})
|
||||
case MediaTypes.`application/x-www-form-urlencoded` =>
|
||||
FormData(params.mapValues(String.valueOf))
|
||||
case m: MediaType => // Default : application/x-www-form-urlencoded.
|
||||
FormData(params.mapValues(String.valueOf))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private def bodyContent(request: ApiRequest[_]): Option[Any] = {
|
||||
request.bodyParam.map(Extraction.decompose).map(compact)
|
||||
}
|
||||
private def bodyContent(request: ApiRequest[_]): Option[Any] = {
|
||||
request.bodyParam.map(Extraction.decompose).map(compact)
|
||||
}
|
||||
|
||||
private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = {
|
||||
private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = {
|
||||
|
||||
val builder = new RequestBuilder(request.method.toSprayMethod)
|
||||
val httpRequest = request.method.toSprayMethod match {
|
||||
case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri)
|
||||
case HttpMethods.POST | HttpMethods.PUT =>
|
||||
formDataContent(request) orElse bodyContent(request) match {
|
||||
case Some(c: FormData) =>
|
||||
builder.apply(uri, c)
|
||||
case Some(c: MultipartFormData) =>
|
||||
builder.apply(uri, c)
|
||||
case Some(c: String) =>
|
||||
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c))
|
||||
case _ =>
|
||||
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " "))
|
||||
}
|
||||
case _ => builder.apply(uri)
|
||||
}
|
||||
val builder = new RequestBuilder(request.method.toSprayMethod)
|
||||
val httpRequest = request.method.toSprayMethod match {
|
||||
case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri)
|
||||
case HttpMethods.POST | HttpMethods.PUT =>
|
||||
formDataContent(request) orElse bodyContent(request) match {
|
||||
case Some(c: FormData) =>
|
||||
builder.apply(uri, c)
|
||||
case Some(c: MultipartFormData) =>
|
||||
builder.apply(uri, c)
|
||||
case Some(c: String) =>
|
||||
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c))
|
||||
case _ =>
|
||||
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " "))
|
||||
}
|
||||
case _ => builder.apply(uri)
|
||||
}
|
||||
|
||||
httpRequest ~>
|
||||
addHeaders(request.headerParams) ~>
|
||||
addAuthentication(request.credentials) ~>
|
||||
encode(Gzip(CompressionFilter))
|
||||
}
|
||||
httpRequest ~>
|
||||
addHeaders(request.headerParams) ~>
|
||||
addAuthentication(request.credentials) ~>
|
||||
encode(Gzip(CompressionFilter))
|
||||
}
|
||||
|
||||
def makeQuery(r: ApiRequest[_]): Query = {
|
||||
r.credentials.foldLeft(r.queryParams) {
|
||||
case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) =>
|
||||
params + (keyName -> key.value)
|
||||
case (params, _) => params
|
||||
}.asFormattedParams
|
||||
.mapValues(String.valueOf)
|
||||
.foldRight[Query](Uri.Query.Empty) {
|
||||
case ((name, value), acc) => acc.+:(name, value)
|
||||
}
|
||||
}
|
||||
def makeQuery(r: ApiRequest[_]): Query = {
|
||||
r.credentials.foldLeft(r.queryParams) {
|
||||
case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) =>
|
||||
params + (keyName -> key.value)
|
||||
case (params, _) => params
|
||||
}.asFormattedParams
|
||||
.mapValues(String.valueOf)
|
||||
.foldRight[Query](Uri.Query.Empty) {
|
||||
case ((name, value), acc) => acc.+:(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
def makeUri(r: ApiRequest[_]): Uri = {
|
||||
val opPath = r.operationPath.replaceAll("\\{format\\}", "json")
|
||||
val opPathWithParams = r.pathParams.asFormattedParams
|
||||
.mapValues(String.valueOf)
|
||||
.foldLeft(opPath) {
|
||||
case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value)
|
||||
}
|
||||
val query = makeQuery(r)
|
||||
def makeUri(r: ApiRequest[_]): Uri = {
|
||||
val opPath = r.operationPath.replaceAll("\\{format\\}", "json")
|
||||
val opPathWithParams = r.pathParams.asFormattedParams
|
||||
.mapValues(String.valueOf)
|
||||
.foldLeft(opPath) {
|
||||
case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value)
|
||||
}
|
||||
val query = makeQuery(r)
|
||||
|
||||
Uri(r.basePath + opPathWithParams).withQuery(query)
|
||||
}
|
||||
Uri(r.basePath + opPathWithParams).withQuery(query)
|
||||
}
|
||||
|
||||
def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = {
|
||||
try {
|
||||
implicit val timeout: Timeout = settings.connectionTimeout
|
||||
def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = {
|
||||
try {
|
||||
implicit val timeout: Timeout = settings.connectionTimeout
|
||||
|
||||
val uri = makeUri(r)
|
||||
val uri = makeUri(r)
|
||||
|
||||
val connector = HostConnectorSetup(
|
||||
uri.authority.host.toString,
|
||||
uri.effectivePort,
|
||||
sslEncryption = "https".equals(uri.scheme),
|
||||
defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate)))
|
||||
val connector = HostConnectorSetup(
|
||||
uri.authority.host.toString,
|
||||
uri.effectivePort,
|
||||
sslEncryption = "https".equals(uri.scheme),
|
||||
defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate)))
|
||||
|
||||
val request = createRequest(uri, r)
|
||||
val request = createRequest(uri, r)
|
||||
|
||||
for {
|
||||
Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector
|
||||
response <- hostConnector.ask(request).mapTo[HttpResponse]
|
||||
} yield {
|
||||
response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
case NonFatal(x) => Future.failed(x)
|
||||
}
|
||||
}
|
||||
for {
|
||||
Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector
|
||||
response <- hostConnector.ask(request).mapTo[HttpResponse]
|
||||
} yield {
|
||||
response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
case NonFatal(x) => Future.failed(x)
|
||||
}
|
||||
}
|
||||
|
||||
def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = {
|
||||
request.responseForCode(response.status.intValue) match {
|
||||
case Some( (manifest: Manifest[T], state: ResponseState) ) =>
|
||||
entityUnmarshaller(manifest)(response.entity) match {
|
||||
case Right(value) ⇒
|
||||
state match {
|
||||
case ResponseState.Success =>
|
||||
ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap)
|
||||
case ResponseState.Error =>
|
||||
throw new ApiError(response.status.intValue, "Error response received",
|
||||
Some(value),
|
||||
headers = response.headers.map(header => (header.name, header.value)).toMap)
|
||||
}
|
||||
def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = {
|
||||
request.responseForCode(response.status.intValue) match {
|
||||
case Some( (manifest: Manifest[T], state: ResponseState) ) =>
|
||||
entityUnmarshaller(manifest)(response.entity) match {
|
||||
case Right(value) ⇒
|
||||
state match {
|
||||
case ResponseState.Success =>
|
||||
ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap)
|
||||
case ResponseState.Error =>
|
||||
throw new ApiError(response.status.intValue, "Error response received",
|
||||
Some(value),
|
||||
headers = response.headers.map(header => (header.name, header.value)).toMap)
|
||||
}
|
||||
|
||||
case Left(MalformedContent(error, Some(cause))) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause)
|
||||
case Left(MalformedContent(error, Some(cause))) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause)
|
||||
|
||||
case Left(MalformedContent(error, None)) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString))
|
||||
case Left(MalformedContent(error, None)) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString))
|
||||
|
||||
case Left(ContentExpected) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString))
|
||||
}
|
||||
case Left(ContentExpected) ⇒
|
||||
throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString))
|
||||
}
|
||||
|
||||
case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))
|
||||
}
|
||||
}
|
||||
case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))
|
||||
}
|
||||
}
|
||||
|
||||
def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] =
|
||||
Unmarshaller[T](MediaTypes.`application/json`) {
|
||||
case x: HttpEntity.NonEmpty ⇒
|
||||
parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`))
|
||||
.noNulls
|
||||
.camelizeKeys
|
||||
.extract[T]
|
||||
}
|
||||
def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] =
|
||||
Unmarshaller[T](MediaTypes.`application/json`) {
|
||||
case x: HttpEntity.NonEmpty ⇒
|
||||
parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`))
|
||||
.noNulls
|
||||
.camelizeKeys
|
||||
.extract[T]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
sealed trait CustomContentTypes {
|
||||
|
||||
def normalizedContentType(original: String): ContentType =
|
||||
MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original)
|
||||
def normalizedContentType(original: String): ContentType =
|
||||
MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original)
|
||||
|
||||
def parseContentType(contentType: String): ContentType = {
|
||||
val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType)
|
||||
val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader)
|
||||
(parsedContentTypeHeader: @unchecked) match {
|
||||
case Right(ct: HttpHeaders.`Content-Type`) =>
|
||||
ct.contentType
|
||||
case Left(error: ErrorInfo) =>
|
||||
throw new IllegalArgumentException(
|
||||
s"Error converting '$contentType' to a ContentType header: '${error.summary}'")
|
||||
}
|
||||
}
|
||||
def parseContentType(contentType: String): ContentType = {
|
||||
val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType)
|
||||
val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader)
|
||||
(parsedContentTypeHeader: @unchecked) match {
|
||||
case Right(ct: HttpHeaders.`Content-Type`) =>
|
||||
ct.contentType
|
||||
case Left(error: ErrorInfo) =>
|
||||
throw new IllegalArgumentException(
|
||||
s"Error converting '$contentType' to a ContentType header: '${error.summary}'")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed trait UntrustedSslContext {
|
||||
this: ApiInvoker =>
|
||||
this: ApiInvoker =>
|
||||
|
||||
implicit lazy val trustfulSslContext: SSLContext = {
|
||||
settings.alwaysTrustCertificates match {
|
||||
case false =>
|
||||
SSLContext.getDefault
|
||||
implicit lazy val trustfulSslContext: SSLContext = {
|
||||
settings.alwaysTrustCertificates match {
|
||||
case false =>
|
||||
SSLContext.getDefault
|
||||
|
||||
case true =>
|
||||
class IgnoreX509TrustManager extends X509TrustManager {
|
||||
def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
|
||||
case true =>
|
||||
class IgnoreX509TrustManager extends X509TrustManager {
|
||||
def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
|
||||
|
||||
def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
|
||||
def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
|
||||
|
||||
def getAcceptedIssuers = null
|
||||
}
|
||||
|
||||
val context = SSLContext.getInstance("TLS")
|
||||
context.init(null, Array(new IgnoreX509TrustManager), null)
|
||||
context
|
||||
}
|
||||
}
|
||||
|
||||
implicit val clientSSLEngineProvider =
|
||||
ClientSSLEngineProvider {
|
||||
_ =>
|
||||
val engine = trustfulSslContext.createSSLEngine()
|
||||
engine.setUseClientMode(true)
|
||||
engine
|
||||
}
|
||||
def getAcceptedIssuers = null
|
||||
}
|
||||
|
||||
val context = SSLContext.getInstance("TLS")
|
||||
context.init(null, Array(new IgnoreX509TrustManager), null)
|
||||
context
|
||||
}
|
||||
}
|
||||
|
||||
implicit val clientSSLEngineProvider =
|
||||
ClientSSLEngineProvider {
|
||||
_ =>
|
||||
val engine = trustfulSslContext.createSSLEngine()
|
||||
engine.setUseClientMode(true)
|
||||
engine
|
||||
}
|
||||
}
|
||||
|
@ -2,49 +2,49 @@ package {{invokerPackage}}
|
||||
|
||||
sealed trait ResponseState
|
||||
object ResponseState {
|
||||
case object Success extends ResponseState
|
||||
case object Error extends ResponseState
|
||||
case object Success extends ResponseState
|
||||
case object Error extends ResponseState
|
||||
}
|
||||
|
||||
case class ApiRequest[U](
|
||||
// required fields
|
||||
method: ApiMethod,
|
||||
basePath: String,
|
||||
operationPath: String,
|
||||
contentType: String,
|
||||
// required fields
|
||||
method: ApiMethod,
|
||||
basePath: String,
|
||||
operationPath: String,
|
||||
contentType: String,
|
||||
|
||||
// optional fields
|
||||
responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty,
|
||||
bodyParam: Option[Any] = None,
|
||||
formParams: Map[String, Any] = Map.empty,
|
||||
pathParams: Map[String, Any] = Map.empty,
|
||||
queryParams: Map[String, Any] = Map.empty,
|
||||
headerParams: Map[String, Any] = Map.empty,
|
||||
credentials: Seq[Credentials] = List.empty) {
|
||||
// optional fields
|
||||
responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty,
|
||||
bodyParam: Option[Any] = None,
|
||||
formParams: Map[String, Any] = Map.empty,
|
||||
pathParams: Map[String, Any] = Map.empty,
|
||||
queryParams: Map[String, Any] = Map.empty,
|
||||
headerParams: Map[String, Any] = Map.empty,
|
||||
credentials: Seq[Credentials] = List.empty) {
|
||||
|
||||
def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred)
|
||||
def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred)
|
||||
|
||||
def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location))
|
||||
def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location))
|
||||
|
||||
def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success)))
|
||||
def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success)))
|
||||
|
||||
def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error)))
|
||||
def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error)))
|
||||
|
||||
def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0)
|
||||
def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0)
|
||||
|
||||
def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0)
|
||||
def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0)
|
||||
|
||||
def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0)
|
||||
def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0)
|
||||
|
||||
def withoutBody() = copy[U](bodyParam = None)
|
||||
def withoutBody() = copy[U](bodyParam = None)
|
||||
|
||||
def withBody(body: Any) = copy[U](bodyParam = Some(body))
|
||||
def withBody(body: Any) = copy[U](bodyParam = Some(body))
|
||||
|
||||
def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value))
|
||||
def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value))
|
||||
|
||||
def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value))
|
||||
def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value))
|
||||
|
||||
def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value))
|
||||
def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value))
|
||||
|
||||
def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value))
|
||||
def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value))
|
||||
}
|
||||
|
@ -11,20 +11,20 @@ import scala.collection.JavaConversions._
|
||||
import scala.concurrent.duration.FiniteDuration
|
||||
|
||||
class ApiSettings(config: Config) extends Extension {
|
||||
def this(system: ExtendedActorSystem) = this(system.settings.config)
|
||||
def this(system: ExtendedActorSystem) = this(system.settings.config)
|
||||
|
||||
private def cfg = config.getConfig("io.swagger.client.apiRequest")
|
||||
private def cfg = config.getConfig("io.swagger.client.apiRequest")
|
||||
|
||||
val alwaysTrustCertificates = cfg.getBoolean("trust-certificates")
|
||||
val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render))
|
||||
val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
|
||||
val compressionEnabled = cfg.getBoolean("compression.enabled")
|
||||
val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt
|
||||
val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode(
|
||||
c.getInt("code"),
|
||||
c.getString("reason"),
|
||||
c.getBoolean("success"))
|
||||
}
|
||||
val alwaysTrustCertificates = cfg.getBoolean("trust-certificates")
|
||||
val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render))
|
||||
val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
|
||||
val compressionEnabled = cfg.getBoolean("compression.enabled")
|
||||
val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt
|
||||
val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode(
|
||||
c.getInt("code"),
|
||||
c.getString("reason"),
|
||||
c.getBoolean("success"))
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -6,20 +6,21 @@ import scala.reflect.ClassTag
|
||||
|
||||
object EnumsSerializers {
|
||||
|
||||
def all = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+
|
||||
new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}}
|
||||
def all = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+
|
||||
new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}}
|
||||
|
||||
|
||||
|
||||
private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E)
|
||||
private class EnumNameSerializer[E
|
||||
<: Enumeration: ClassTag](enum: E)
|
||||
extends Serializer[E#Value] {
|
||||
import JsonDSL._
|
||||
|
||||
val EnumerationClass = classOf[E#Value]
|
||||
val EnumerationClass=classOf[E#Value]
|
||||
|
||||
def deserialize(implicit format: Formats):
|
||||
PartialFunction[(TypeInfo, JValue), E#Value] = {
|
||||
case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => {
|
||||
PartialFunction[(TypeInfo, JValue), E#Value]={
|
||||
case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json)=> {
|
||||
json match {
|
||||
case JString(value) =>
|
||||
enum.withName(value)
|
||||
@ -39,4 +40,4 @@ object EnumsSerializers {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
{{^notes.isEmpty}}
|
||||
{{notes}}
|
||||
{{notes}}
|
||||
{{/notes.isEmpty}}
|
||||
|
||||
Expected answers:
|
||||
@ -10,12 +10,12 @@ Expected answers:
|
||||
{{/responses}}
|
||||
{{#authMethods.0}}
|
||||
|
||||
Available security schemes:
|
||||
{{#authMethods}}
|
||||
Available security schemes:
|
||||
{{#authMethods}}
|
||||
{{name}} ({{type}})
|
||||
{{/authMethods}}
|
||||
{{/authMethods}}
|
||||
{{/authMethods.0}}
|
||||
|
||||
{{#allParams}}
|
||||
@param {{paramName}} {{description}}
|
||||
@param {{paramName}} {{description}}
|
||||
{{/allParams}}
|
||||
|
@ -4,27 +4,27 @@ import {{invokerPackage}}.ApiModel
|
||||
import org.joda.time.DateTime
|
||||
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
{{#model}}
|
||||
|
||||
case class {{classname}} (
|
||||
case class {{classname}} (
|
||||
{{#vars}}{{#description}}/* {{{description}}} */
|
||||
{{/description}}{{name}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}}
|
||||
{{/vars}} extends ApiModel
|
||||
|
||||
{{#hasEnums}}
|
||||
object {{classname}}Enums {
|
||||
{{#hasEnums}}
|
||||
object {{classname}}Enums {
|
||||
|
||||
{{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value
|
||||
{{/isEnum}}{{/vars}}
|
||||
{{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration {
|
||||
{{#_enum}}
|
||||
{{#_enum}}
|
||||
val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}")
|
||||
{{/_enum}}
|
||||
{{/_enum}}
|
||||
}
|
||||
|
||||
{{/isEnum}}{{/vars}}
|
||||
}
|
||||
{{/hasEnums}}
|
||||
{{/model}}
|
||||
}
|
||||
{{/hasEnums}}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
||||
|
@ -1,24 +1,24 @@
|
||||
{{configKeyPath}} {
|
||||
|
||||
{{configKey}} {
|
||||
{{configKey}} {
|
||||
|
||||
compression {
|
||||
enabled: false
|
||||
size-threshold: 0
|
||||
}
|
||||
compression {
|
||||
enabled: false
|
||||
size-threshold: 0
|
||||
}
|
||||
|
||||
trust-certificates: true
|
||||
trust-certificates: true
|
||||
|
||||
connection-timeout: {{defaultTimeout}}ms
|
||||
connection-timeout: {{defaultTimeout}}ms
|
||||
|
||||
default-headers {
|
||||
"userAgent": "{{artifactId}}_{{artifactVersion}}"
|
||||
}
|
||||
default-headers {
|
||||
"userAgent": "{{artifactId}}_{{artifactVersion}}"
|
||||
}
|
||||
|
||||
// let you define custom http status code, as in :
|
||||
// { code: 601, reason: "some custom http status code", success: false }
|
||||
custom-codes : []
|
||||
}
|
||||
// let you define custom http status code, as in :
|
||||
// { code: 601, reason: "some custom http status code", success: false }
|
||||
custom-codes : []
|
||||
}
|
||||
}
|
||||
|
||||
spray.can.host-connector.max-redirects = 10
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user