diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 8f57c21653f..ec0d6875358 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -1,4 +1,4 @@ - io.swagger @@ -16,12 +16,12 @@ swagger-codegen-cli - - src/main/resources - - logback.xml - - + + src/main/resources + + logback.xml + + @@ -62,7 +62,8 @@ - + diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java index 62f0b5cb7e2..fe6d370f3b8 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -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 - * + *

* Command line interface for swagger codegen * use `swagger-codegen-cli.jar help` for more info * diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java index 54fbfac6e7a..6b34a4bf56d 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -1,33 +1,24 @@ 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") public class ConfigHelp implements Runnable { - + @Option(name = {"-l", "--lang"}, title = "language", required = true, 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(); + } + } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 497cba64511..0d7e94e8f28 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -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 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); @@ -84,13 +106,13 @@ public class Generate implements Runnable { if (null != templateDir) { 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()) { if (genConfig.hasOption(langCliOption.getOpt())) { - config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); } } } @@ -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 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); - } - } } diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java index 5627b6c7ac8..c3d7391579e 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java @@ -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; diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java index 4a875b7199e..c75181c51cd 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -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,8 +81,9 @@ 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 + * @param data - map with additional params needed to process templates * @return converter object to pass to lambdaj */ private Converter processFiles(final File targetDir, final Map data) { @@ -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 */ diff --git a/modules/swagger-codegen-cli/src/main/resources/logback.xml b/modules/swagger-codegen-cli/src/main/resources/logback.xml index 273b46980db..3bd0c92d369 100644 --- a/modules/swagger-codegen-cli/src/main/resources/logback.xml +++ b/modules/swagger-codegen-cli/src/main/resources/logback.xml @@ -1,12 +1,12 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 5debeeb2570..1b6712ba32f 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -1,356 +1,357 @@ - - - io.swagger - swagger-codegen-project - 2.1.1 - ../.. - - 4.0.0 - swagger-codegen - jar - swagger-codegen (core library) - - src/main/java - install - - - src/main/resources - - logback.xml - - - - - - org.jvnet.wagon-svn - wagon-svn - 1.8 - - - org.apache.maven.wagon - wagon-ssh-external - 1.0-alpha-6 - - - org.apache.maven.wagon - wagon-webdav - 1.0-beta-1 - - - target - ${project.artifactId}-${project.version} - - - org.codehaus.mojo - exec-maven-plugin - 1.3.2 - - - - java - - - - - io.swagger.codegen.Codegen - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - net.alchim31.maven - scala-maven-plugin - - - - add-source - compile - testCompile - - - - - - incremental - - - -Xmx384m - - - -target:jvm-1.6 - -deprecation - - - - run-scalatest - org.scalatest.tools.Runner - - -p - ${project.build.testOutputDirectory} - - - -Xmx512m - - - - - - - maven-compiler-plugin - 3.0 - - 1.6 - 1.6 - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - development - ${project.url} - ${project.version} - io.swagger - - - - - - org.apache.maven.plugins - maven-site-plugin - 2.1 - - - org.apache.maven.plugins - maven-release-plugin - 2.1 - - - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - org.apache.maven.plugins - maven-gpg-plugin - - release - sign - - - - - - - - release-profile - - true - - + + + io.swagger + swagger-codegen-project + 2.1.1 + ../.. + + 4.0.0 + swagger-codegen + jar + swagger-codegen (core library) + + src/main/java + install + + + src/main/resources + + logback.xml + + + + + + org.jvnet.wagon-svn + wagon-svn + 1.8 + + + org.apache.maven.wagon + wagon-ssh-external + 1.0-alpha-6 + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-1 + + + target + ${project.artifactId}-${project.version} - - net.alchim31.maven - scala-maven-plugin - - - - compile - testCompile - - - - - ${scala-version} - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source - prepare-package - - add-source - + + org.codehaus.mojo + exec-maven-plugin + 1.3.2 + + + + java + + + - - src/main/scala - + io.swagger.codegen.Codegen - - - + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + net.alchim31.maven + scala-maven-plugin + + + + add-source + compile + testCompile + + + + + + incremental + + + -Xmx384m + + + -target:jvm-1.6 + -deprecation + + + + run-scalatest + org.scalatest.tools.Runner + + -p + ${project.build.testOutputDirectory} + + + -Xmx512m + + + + + + + maven-compiler-plugin + 3.0 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + development + ${project.url} + ${project.version} + io.swagger + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.1 + - - - - release-sign-artifacts - - - performRelease - true - - - + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-gpg-plugin + + release + sign + + + + + + + + release-profile + + true + + + + + net.alchim31.maven + scala-maven-plugin + + + + compile + testCompile + + + + + ${scala-version} + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + prepare-package + + add-source + + + + src/main/scala + + + + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + + + target/site - - org.apache.maven.plugins - maven-gpg-plugin - - - sign-artifacts - verify - - sign - - - - + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + true + true + + http://java.sun.com/javaee/5/docs/api + http://java.sun.com/j2se/1.5.0/docs/api + + + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + true + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + project-team + + + + - - - - - target/site - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - true - true - - http://java.sun.com/javaee/5/docs/api - http://java.sun.com/j2se/1.5.0/docs/api - - - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - true - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - project-team - - - - - - - - - io.swagger - swagger-parser - ${swagger-parser-version} - compile - - - io.swagger - swagger-compat-spec-parser - ${swagger-parser-version} - - - ${project.groupId} - swagger-core - ${swagger-core-version} - - - com.samskivert - jmustache - ${jmustache-version} - - - commons-io - commons-io - ${commons-io-version} - - - org.apache.maven - maven-plugin-tools-api - 2.0 - - - org.apache.felix - maven-bundle-plugin - ${felix-version} - - - org.slf4j - slf4j-ext - ${slf4j-version} - - - org.slf4j - slf4j-api - ${slf4j-version} - - - commons-lang - commons-lang - ${commons-lang-version} - - - commons-cli - commons-cli - ${commons-cli-version} - - - org.scalatest - scalatest_2.11 - ${scala-test-version} - test - - - org.scala-lang - scala-library - ${scala-version} - test - - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - true - - - + + + + io.swagger + swagger-parser + ${swagger-parser-version} + compile + + + io.swagger + swagger-compat-spec-parser + ${swagger-parser-version} + + + ${project.groupId} + swagger-core + ${swagger-core-version} + + + com.samskivert + jmustache + ${jmustache-version} + + + commons-io + commons-io + ${commons-io-version} + + + org.apache.maven + maven-plugin-tools-api + 2.0 + + + org.apache.felix + maven-bundle-plugin + ${felix-version} + + + org.slf4j + slf4j-ext + ${slf4j-version} + + + org.slf4j + slf4j-api + ${slf4j-version} + + + commons-lang + commons-lang + ${commons-lang-version} + + + commons-cli + commons-cli + ${commons-cli-version} + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + org.scala-lang + scala-library + ${scala-version} + test + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + diff --git a/modules/swagger-codegen/src/main/java/config/Config.java b/modules/swagger-codegen/src/main/java/config/Config.java index 9bc4bf58624..8b8f1b36a96 100644 --- a/modules/swagger-codegen/src/main/java/config/Config.java +++ b/modules/swagger-codegen/src/main/java/config/Config.java @@ -1,33 +1,34 @@ package config; import com.google.common.collect.ImmutableMap; + import java.util.HashMap; import java.util.Map; public class Config { - private Map options; + private Map options; - public Config() { - this.options = new HashMap(); - } + public Config() { + this.options = new HashMap(); + } - public Config(Map properties) { - this.options = properties; - } + public Config(Map properties) { + this.options = properties; + } - public Map getOptions() { - return ImmutableMap.copyOf(options); - } - - public boolean hasOption(String opt){ - return options.containsKey(opt); - } - - public String getOption(String opt){ - return options.get(opt); - } - - public void setOption(String opt, String value){ - options.put(opt, value); - } + public Map getOptions() { + return ImmutableMap.copyOf(options); + } + + public boolean hasOption(String opt) { + return options.containsKey(opt); + } + + public String getOption(String opt) { + return options.get(opt); + } + + public void setOption(String opt, String value) { + options.put(opt, value); + } } diff --git a/modules/swagger-codegen/src/main/java/config/ConfigParser.java b/modules/swagger-codegen/src/main/java/config/ConfigParser.java index cbb1b78f645..101fbb0d256 100644 --- a/modules/swagger-codegen/src/main/java/config/ConfigParser.java +++ b/modules/swagger-codegen/src/main/java/config/ConfigParser.java @@ -2,40 +2,39 @@ 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; public class ConfigParser { - public static Config read(String location) { + public static Config read(String location) { - System.out.println("reading config from " + location); + System.out.println("reading config from " + location); - ObjectMapper mapper = new ObjectMapper(); - - Config config = new Config(); - - try { - JsonNode rootNode = mapper.readTree(new File(location)); - Iterator> optionNodes = rootNode.fields(); - - while (optionNodes.hasNext()) { - Map.Entry optionNode = (Map.Entry) optionNodes.next(); - - if(optionNode.getValue().isValueNode()){ - config.setOption(optionNode.getKey(), optionNode.getValue().asText()); + ObjectMapper mapper = new ObjectMapper(); + + Config config = new Config(); + + try { + JsonNode rootNode = mapper.readTree(new File(location)); + Iterator> optionNodes = rootNode.fields(); + + while (optionNodes.hasNext()) { + Map.Entry optionNode = (Map.Entry) optionNodes.next(); + + if (optionNode.getValue().isValueNode()) { + config.setOption(optionNode.getKey(), optionNode.getValue().asText()); + } else { + System.out.println("omitting non-value node " + optionNode.getKey()); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + return null; } - else{ - System.out.println("omitting non-value node " + optionNode.getKey()); - } - } + + return config; } - catch (Exception e) { - System.out.println(e.getMessage()); - return null; - } - - return config; - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 3fc7dfb8da2..54a2f7efae0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -1,60 +1,69 @@ 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 { - public File writeToFile(String filename, String contents) throws IOException { - System.out.println("writing file " + filename); - File output = new File(filename); + public File writeToFile(String filename, String contents) throws IOException { + System.out.println("writing file " + filename); + File output = new File(filename); - if(output.getParent() != null && !new File(output.getParent()).exists()) { - File parent = new File(output.getParent()); - parent.mkdirs(); - } - Writer out = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(output), "UTF-8")); + if (output.getParent() != null && !new File(output.getParent()).exists()) { + File parent = new File(output.getParent()); + parent.mkdirs(); + } + Writer out = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(output), "UTF-8")); - out.write(contents); - out.close(); - return output; - } + out.write(contents); + out.close(); + return output; + } - public String readTemplate(String name) { - try{ - Reader reader = getTemplateReader(name); - 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() : ""; + public String readTemplate(String name) { + try { + Reader reader = getTemplateReader(name); + 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) { + e.printStackTrace(); + } + throw new RuntimeException("can't load template " + name); } - catch(Exception e) { - e.printStackTrace(); - } - throw new RuntimeException("can't load template " + name); - } - public Reader getTemplateReader(String name) { - try{ - InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); - if(is == null) - is = new FileInputStream(new File(name)); - if(is == null) - throw new RuntimeException("no file found"); - return new InputStreamReader(is); + public Reader getTemplateReader(String name) { + try { + InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); + 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) { + e.printStackTrace(); + } + throw new RuntimeException("can't load template " + name); } - catch(Exception e) { - e.printStackTrace(); - } - throw new RuntimeException("can't load template " + name); - } - private String getCPResourcePath(String name) { - if (!"/".equals(File.separator)) - return name.replaceAll(Pattern.quote(File.separator), "/"); - return name; - } + private String getCPResourcePath(String name) { + if (!"/".equals(File.separator)) { + return name.replaceAll(Pattern.quote(File.separator), "/"); + } + return name; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java index 3f4334507ae..1aa0937b31b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java @@ -1,23 +1,23 @@ package io.swagger.codegen; public class CliOption { - private final String opt; - private String description; + private final String opt; + private String description; - public CliOption(String opt, String description) { - this.opt = opt; - this.description = description; - } + public CliOption(String opt, String description) { + this.opt = opt; + this.description = description; + } - public String getOpt() { - return opt; - } + public String getOpt() { + return opt; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java index c1d21f48035..da026c7f040 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -1,88 +1,92 @@ 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 { - private ClientOpts opts; - private Swagger swagger; - private List auths; - protected CodegenConfig config; + protected CodegenConfig config; + private ClientOpts opts; + private Swagger swagger; + private List auths; - public ClientOptInput swagger(Swagger swagger) { - this.setSwagger(swagger); - return this; - } - public ClientOptInput opts(ClientOpts opts) { - this.setOpts(opts); - return this; - } - - public void setAuth(String urlEncodedAuthString) { - List auths = new ArrayList(); - if(urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) { - String[] parts = urlEncodedAuthString.split(","); - for(String part : parts) { - String[] kvPair = part.split(":"); - if(kvPair.length == 2) { - auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); - } - } + public ClientOptInput swagger(Swagger swagger) { + this.setSwagger(swagger); + return this; } - 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(); + + public ClientOptInput opts(ClientOpts opts) { + this.setOpts(opts); + return this; } - else - return null; - } - public List getAuthorizationValues() { - return auths; - } - public CodegenConfig getConfig() { - return config; - } - public void setConfig(CodegenConfig config) { - this.config = config; - } + 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 setOpts(ClientOpts opts) { - this.opts = opts; - } + public void setAuth(String urlEncodedAuthString) { + List auths = new ArrayList(); + if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) { + String[] parts = urlEncodedAuthString.split(","); + for (String part : parts) { + String[] kvPair = part.split(":"); + if (kvPair.length == 2) { + auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); + } + } + } + this.auths = auths; + } - public ClientOpts getOpts() { - return opts; - } + public List getAuthorizationValues() { + return auths; + } - public void setSwagger(Swagger swagger) { - this.swagger = swagger; - } + public CodegenConfig getConfig() { + return config; + } - @ApiModelProperty(dataType="Object") - public Swagger getSwagger() { - return swagger; - } + public void setConfig(CodegenConfig config) { + this.config = config; + } + + public ClientOpts getOpts() { + return opts; + } + + public void setOpts(ClientOpts opts) { + this.opts = opts; + } + + @ApiModelProperty(dataType = "Object") + public Swagger getSwagger() { + return swagger; + } + + public void setSwagger(Swagger swagger) { + this.swagger = swagger; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java index 465fed820da..9c4d41f7bfd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java @@ -1,52 +1,57 @@ 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; - protected String target; - protected AuthMethod auth; - protected Map properties = new HashMap(); - protected String outputDirectory; + protected String uri; + protected String target; + protected AuthMethod auth; + protected Map properties = new HashMap(); + protected String outputDirectory; - public String getUri() { - return uri; - } - public void setUri(String uri) { - this.uri = uri; - } + public String getUri() { + return uri; + } - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } + public void setUri(String uri) { + this.uri = uri; + } - public Map getProperties() { - return properties; - } - public void setProperties(Map properties) { - this.properties = properties; - } + public String getTarget() { + return target; + } - public String getOutputDirectory() { - return outputDirectory; - } - public void setOutputDirectory(String outputDirectory) { - this.outputDirectory = outputDirectory; - } + public void setTarget(String target) { + this.target = target; + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("ClientOpts: {\n"); - sb.append(" uri: ").append(uri).append(","); - sb.append(" auth: ").append(auth).append(","); - sb.append(properties); - sb.append("}"); - return sb.toString(); - } + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public String getOutputDirectory() { + return outputDirectory; + } + + public void setOutputDirectory(String outputDirectory) { + this.outputDirectory = outputDirectory; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("ClientOpts: {\n"); + sb.append(" uri: ").append(uri).append(","); + sb.append(" auth: ").append(auth).append(","); + sb.append(properties); + sb.append("}"); + return sb.toString(); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index 8772a8b8ced..c99e04e5494 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -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} @@ -18,126 +21,128 @@ import java.util.*; */ @Deprecated public class Codegen extends DefaultGenerator { - static Map configs = new HashMap(); - static String configString; - static { - List extensions = getExtensions(); - StringBuilder sb = new StringBuilder(); + static Map configs = new HashMap(); + static String configString; + 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"; - 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) { - 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(); - StringBuilder sb = new StringBuilder(); + Options options = new Options(); + options.addOption("h", "help", false, "shows this message"); + options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); + options.addOption("o", "output", true, "where to write the generated files"); + options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file"); + options.addOption("t", "template-dir", true, "folder containing the template files"); + options.addOption("d", "debug-info", false, "prints additional info for debugging"); + options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); - Options options = new Options(); - options.addOption("h", "help", false, "shows this message"); - options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); - options.addOption("o", "output", true, "where to write the generated files"); - options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file"); - options.addOption("t", "template-dir", true, "folder containing the template files"); - options.addOption("d", "debug-info", false, "prints additional info for debugging"); - options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + Swagger swagger = null; - ClientOptInput clientOptInput = new ClientOptInput(); - ClientOpts clientOpts = new ClientOpts(); - Swagger swagger = null; + CommandLine cmd = null; + try { + CommandLineParser parser = new BasicParser(); + CodegenConfig config = null; - CommandLine cmd = null; - try { - CommandLineParser parser = new BasicParser(); - CodegenConfig config = null; - - cmd = parser.parse(options, args); - if (cmd.hasOption("d")) { - usage(options); - System.out.println(debugInfoOptions); - return; - } - if (cmd.hasOption("a")) - clientOptInput.setAuth(cmd.getOptionValue("a")); - if (cmd.hasOption("l")) - clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); - else { - usage(options); - return; - } - if (cmd.hasOption("o")) - clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); - if (cmd.hasOption("h")) { - if(cmd.hasOption("l")) { - config = getConfig(String.valueOf(cmd.getOptionValue("l"))); - if(config != null) { - options.addOption("h", "help", true, config.getHelp()); + cmd = parser.parse(options, args); + if (cmd.hasOption("d")) { + usage(options); + System.out.println(debugInfoOptions); + return; + } + if (cmd.hasOption("a")) { + clientOptInput.setAuth(cmd.getOptionValue("a")); + } + if (cmd.hasOption("l")) { + clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); + } else { + usage(options); + return; + } + if (cmd.hasOption("o")) { + clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); + } + if (cmd.hasOption("h")) { + if (cmd.hasOption("l")) { + config = getConfig(String.valueOf(cmd.getOptionValue("l"))); + if (config != null) { + options.addOption("h", "help", true, config.getHelp()); + usage(options); + return; + } + } + usage(options); + return; + } + if (cmd.hasOption("i")) { + swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); + } + if (cmd.hasOption("t")) { + clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); + } + } catch (Exception e) { usage(options); return; - } } - usage(options); - return; - } - if (cmd.hasOption("i")) - swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); - if (cmd.hasOption("t")) - clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); + try { + clientOptInput + .opts(clientOpts) + .swagger(swagger); + new Codegen().opts(clientOptInput).generate(); + } catch (Exception e) { + e.printStackTrace(); + } } - catch (Exception e) { - usage(options); - return; - } - try{ - clientOptInput - .opts(clientOpts) - .swagger(swagger); - new Codegen().opts(clientOptInput).generate(); - } - catch (Exception e) { - e.printStackTrace(); - } - } - public static List getExtensions() { - ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); - List output = new ArrayList(); - Iterator itr = loader.iterator(); - while(itr.hasNext()) { - output.add(itr.next()); + public static List getExtensions() { + ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); + List output = new ArrayList(); + Iterator itr = loader.iterator(); + while (itr.hasNext()) { + output.add(itr.next()); + } + return output; } - return output; - } - static void usage(Options options) { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp( "Codegen", options ); - } + static void usage(Options options) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("Codegen", options); + } - public static CodegenConfig getConfig(String name) { - if(configs.containsKey(name)) { - return configs.get(name); + public static CodegenConfig getConfig(String name) { + if (configs.containsKey(name)) { + return configs.get(name); + } 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) { + throw new RuntimeException("can't load class " + name); + } + } } - 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) { - throw new RuntimeException("can't load class " + name); - } + + static { + List 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(); + } } - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4ff582dcb11..6f96bd82b5d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -1,64 +1,105 @@ 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 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 cliOptions(); - String generateExamplePath(String path, Operation operation); + CodegenType getTag(); - Set reservedWords(); + String getName(); - List supportingFiles(); + String getHelp(); - void setOutputDir(String dir); - String getOutputDir(); + Map additionalProperties(); - CodegenModel fromModel(String name, Model model); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); - List fromSecurity(Map schemes); + String apiPackage(); - Set defaultIncludes(); - Map typeMapping(); - Map instantiationTypes(); - Map importMapping(); - Map apiTemplateFiles(); - Map modelTemplateFiles(); - void processSwagger(Swagger swagger); + String apiFileFolder(); - 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> operations); - Map postProcessModels(Map objs); - Map postProcessOperations(Map objs); - Map postProcessSupportingFileData(Map objs); + String fileSuffix(); - String apiFilename(String templateName, String tag); + String outputFolder(); - boolean shouldOverwrite(String filename); + 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 cliOptions(); + + String generateExamplePath(String path, Operation operation); + + Set reservedWords(); + + List supportingFiles(); + + String getOutputDir(); + + void setOutputDir(String dir); + + CodegenModel fromModel(String name, Model model); + + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); + + List fromSecurity(Map schemes); + + Set defaultIncludes(); + + Map typeMapping(); + + Map instantiationTypes(); + + Map importMapping(); + + Map apiTemplateFiles(); + + Map 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> operations); + + Map postProcessModels(Map objs); + + Map postProcessOperations(Map objs); + + Map postProcessSupportingFileData(Map objs); + + String apiFilename(String templateName, String tag); + + boolean shouldOverwrite(String filename); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 0cacc3a56e3..6a84274774c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -1,16 +1,18 @@ 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; - public String name, classname, description, classVarName, modelJson; - public String defaultValue; - public List vars = new ArrayList(); - public Set imports = new HashSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; - public ExternalDocs externalDocs; + public String parent; + public String name, classname, description, classVarName, modelJson; + public String defaultValue; + public List vars = new ArrayList(); + public Set imports = new HashSet(); + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; + public ExternalDocs externalDocs; } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java index 06dfcfbc86b..4c2b4d4eb87 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java @@ -5,34 +5,35 @@ import java.util.Map; public final class CodegenModelFactory { - private static final Map> typeMapping = new HashMap>(); + private static final Map> typeMapping = new HashMap>(); - /** - * 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 - */ - public static void setTypeMapping(CodegenModelType type, Class implementation) { - if (!type.getDefaultImplementation().isAssignableFrom(implementation)) { - throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName()); + /** + * 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 + */ + public static void setTypeMapping(CodegenModelType type, Class implementation) { + if (!type.getDefaultImplementation().isAssignableFrom(implementation)) { + throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName()); + } + try { + implementation.newInstance(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + typeMapping.put(type, implementation); } - try { - implementation.newInstance(); - } catch (Exception e) { - throw new IllegalArgumentException(e); - } - typeMapping.put(type, implementation); - } - @SuppressWarnings("unchecked") - public static T newInstance(CodegenModelType type) { - Class classType = typeMapping.get(type); - try { - return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); + @SuppressWarnings("unchecked") + public static T newInstance(CodegenModelType type) { + Class classType = typeMapping.get(type); + try { + return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); + } catch (InstantiationException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } } - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java index 8c082a899cd..dce8ab0e2e5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java @@ -2,20 +2,20 @@ package io.swagger.codegen; public enum CodegenModelType { - MODEL(CodegenModel.class), - OPERATION(CodegenOperation.class), - PARAMETER(CodegenParameter.class), - PROPERTY(CodegenProperty.class), - RESPONSE(CodegenResponse.class), - SECURITY(CodegenSecurity.class); + MODEL(CodegenModel.class), + OPERATION(CodegenOperation.class), + PARAMETER(CodegenParameter.class), + PROPERTY(CodegenProperty.class), + RESPONSE(CodegenResponse.class), + SECURITY(CodegenSecurity.class); - private final Class defaultImplementation; + private final Class defaultImplementation; - private CodegenModelType(Class defaultImplementation) { - this.defaultImplementation = defaultImplementation; - } + private CodegenModelType(Class defaultImplementation) { + this.defaultImplementation = defaultImplementation; + } - public Class getDefaultImplementation() { - return defaultImplementation; - } + public Class getDefaultImplementation() { + return defaultImplementation; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index f7bd875848c..b795f8e38e2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -1,32 +1,35 @@ 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 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 final List responseHeaders = new ArrayList(); + 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> consumes, produces; + public CodegenParameter bodyParam; + public List allParams = new ArrayList(); + public List bodyParams = new ArrayList(); + public List pathParams = new ArrayList(); + public List queryParams = new ArrayList(); + public List headerParams = new ArrayList(); + public List formParams = new ArrayList(); + public List authMethods; + public List tags; + public List responses = new ArrayList(); + public Set imports = new HashSet(); + public List> examples; + public ExternalDocs externalDocs; - public List> consumes, produces; - public CodegenParameter bodyParam; - public List allParams = new ArrayList(); - public List bodyParams = new ArrayList(); - public List pathParams = new ArrayList(); - public List queryParams = new ArrayList(); - public List headerParams = new ArrayList(); - public List formParams = new ArrayList(); - public List authMethods; - public List tags; - public List responses = new ArrayList(); - public final List responseHeaders = new ArrayList(); - public Set imports = new HashSet(); - public List> examples; - public ExternalDocs externalDocs; - - // legacy support - public String nickname; + // legacy support + public String nickname; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index f19809606d1..6777d1028da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -1,41 +1,41 @@ package io.swagger.codegen; public class CodegenParameter { - public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, - isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; - public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; - public String jsonSchema; + public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, + isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; + public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; + public String jsonSchema; - /** - * Determines whether this parameter is mandatory. If the parameter is in "path", - * this property is required and its value MUST be true. Otherwise, the property - * MAY be included and its default value is false. - */ - public Boolean required; + /** + * Determines whether this parameter is mandatory. If the parameter is in "path", + * this property is required and its value MUST be true. Otherwise, the property + * MAY be included and its default value is false. + */ + public Boolean required; - public CodegenParameter copy() { - CodegenParameter output = new CodegenParameter(); - output.isFile = this.isFile; - output.notFile = this.notFile; - output.hasMore = this.hasMore; - output.isContainer = this.isContainer; - output.secondaryParam = this.secondaryParam; - output.baseName = this.baseName; - output.paramName = this.paramName; - output.dataType = this.dataType; - output.collectionFormat = this.collectionFormat; - output.description = this.description; - output.baseType = this.baseType; - output.isFormParam = this.isFormParam; - output.isQueryParam = this.isQueryParam; - output.isPathParam = this.isPathParam; - output.isHeaderParam = this.isHeaderParam; - output.isCookieParam = this.isCookieParam; - output.isBodyParam = this.isBodyParam; - output.required = this.required; - output.jsonSchema = this.jsonSchema; - output.defaultValue = this.defaultValue; + public CodegenParameter copy() { + CodegenParameter output = new CodegenParameter(); + output.isFile = this.isFile; + output.notFile = this.notFile; + output.hasMore = this.hasMore; + output.isContainer = this.isContainer; + output.secondaryParam = this.secondaryParam; + output.baseName = this.baseName; + output.paramName = this.paramName; + output.dataType = this.dataType; + output.collectionFormat = this.collectionFormat; + output.description = this.description; + output.baseType = this.baseType; + output.isFormParam = this.isFormParam; + output.isQueryParam = this.isQueryParam; + output.isPathParam = this.isPathParam; + output.isHeaderParam = this.isHeaderParam; + output.isCookieParam = this.isCookieParam; + output.isBodyParam = this.isBodyParam; + output.required = this.required; + output.jsonSchema = this.jsonSchema; + output.defaultValue = this.defaultValue; - return output; - } + return output; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 407266add1f..7872da2c707 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -1,28 +1,37 @@ 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; + 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 */ - public Integer maxLength; - /** 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 */ - public String pattern; - /** A free-form property to include an example of an instance for this schema. */ - public String example; + /** + * 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 + */ + public Integer minLength; + /** + * 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. + */ + public String example; - public String jsonSchema; - public Double minimum; - public Double maximum; - public Boolean exclusiveMinimum; - public Boolean exclusiveMaximum; - public Boolean hasMore = null, required = null, secondaryParam = null; - public Boolean isPrimitiveType, isContainer, isNotContainer; - public boolean isEnum; - public List _enum; - public Map allowableValues; + public String jsonSchema; + public Double minimum; + public Double maximum; + public Boolean exclusiveMinimum; + public Boolean exclusiveMaximum; + public Boolean hasMore = null, required = null, secondaryParam = null; + public Boolean isPrimitiveType, isContainer, isNotContainer; + public boolean isEnum; + public List _enum; + public Map allowableValues; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index 514ced65b63..6d90152f514 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -5,17 +5,20 @@ import java.util.List; import java.util.Map; public class CodegenResponse { - public String code, message; - public Boolean hasMore; - public List> examples; - public final List headers = new ArrayList(); - public String dataType, baseType, containerType; - public Boolean isDefault; - public Boolean simpleType; - public Boolean primitiveType; - public Boolean isMapContainer; - public Boolean isListContainer; - public Object schema; - public String jsonSchema; - public boolean isWildcard() { return "0".equals(code) || "default".equals(code); } + public final List headers = new ArrayList(); + public String code, message; + public Boolean hasMore; + public List> examples; + public String dataType, baseType, containerType; + public Boolean isDefault; + public Boolean simpleType; + public Boolean primitiveType; + public Boolean isMapContainer; + public Boolean isListContainer; + public Object schema; + public String jsonSchema; + + public boolean isWildcard() { + return "0".equals(code) || "default".equals(code); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index 09e1a503191..8613e0a8d41 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -1,10 +1,10 @@ package io.swagger.codegen; public class CodegenSecurity { - public String name; - public String type; - public Boolean hasMore, isBasic, isOAuth, isApiKey; - // ApiKey specific - public String keyParamName; - public Boolean isKeyInQuery, isKeyInHeader; + public String name; + public String type; + public Boolean hasMore, isBasic, isOAuth, isApiKey; + // ApiKey specific + public String keyParamName; + public Boolean isKeyInQuery, isKeyInHeader; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java index b7c8aad9f1b..8d65290e8f8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java @@ -1,34 +1,36 @@ 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; + CLIENT, SERVER, DOCUMENTATION, OTHER; - private static Map names = new HashMap(); + private static Map names = new HashMap(); - 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()); - } - - @JsonValue - public String toValue() { - for (Map.Entry entry : names.entrySet()) { - if (entry.getValue() == this) - return entry.getKey(); + @JsonCreator + public static CodegenType forValue(String value) { + return names.get(value.toLowerCase()); } - return null; // or fail - } + @JsonValue + public String toValue() { + for (Map.Entry entry : names.entrySet()) { + 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); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index e342d07f66f..c15c2abaa57 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1,25 +1,5 @@ package io.swagger.codegen; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nullable; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.common.base.Function; import com.google.common.collect.Lists; import io.swagger.codegen.examples.ExampleGenerator; @@ -59,1219 +39,1462 @@ import io.swagger.models.properties.PropertyBuilder; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import io.swagger.util.Json; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class DefaultCodegen { - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); - protected String outputFolder = ""; - protected Set defaultIncludes = new HashSet(); - protected Map typeMapping = new HashMap(); - protected Map instantiationTypes = new HashMap(); - protected Set reservedWords = new HashSet(); - protected Set languageSpecificPrimitives = new HashSet(); - protected Map importMapping = new HashMap(); - protected String modelPackage = "", apiPackage = "", fileSuffix; - protected Map apiTemplateFiles = new HashMap(); - protected Map modelTemplateFiles = new HashMap(); - protected String templateDir; - protected Map additionalProperties = new HashMap(); - protected List supportingFiles = new ArrayList(); - protected List cliOptions = new ArrayList(); + protected String outputFolder = ""; + protected Set defaultIncludes = new HashSet(); + protected Map typeMapping = new HashMap(); + protected Map instantiationTypes = new HashMap(); + protected Set reservedWords = new HashSet(); + protected Set languageSpecificPrimitives = new HashSet(); + protected Map importMapping = new HashMap(); + protected String modelPackage = "", apiPackage = "", fileSuffix; + protected Map apiTemplateFiles = new HashMap(); + protected Map modelTemplateFiles = new HashMap(); + protected String templateDir; + protected Map additionalProperties = new HashMap(); + protected List supportingFiles = new ArrayList(); + protected List cliOptions = new ArrayList(); - public List cliOptions() { - return cliOptions; - } - - public void processOpts(){ - if(additionalProperties.containsKey("templateDir")) { - this.setTemplateDir((String)additionalProperties.get("templateDir")); + public List cliOptions() { + return cliOptions; } - - if(additionalProperties.containsKey("modelPackage")) { - this.setModelPackage((String)additionalProperties.get("modelPackage")); - } - - if(additionalProperties.containsKey("apiPackage")) { - this.setApiPackage((String)additionalProperties.get("apiPackage")); - } - } - // override with any special post-processing - public Map postProcessModels(Map objs) { - return objs; - } - - // override with any special post-processing - public Map postProcessOperations(Map objs) { - return objs; - } - - // override with any special post-processing - public Map postProcessSupportingFileData(Map objs) { - return objs; - } - - // override with any special handling of the entire swagger spec - public void processSwagger(Swagger swagger) {} - - // override with any special text escaping logic - public String escapeText(String input) { - if(input != null) { - String output = input.replaceAll("\n", "\\\\n"); - output = output.replace("\"", "\\\""); - return output; - } - return input; - } - - public Set defaultIncludes() { - return defaultIncludes; - } - public Map typeMapping() { - return typeMapping; - } - public Map instantiationTypes() { - return instantiationTypes; - } - public Set reservedWords() { - return reservedWords; - } - public Set languageSpecificPrimitives() { - return languageSpecificPrimitives; - } - public Map importMapping() { - return importMapping; - } - public String modelPackage() { - return modelPackage; - } - public String apiPackage() { - return apiPackage; - } - public String fileSuffix() { - return fileSuffix; - } - public String templateDir() { - return templateDir; - } - public Map apiTemplateFiles() { - return apiTemplateFiles; - } - public Map modelTemplateFiles() { - return modelTemplateFiles; - } - - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - public Map additionalProperties() { - return additionalProperties; - } - public List supportingFiles() { - return supportingFiles; - } - public String outputFolder() { - return outputFolder; - } - - public void setOutputDir(String dir) { - this.outputFolder = dir; - } - public String getOutputDir() { - return outputFolder(); - } - - public void setTemplateDir(String templateDir) { - this.templateDir = templateDir; - } - - public void setModelPackage(String modelPackage) { - this.modelPackage = modelPackage; - } - - public void setApiPackage(String apiPackage) { - this.apiPackage = apiPackage; - } - - public String toApiFilename(String name) { - return toApiName(name); - } - - public String toApiVarName(String name) { - return snakeCase(name); - } - - public String toModelFilename(String name) { - return initialCaps(name); - } - - public String toOperationId(String operationId) { return operationId; } - - public String toVarName(String name) { - if(reservedWords.contains(name)) - return escapeReservedWord(name); - else - return name; - } - - public String toParamName(String name) { - name = removeNonNameElementToCamelCase(name); - if(reservedWords.contains(name)) { - return escapeReservedWord(name); - } - return name; - } - - public String toEnumName(CodegenProperty property) { - return StringUtils.capitalize(property.name) + "Enum"; - } - - public String escapeReservedWord(String name) { - throw new RuntimeException("reserved word " + name + " not allowed"); - } - - public String toModelImport(String name) { - if("".equals(modelPackage())) - return name; - else - return modelPackage() + "." + name; - } - - public String toApiImport(String name) { - return apiPackage() + "." + name; - } - - public DefaultCodegen() { - defaultIncludes = new HashSet( - Arrays.asList("double", - "int", - "long", - "short", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Void", - "Integer", - "Long", - "Float") - ); - - typeMapping = new HashMap(); - typeMapping.put("array", "List"); - typeMapping.put("map", "Map"); - typeMapping.put("List", "List"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("int", "Integer"); - typeMapping.put("float", "Float"); - typeMapping.put("number", "BigDecimal"); - typeMapping.put("DateTime", "Date"); - typeMapping.put("long", "Long"); - typeMapping.put("short", "Short"); - typeMapping.put("char", "String"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "Object"); - typeMapping.put("integer", "Integer"); - - instantiationTypes = new HashMap(); - - reservedWords = new HashSet(); - - importMapping = new HashMap(); - importMapping.put("BigDecimal", "java.math.BigDecimal"); - importMapping.put("UUID", "java.util.UUID"); - importMapping.put("File", "java.io.File"); - importMapping.put("Date", "java.util.Date"); - importMapping.put("Timestamp", "java.sql.Timestamp"); - importMapping.put("Map", "java.util.Map"); - importMapping.put("HashMap", "java.util.HashMap"); - importMapping.put("Array", "java.util.List"); - importMapping.put("ArrayList", "java.util.ArrayList"); - importMapping.put("List", "java.util.*"); - importMapping.put("Set", "java.util.*"); - importMapping.put("DateTime", "org.joda.time.*"); - importMapping.put("LocalDateTime", "org.joda.time.*"); - importMapping.put("LocalDate", "org.joda.time.*"); - importMapping.put("LocalTime", "org.joda.time.*"); - - cliOptions.add(new CliOption("modelPackage", "package for generated models")); - cliOptions.add(new CliOption("apiPackage", "package for generated api classes")); - } - - - public String generateExamplePath(String path, Operation operation) { - StringBuilder sb = new StringBuilder(); - sb.append(path); - - if(operation.getParameters() != null) { - int count = 0; - - for(Parameter param : operation.getParameters()) { - if(param instanceof QueryParameter) { - StringBuilder paramPart = new StringBuilder(); - QueryParameter qp = (QueryParameter) param; - - if(count == 0) - paramPart.append("?"); - else - paramPart.append(","); - count += 1; - if(!param.getRequired()) - paramPart.append("["); - paramPart.append(param.getName()).append("="); - paramPart.append("{"); - if(qp.getCollectionFormat() != null) { - paramPart.append(param.getName() + "1"); - if("csv".equals(qp.getCollectionFormat())) - paramPart.append(","); - else if("pipes".equals(qp.getCollectionFormat())) - paramPart.append("|"); - else if("tsv".equals(qp.getCollectionFormat())) - paramPart.append("\t"); - else if("multi".equals(qp.getCollectionFormat())) { - paramPart.append("&").append(param.getName()).append("="); - paramPart.append(param.getName() + "2"); - } - } - else { - paramPart.append(param.getName()); - } - paramPart.append("}"); - if(!param.getRequired()) - paramPart.append("]"); - sb.append(paramPart.toString()); + public void processOpts() { + if (additionalProperties.containsKey("templateDir")) { + this.setTemplateDir((String) additionalProperties.get("templateDir")); } - } - } - return sb.toString(); - } - - 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) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "<" + inner + ">"; - } - else - return null; - } - - public String toDefaultValue(Property p) { - if(p instanceof StringProperty) - return "null"; - else if (p instanceof BooleanProperty) - return "null"; - else if(p instanceof DateProperty) - return "null"; - else if(p instanceof DateTimeProperty) - return "null"; - else if (p instanceof DoubleProperty) { - DoubleProperty dp = (DoubleProperty) p; - if(dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } - else if (p instanceof FloatProperty) { - FloatProperty dp = (FloatProperty) p; - if(dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } - else if (p instanceof IntegerProperty) { - IntegerProperty dp = (IntegerProperty) p; - if(dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } - else if (p instanceof LongProperty) { - LongProperty dp = (LongProperty) p; - if(dp.getDefault() != null) { - return dp.getDefault().toString(); - } - return "null"; - } - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap() "; - } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ArrayList<" + inner + ">() "; - } - else - return "null"; - } - - /** - * returns the swagger type for the property - **/ - public String getSwaggerType(Property p) { - String datatype = null; - if(p instanceof StringProperty) - datatype = "string"; - else if (p instanceof BooleanProperty) - datatype = "boolean"; - else if(p instanceof DateProperty) - datatype = "date"; - else if(p instanceof DateTimeProperty) - datatype = "DateTime"; - else if (p instanceof DoubleProperty) - datatype = "double"; - else if (p instanceof FloatProperty) - datatype = "float"; - else if (p instanceof IntegerProperty) - datatype = "integer"; - else if (p instanceof LongProperty) - datatype = "long"; - else if (p instanceof MapProperty) - datatype = "map"; - else if (p instanceof DecimalProperty) - datatype = "number"; - else if (p instanceof RefProperty) { - RefProperty r = (RefProperty)p; - datatype = r.get$ref(); - if(datatype.indexOf("#/definitions/") == 0) - datatype = datatype.substring("#/definitions/".length()); - } - else { - if(p != null) datatype = p.getType(); - } - return datatype; - } - - public String snakeCase(String name) { - return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; - } - - public String initialCaps(String name) { - return StringUtils.capitalize(name); - } - - public String getTypeDeclaration(String name) { - return name; - } - - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if(typeMapping.containsKey(swaggerType)) - return typeMapping.get(swaggerType); - return swaggerType; - } - - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultApi"; - return initialCaps(name) + "Api"; - } - - public String toModelName(String name) { - return initialCaps(name); - } - - public CodegenModel fromModel(String name, Model model) { - CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); - if(reservedWords.contains(name)) - m.name = escapeReservedWord(name); - else - m.name = name; - m.description = escapeText(model.getDescription()); - m.classname = toModelName(name); - m.classVarName = toVarName(name); - m.modelJson = Json.pretty(model); - m.externalDocs = model.getExternalDocs(); - if(model instanceof ArrayModel) { - ArrayModel am = (ArrayModel) model; - ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); - addParentContainer(m, name, arrayProperty); - } - else if (model instanceof RefModel) { - // TODO - } else if (model instanceof ComposedModel) { - final ComposedModel composed = (ComposedModel) model; - final RefModel parent = (RefModel) composed.getParent(); - final String parentModel = toModelName(parent.getSimpleRef()); - m.parent = parentModel; - addImport(m, parentModel); - final ModelImpl child = (ModelImpl) composed.getChild(); - addVars(m, child.getProperties(), child.getRequired()); - } else { - ModelImpl impl = (ModelImpl) model; - if(impl.getAdditionalProperties() != null) { - MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); - addParentContainer(m, name, mapProperty); - } - addVars(m, impl.getProperties(), impl.getRequired()); - } - return m; - } - - public String getterAndSetterCapitalize(String name) { - if (name == null || name.length() == 0) { - return name; - } - - return camelize(toVarName(name)); - - } - - public CodegenProperty fromProperty(String name, Property p) { - if(p == null) { - LOGGER.error("unexpected missing property for name " + null); - return null; - } - CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); - - property.name = toVarName(name); - property.baseName = name; - property.description = escapeText(p.getDescription()); - property.getter = "get" + getterAndSetterCapitalize(name); - property.setter = "set" + getterAndSetterCapitalize(name); - property.example = p.getExample(); - property.defaultValue = toDefaultValue(p); - property.jsonSchema = Json.pretty(p); - - String type = getSwaggerType(p); - if(p instanceof AbstractNumericProperty) { - AbstractNumericProperty np = (AbstractNumericProperty) p; - property.minimum = np.getMinimum(); - property.maximum = np.getMaximum(); - property.exclusiveMinimum = np.getExclusiveMinimum(); - property.exclusiveMaximum = np.getExclusiveMaximum(); - - // legacy support - Map allowableValues = new HashMap(); - if(np.getMinimum() != null) - allowableValues.put("min", np.getMinimum()); - if(np.getMaximum() != null) - allowableValues.put("max", np.getMaximum()); - property.allowableValues = allowableValues; - } - - if(p instanceof StringProperty) { - StringProperty sp = (StringProperty) p; - property.maxLength = sp.getMaxLength(); - property.minLength = sp.getMinLength(); - property.pattern = sp.getPattern(); - if(sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = _enum; - property.isEnum = true; - - // legacy support - Map allowableValues = new HashMap(); - allowableValues.put("values", _enum); - property.allowableValues = allowableValues; - } - } - - property.datatype = getTypeDeclaration(p); - - // this can cause issues for clients which don't support enums - if(property.isEnum) - property.datatypeWithEnum = toEnumName(property); - else - property.datatypeWithEnum = property.datatype; - - property.baseType = getSwaggerType(p); - - if(p instanceof ArrayProperty) { - property.isContainer = true; - property.containerType = "array"; - ArrayProperty ap = (ArrayProperty) p; - CodegenProperty cp = fromProperty("inner", ap.getItems()); - if(cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); - } - else { - property.baseType = getSwaggerType(p); - if(!languageSpecificPrimitives.contains(cp.baseType)) - property.complexType = cp.baseType; - else - property.isPrimitiveType = true; - } - } - else if(p instanceof MapProperty) { - property.isContainer = true; - property.containerType = "map"; - MapProperty ap = (MapProperty) p; - CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); - - property.baseType = getSwaggerType(p); - if(!languageSpecificPrimitives.contains(cp.baseType)) - property.complexType = cp.baseType; - else - property.isPrimitiveType = true; - } - else { - setNonArrayMapProperty(property, type); - } - return property; - } - - protected void setNonArrayMapProperty(CodegenProperty property, String type) { - property.isNotContainer = true; - if(languageSpecificPrimitives().contains(type)) - property.isPrimitiveType = true; - else - property.complexType = property.baseType; - } - - private Response findMethodResponse(Map responses) { - - String code = null; - for(String responseCode : responses.keySet()) { - if (responseCode.startsWith("2") || responseCode.equals("default")) { - if (code == null || code.compareTo(responseCode) > 0) { - code = responseCode; + if (additionalProperties.containsKey("modelPackage")) { + this.setModelPackage((String) additionalProperties.get("modelPackage")); } - } - } - if (code == null) - return null; - return responses.get(code); - } - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); - Set imports = new HashSet(); - - String operationId = operation.getOperationId(); - if(operationId == null) { - String tmpPath = path; - tmpPath = tmpPath.replaceAll("\\{", ""); - tmpPath = tmpPath.replaceAll("\\}", ""); - String[] parts = (tmpPath + "/" + httpMethod).split("/"); - StringBuilder builder = new StringBuilder(); - if("/".equals(tmpPath)) { - // must be root tmpPath - builder.append("root"); - } - for(int i = 0; i < parts.length; i++) { - String part = parts[i]; - if(part.length() > 0) { - if(builder.toString().length() == 0) - part = Character.toLowerCase(part.charAt(0)) + part.substring(1); - else - part = initialCaps(part); - builder.append(part); + if (additionalProperties.containsKey("apiPackage")) { + this.setApiPackage((String) additionalProperties.get("apiPackage")); } - } - operationId = builder.toString(); - LOGGER.warn("generated operationId " + operationId); - } - operationId = removeNonNameElementToCamelCase(operationId); - op.path = path; - op.operationId = toOperationId(operationId); - op.summary = escapeText(operation.getSummary()); - op.notes = escapeText(operation.getDescription()); - op.tags = operation.getTags(); - - if(operation.getConsumes() != null && operation.getConsumes().size() > 0) { - List> c = new ArrayList>(); - int count = 0; - for(String key: operation.getConsumes()) { - Map mediaType = new HashMap(); - mediaType.put("mediaType", key); - count += 1; - if (count < operation.getConsumes().size()) - mediaType.put("hasMore", "true"); - else - mediaType.put("hasMore", null); - c.add(mediaType); - } - op.consumes = c; - op.hasConsumes = true; } - if(operation.getProduces() != null && operation.getProduces().size() > 0) { - List> c = new ArrayList>(); - int count = 0; - for(String key: operation.getProduces()) { - Map mediaType = new HashMap(); - mediaType.put("mediaType", key); - count += 1; - if (count < operation.getProduces().size()) - mediaType.put("hasMore", "true"); - else - mediaType.put("hasMore", null); - c.add(mediaType); - } - op.produces = c; - op.hasProduces = true; + // override with any special post-processing + public Map postProcessModels(Map objs) { + return objs; } - if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); + // override with any special post-processing + public Map postProcessOperations(Map objs) { + return objs; + } - for (Map.Entry entry : operation.getResponses().entrySet()) { - Response response = entry.getValue(); - CodegenResponse r = fromResponse(entry.getKey(), response); - r.hasMore = true; - if(r.baseType != null && - !defaultIncludes.contains(r.baseType) && - !languageSpecificPrimitives.contains(r.baseType)) - imports.add(r.baseType); - r.isDefault = response == methodResponse; - op.responses.add(r); - } - op.responses.get(op.responses.size() - 1).hasMore = false; + // override with any special post-processing + public Map postProcessSupportingFileData(Map objs) { + return objs; + } - if(methodResponse != null) { - if (methodResponse.getSchema() != null) { - CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + // override with any special handling of the entire swagger spec + public void processSwagger(Swagger swagger) { + } - Property responseProperty = methodResponse.getSchema(); - - if(responseProperty instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) responseProperty; - CodegenProperty innerProperty = fromProperty("response", ap.getItems()); - op.returnBaseType = innerProperty.baseType; + // override with any special text escaping logic + public String escapeText(String input) { + if (input != null) { + String output = input.replaceAll("\n", "\\\\n"); + output = output.replace("\"", "\\\""); + return output; } - else { - if(cm.complexType != null) - op.returnBaseType = cm.complexType; - else - op.returnBaseType = cm.baseType; - } - op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); - op.defaultResponse = toDefaultValue(responseProperty); - op.returnType = cm.datatype; - if(cm.isContainer != null) { - op.returnContainer = cm.containerType; - if("map".equals(cm.containerType)) - op.isMapContainer = Boolean.TRUE; - else if ("list".equalsIgnoreCase(cm.containerType)) - op.isListContainer = Boolean.TRUE; - else if ("array".equalsIgnoreCase(cm.containerType)) - op.isListContainer = Boolean.TRUE; - } - else - op.returnSimpleType = true; - if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) - op.returnTypeIsPrimitive = true; - } - addHeaders(methodResponse, op.responseHeaders); - } + return input; } - List parameters = operation.getParameters(); - CodegenParameter bodyParam = null; - List allParams = new ArrayList(); - List bodyParams = new ArrayList(); - List pathParams = new ArrayList(); - List queryParams = new ArrayList(); - List headerParams = new ArrayList(); - List cookieParams = new ArrayList(); - List formParams = new ArrayList(); - - if(parameters != null) { - for(Parameter param : parameters) { - CodegenParameter p = fromParameter(param, imports); - allParams.add(p); - if(param instanceof QueryParameter) { - p.isQueryParam = new Boolean(true); - queryParams.add(p.copy()); - } - else if(param instanceof PathParameter) { - p.required = true; - p.isPathParam = new Boolean(true); - pathParams.add(p.copy()); - } - else if(param instanceof HeaderParameter) { - p.isHeaderParam = new Boolean(true); - headerParams.add(p.copy()); - } - else if(param instanceof CookieParameter) { - p.isCookieParam = new Boolean(true); - cookieParams.add(p.copy()); - } - else if(param instanceof BodyParameter) { - p.isBodyParam = new Boolean(true); - bodyParam = p; - bodyParams.add(p.copy()); - } - else if(param instanceof FormParameter) { - if("file".equalsIgnoreCase(((FormParameter)param).getType())) - p.isFile = true; - else - p.notFile = true; - p.isFormParam = new Boolean(true); - formParams.add(p.copy()); - } - } - } - for(String i: imports) { - if(!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)){ - op.imports.add(i); - } - } - op.bodyParam = bodyParam; - op.httpMethod = httpMethod.toUpperCase(); - op.allParams = addHasMore(allParams); - op.bodyParams = addHasMore(bodyParams); - op.pathParams = addHasMore(pathParams); - op.queryParams = addHasMore(queryParams); - op.headerParams = addHasMore(headerParams); - // op.cookieParams = cookieParams; - op.formParams = addHasMore(formParams); - // legacy support - op.nickname = op.operationId; - - - if(op.allParams.size() > 0) - op.hasParams = true; - op.externalDocs = operation.getExternalDocs(); - - return op; - } - - public CodegenResponse fromResponse(String responseCode, Response response) { - CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); - if("default".equals(responseCode)) - r.code = "0"; - else - r.code = responseCode; - r.message = response.getDescription(); - r.schema = response.getSchema(); - r.examples = toExamples(response.getExamples()); - r.jsonSchema = Json.pretty(response); - addHeaders(response, r.headers); - - if (r.schema != null) { - Property responseProperty = response.getSchema(); - responseProperty.setRequired(true); - CodegenProperty cm = fromProperty("response", responseProperty); - - if(responseProperty instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) responseProperty; - CodegenProperty innerProperty = fromProperty("response", ap.getItems()); - r.baseType = innerProperty.baseType; - } - else { - if(cm.complexType != null) - r.baseType = cm.complexType; - else - r.baseType = cm.baseType; - } - r.dataType = cm.datatype; - if(cm.isContainer != null) { - r.simpleType = false; - r.containerType = cm.containerType; - r.isMapContainer = "map".equals(cm.containerType); - r.isListContainer = "list".equals(cm.containerType); - } - else - r.simpleType = true; - r.primitiveType = (r.baseType == null ||languageSpecificPrimitives().contains(r.baseType)); - } - if (r.baseType == null) { - r.isMapContainer = false; - r.isListContainer = false; - r.primitiveType = true; - r.simpleType = true; - } - return r; - } - - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); - p.baseName = param.getName(); - p.description = escapeText(param.getDescription()); - if(param.getRequired()) - p.required = param.getRequired(); - p.jsonSchema = Json.pretty(param); - - // move the defaultValue for headers, forms and params - if(param instanceof QueryParameter) { - p.defaultValue = ((QueryParameter)param).getDefaultValue(); - } else if(param instanceof HeaderParameter) { - p.defaultValue = ((HeaderParameter)param).getDefaultValue(); - } else if(param instanceof FormParameter) { - p.defaultValue = ((FormParameter)param).getDefaultValue(); + public Set defaultIncludes() { + return defaultIncludes; } - if(param instanceof SerializableParameter) { - SerializableParameter qp = (SerializableParameter) param; - Property property = null; - String collectionFormat = null; - if("array".equals(qp.getType())) { - Property inner = qp.getItems(); - if(inner == null) { - LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); - } - property = new ArrayProperty(inner); - collectionFormat = qp.getCollectionFormat(); - CodegenProperty pr = fromProperty("inner", inner); - p.baseType = pr.datatype; - p.isContainer = true; - imports.add(pr.baseType); - } - else if("object".equals(qp.getType())) { - Property inner = qp.getItems(); - if(inner == null) { - LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); - inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); - } - property = new MapProperty(inner); - collectionFormat = qp.getCollectionFormat(); - CodegenProperty pr = fromProperty("inner", inner); - p.baseType = pr.datatype; - imports.add(pr.baseType); - } - else - property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null); - if(property == null) { - LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); - property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); - } - property.setRequired(param.getRequired()); - CodegenProperty model = fromProperty(qp.getName(), property); - p.collectionFormat = collectionFormat; - p.dataType = model.datatype; - p.paramName = toParamName(qp.getName()); - - if(model.complexType != null) { - imports.add(model.complexType); - } + public Map typeMapping() { + return typeMapping; } - else { - BodyParameter bp = (BodyParameter) param; - Model model = bp.getSchema(); - if(model instanceof ModelImpl) { - ModelImpl impl = (ModelImpl) model; - CodegenModel cm = fromModel(bp.getName(), impl); - if(cm.emptyVars != null && cm.emptyVars == false) { - p.dataType = getTypeDeclaration(cm.classname); - imports.add(p.dataType); - } - else { - // TODO: missing format, so this will not always work - Property prop = PropertyBuilder.build(impl.getType(), null, null); - prop.setRequired(bp.getRequired()); - CodegenProperty cp = fromProperty("property", prop); - if(cp != null) { - p.dataType = cp.datatype; - } - } - } - else if(model instanceof ArrayModel) { - // to use the built-in model parsing, we unwrap the ArrayModel - // and get a single property from it - ArrayModel impl = (ArrayModel) model; - CodegenModel cm = fromModel(bp.getName(), impl); - // get the single property - ArrayProperty ap = new ArrayProperty().items(impl.getItems()); - ap.setRequired(param.getRequired()); - CodegenProperty cp = fromProperty("inner", ap); - if(cp.complexType != null) { - imports.add(cp.complexType); - } - imports.add(cp.baseType); - p.dataType = cp.datatype; - p.isContainer = true; - } - else{ - Model sub = bp.getSchema(); - if(sub instanceof RefModel) { - String name = ((RefModel)sub).getSimpleRef(); - if(typeMapping.containsKey(name)) - name = typeMapping.get(name); - else { - name = toModelName(name); - if(defaultIncludes.contains(name)) { - imports.add(name); - } - imports.add(name); - name = getTypeDeclaration(name); - } - p.dataType = name; - } - } - p.paramName = toParamName(bp.getName()); + public Map instantiationTypes() { + return instantiationTypes; } - return p; - } - public List fromSecurity(Map schemes) { - if(schemes == null) - return null; - - List secs = new ArrayList(schemes.size()); - for (Iterator> it = schemes.entrySet().iterator(); it.hasNext();) { - final Map.Entry entry = it.next(); - final SecuritySchemeDefinition schemeDefinition = entry.getValue(); - - CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); - sec.name = entry.getKey(); - sec.type = schemeDefinition.getType(); - - if (schemeDefinition instanceof ApiKeyAuthDefinition) { - final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; - sec.isBasic = sec.isOAuth = false; - sec.isApiKey = true; - sec.keyParamName = apiKeyDefinition.getName(); - sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; - sec.isKeyInQuery = !sec.isKeyInHeader; - } else { - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = false; - sec.isBasic = schemeDefinition instanceof BasicAuthDefinition; - sec.isOAuth = !sec.isBasic; - } - - sec.hasMore = it.hasNext(); - secs.add(sec); + public Set reservedWords() { + return reservedWords; } - return secs; - } - protected List> toExamples(Map examples) { - if(examples == null) - return null; - - final List> output = new ArrayList>(examples.size()); - for(Map.Entry entry : examples.entrySet()) { - final Map kv = new HashMap(); - kv.put("contentType", entry.getKey()); - kv.put("example", entry.getValue()); - output.add(kv); + public Set languageSpecificPrimitives() { + return languageSpecificPrimitives; } - return output; - } - private void addHeaders(Response response, List target) { - if (response.getHeaders() != null) { - for (Map.Entry headers : response.getHeaders().entrySet()) { - target.add(fromProperty(headers.getKey(), headers.getValue())); - } + public Map importMapping() { + return importMapping; } - } - private List addHasMore(List objs) { - if(objs != null) { - for(int i = 0; i < objs.size(); i++) { - if(i > 0) - objs.get(i).secondaryParam = new Boolean(true); - if(i < objs.size() - 1) - objs.get(i).hasMore = new Boolean(true); - } + public String modelPackage() { + return modelPackage; } - return objs; - } - private Map addHasMore(Map objs) { - if(objs != null) { - for(int i = 0; i < objs.size() - 1; i++) { - if(i > 0) - objs.put("secondaryParam", new Boolean(true)); - if(i < objs.size() - 1) - objs.put("hasMore", true); - } + public String apiPackage() { + return apiPackage; } - return objs; - } - - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - List opList = operations.get(tag); - if(opList == null) { - opList = new ArrayList(); - operations.put(tag, opList); + public String fileSuffix() { + return fileSuffix; } - opList.add(co); - co.baseName = tag; - } - private void addParentContainer(CodegenModel m, String name, Property property) { - final CodegenProperty tmp = fromProperty(name, property); - addImport(m, tmp.complexType); - m.parent = toInstantiationType(property); - final String containerType = tmp.containerType; - final String instantiationType = instantiationTypes.get(containerType); - if (instantiationType != null) { - addImport(m, instantiationType); + public String templateDir() { + return templateDir; } - final String mappedType = typeMapping.get(containerType); - if (mappedType != null) { - addImport(m, mappedType); + + public Map apiTemplateFiles() { + return apiTemplateFiles; } - } - private void addImport(CodegenModel m, String type) { - if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { - m.imports.add(type); + public Map modelTemplateFiles() { + return modelTemplateFiles; } - } - private void addVars(CodegenModel m, Map properties, Collection required) { - if (properties != null && properties.size() > 0) { - m.hasVars = true; - m.hasEnums = false; - final int totalCount = properties.size(); - final Set mandatory = required == null ? Collections. emptySet() : new HashSet(required); - int count = 0; - for (Map.Entry entry : properties.entrySet()) { - final String key = entry.getKey(); - final Property prop = entry.getValue(); + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } - if (prop == null) { - LOGGER.warn("null property for " + key); + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + public Map additionalProperties() { + return additionalProperties; + } + + public List supportingFiles() { + return supportingFiles; + } + + public String outputFolder() { + return outputFolder; + } + + public void setOutputDir(String dir) { + this.outputFolder = dir; + } + + public String getOutputDir() { + return outputFolder(); + } + + public void setTemplateDir(String templateDir) { + this.templateDir = templateDir; + } + + public void setModelPackage(String modelPackage) { + this.modelPackage = modelPackage; + } + + public void setApiPackage(String apiPackage) { + this.apiPackage = apiPackage; + } + + public String toApiFilename(String name) { + return toApiName(name); + } + + public String toApiVarName(String name) { + return snakeCase(name); + } + + public String toModelFilename(String name) { + return initialCaps(name); + } + + public String toOperationId(String operationId) { + return operationId; + } + + public String toVarName(String name) { + if (reservedWords.contains(name)) { + return escapeReservedWord(name); } else { - final CodegenProperty cp = fromProperty(key, prop); - cp.required = mandatory.contains(key) ? true : null; - if (cp.isEnum) { - m.hasEnums = true; - } - count += 1; - if (count != totalCount) - cp.hasMore = true; - if (cp.isContainer != null) { - addImport(m, typeMapping.get("array")); - } - addImport(m, cp.baseType); - addImport(m, cp.complexType); - m.vars.add(cp); + return name; } - } - } else { - m.emptyVars = true; } - } + + public String toParamName(String name) { + name = removeNonNameElementToCamelCase(name); + if (reservedWords.contains(name)) { + return escapeReservedWord(name); + } + return name; + } + + public String toEnumName(CodegenProperty property) { + return StringUtils.capitalize(property.name) + "Enum"; + } + + public String escapeReservedWord(String name) { + throw new RuntimeException("reserved word " + name + " not allowed"); + } + + public String toModelImport(String name) { + if ("".equals(modelPackage())) { + return name; + } else { + return modelPackage() + "." + name; + } + } + + public String toApiImport(String name) { + return apiPackage() + "." + name; + } + + public DefaultCodegen() { + defaultIncludes = new HashSet( + Arrays.asList("double", + "int", + "long", + "short", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Void", + "Integer", + "Long", + "Float") + ); + + typeMapping = new HashMap(); + typeMapping.put("array", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("List", "List"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Integer"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("long", "Long"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "String"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Object"); + typeMapping.put("integer", "Integer"); + + instantiationTypes = new HashMap(); + + reservedWords = new HashSet(); + + importMapping = new HashMap(); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("Array", "java.util.List"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("List", "java.util.*"); + importMapping.put("Set", "java.util.*"); + importMapping.put("DateTime", "org.joda.time.*"); + importMapping.put("LocalDateTime", "org.joda.time.*"); + importMapping.put("LocalDate", "org.joda.time.*"); + importMapping.put("LocalTime", "org.joda.time.*"); + + cliOptions.add(new CliOption("modelPackage", "package for generated models")); + cliOptions.add(new CliOption("apiPackage", "package for generated api classes")); + } + + + public String generateExamplePath(String path, Operation operation) { + StringBuilder sb = new StringBuilder(); + sb.append(path); + + if (operation.getParameters() != null) { + int count = 0; + + for (Parameter param : operation.getParameters()) { + if (param instanceof QueryParameter) { + StringBuilder paramPart = new StringBuilder(); + QueryParameter qp = (QueryParameter) param; + + if (count == 0) { + paramPart.append("?"); + } else { + paramPart.append(","); + } + count += 1; + if (!param.getRequired()) { + paramPart.append("["); + } + paramPart.append(param.getName()).append("="); + paramPart.append("{"); + if (qp.getCollectionFormat() != null) { + paramPart.append(param.getName() + "1"); + if ("csv".equals(qp.getCollectionFormat())) { + paramPart.append(","); + } else if ("pipes".equals(qp.getCollectionFormat())) { + paramPart.append("|"); + } else if ("tsv".equals(qp.getCollectionFormat())) { + paramPart.append("\t"); + } else if ("multi".equals(qp.getCollectionFormat())) { + paramPart.append("&").append(param.getName()).append("="); + paramPart.append(param.getName() + "2"); + } + } else { + paramPart.append(param.getName()); + } + paramPart.append("}"); + if (!param.getRequired()) { + paramPart.append("]"); + } + sb.append(paramPart.toString()); + } + } + } + + return sb.toString(); + } + + 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) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "<" + inner + ">"; + } else { + return null; + } + } + + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap() "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ArrayList<" + inner + ">() "; + } else { + return "null"; + } + } + + /** + * returns the swagger type for the property + **/ + public String getSwaggerType(Property p) { + String datatype = null; + if (p instanceof StringProperty) { + datatype = "string"; + } else if (p instanceof BooleanProperty) { + datatype = "boolean"; + } else if (p instanceof DateProperty) { + datatype = "date"; + } else if (p instanceof DateTimeProperty) { + datatype = "DateTime"; + } else if (p instanceof DoubleProperty) { + datatype = "double"; + } else if (p instanceof FloatProperty) { + datatype = "float"; + } else if (p instanceof IntegerProperty) { + datatype = "integer"; + } else if (p instanceof LongProperty) { + datatype = "long"; + } else if (p instanceof MapProperty) { + datatype = "map"; + } else if (p instanceof DecimalProperty) { + datatype = "number"; + } else if (p instanceof RefProperty) { + RefProperty r = (RefProperty) p; + datatype = r.get$ref(); + if (datatype.indexOf("#/definitions/") == 0) { + datatype = datatype.substring("#/definitions/".length()); + } + } else { + if (p != null) { + datatype = p.getType(); + } + } + return datatype; + } + + public String snakeCase(String name) { + return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; + } + + public String initialCaps(String name) { + return StringUtils.capitalize(name); + } + + public String getTypeDeclaration(String name) { + return name; + } + + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + return swaggerType; + } + + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return initialCaps(name) + "Api"; + } + + public String toModelName(String name) { + return initialCaps(name); + } + + public CodegenModel fromModel(String name, Model model) { + CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + if (reservedWords.contains(name)) { + m.name = escapeReservedWord(name); + } else { + m.name = name; + } + m.description = escapeText(model.getDescription()); + m.classname = toModelName(name); + m.classVarName = toVarName(name); + m.modelJson = Json.pretty(model); + m.externalDocs = model.getExternalDocs(); + if (model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); + addParentContainer(m, name, arrayProperty); + } else if (model instanceof RefModel) { + // TODO + } else if (model instanceof ComposedModel) { + final ComposedModel composed = (ComposedModel) model; + final RefModel parent = (RefModel) composed.getParent(); + final String parentModel = toModelName(parent.getSimpleRef()); + m.parent = parentModel; + addImport(m, parentModel); + final ModelImpl child = (ModelImpl) composed.getChild(); + addVars(m, child.getProperties(), child.getRequired()); + } else { + ModelImpl impl = (ModelImpl) model; + if (impl.getAdditionalProperties() != null) { + MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); + addParentContainer(m, name, mapProperty); + } + addVars(m, impl.getProperties(), impl.getRequired()); + } + return m; + } + + public String getterAndSetterCapitalize(String name) { + if (name == null || name.length() == 0) { + return name; + } + + return camelize(toVarName(name)); + + } + + public CodegenProperty fromProperty(String name, Property p) { + if (p == null) { + LOGGER.error("unexpected missing property for name " + null); + return null; + } + CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); + + property.name = toVarName(name); + property.baseName = name; + property.description = escapeText(p.getDescription()); + property.getter = "get" + getterAndSetterCapitalize(name); + property.setter = "set" + getterAndSetterCapitalize(name); + property.example = p.getExample(); + property.defaultValue = toDefaultValue(p); + property.jsonSchema = Json.pretty(p); + + String type = getSwaggerType(p); + if (p instanceof AbstractNumericProperty) { + AbstractNumericProperty np = (AbstractNumericProperty) p; + property.minimum = np.getMinimum(); + property.maximum = np.getMaximum(); + property.exclusiveMinimum = np.getExclusiveMinimum(); + property.exclusiveMaximum = np.getExclusiveMaximum(); + + // legacy support + Map allowableValues = new HashMap(); + if (np.getMinimum() != null) { + allowableValues.put("min", np.getMinimum()); + } + if (np.getMaximum() != null) { + allowableValues.put("max", np.getMaximum()); + } + property.allowableValues = allowableValues; + } + + if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + property.maxLength = sp.getMaxLength(); + property.minLength = sp.getMinLength(); + property.pattern = sp.getPattern(); + if (sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = _enum; + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + + property.datatype = getTypeDeclaration(p); + + // this can cause issues for clients which don't support enums + if (property.isEnum) { + property.datatypeWithEnum = toEnumName(property); + } else { + property.datatypeWithEnum = property.datatype; + } + + property.baseType = getSwaggerType(p); + + if (p instanceof ArrayProperty) { + property.isContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty("inner", ap.getItems()); + if (cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } else { + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + } + } else if (p instanceof MapProperty) { + property.isContainer = true; + property.containerType = "map"; + MapProperty ap = (MapProperty) p; + CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); + + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + } else { + setNonArrayMapProperty(property, type); + } + return property; + } + + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + property.isNotContainer = true; + if (languageSpecificPrimitives().contains(type)) { + property.isPrimitiveType = true; + } else { + property.complexType = property.baseType; + } + } + + private Response findMethodResponse(Map responses) { + + String code = null; + for (String responseCode : responses.keySet()) { + if (responseCode.startsWith("2") || responseCode.equals("default")) { + if (code == null || code.compareTo(responseCode) > 0) { + code = responseCode; + } + } + } + if (code == null) { + return null; + } + return responses.get(code); + } + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); + Set imports = new HashSet(); + + String operationId = operation.getOperationId(); + if (operationId == null) { + String tmpPath = path; + tmpPath = tmpPath.replaceAll("\\{", ""); + tmpPath = tmpPath.replaceAll("\\}", ""); + String[] parts = (tmpPath + "/" + httpMethod).split("/"); + StringBuilder builder = new StringBuilder(); + if ("/".equals(tmpPath)) { + // must be root tmpPath + builder.append("root"); + } + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + if (part.length() > 0) { + if (builder.toString().length() == 0) { + part = Character.toLowerCase(part.charAt(0)) + part.substring(1); + } else { + part = initialCaps(part); + } + builder.append(part); + } + } + operationId = builder.toString(); + LOGGER.warn("generated operationId " + operationId); + } + operationId = removeNonNameElementToCamelCase(operationId); + op.path = path; + op.operationId = toOperationId(operationId); + op.summary = escapeText(operation.getSummary()); + op.notes = escapeText(operation.getDescription()); + op.tags = operation.getTags(); + + if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for (String key : operation.getConsumes()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getConsumes().size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + op.consumes = c; + op.hasConsumes = true; + } + + if (operation.getProduces() != null && operation.getProduces().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for (String key : operation.getProduces()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getProduces().size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + op.produces = c; + op.hasProduces = true; + } + + if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { + Response methodResponse = findMethodResponse(operation.getResponses()); + + for (Map.Entry entry : operation.getResponses().entrySet()) { + Response response = entry.getValue(); + CodegenResponse r = fromResponse(entry.getKey(), response); + r.hasMore = true; + if (r.baseType != null && + !defaultIncludes.contains(r.baseType) && + !languageSpecificPrimitives.contains(r.baseType)) { + imports.add(r.baseType); + } + r.isDefault = response == methodResponse; + op.responses.add(r); + } + op.responses.get(op.responses.size() - 1).hasMore = false; + + if (methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + + Property responseProperty = methodResponse.getSchema(); + + if (responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + op.returnBaseType = innerProperty.baseType; + } else { + if (cm.complexType != null) { + op.returnBaseType = cm.complexType; + } else { + op.returnBaseType = cm.baseType; + } + } + op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); + op.defaultResponse = toDefaultValue(responseProperty); + op.returnType = cm.datatype; + if (cm.isContainer != null) { + op.returnContainer = cm.containerType; + if ("map".equals(cm.containerType)) { + op.isMapContainer = Boolean.TRUE; + } else if ("list".equalsIgnoreCase(cm.containerType)) { + op.isListContainer = Boolean.TRUE; + } else if ("array".equalsIgnoreCase(cm.containerType)) { + op.isListContainer = Boolean.TRUE; + } + } else { + op.returnSimpleType = true; + } + if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) { + op.returnTypeIsPrimitive = true; + } + } + addHeaders(methodResponse, op.responseHeaders); + } + } + + List parameters = operation.getParameters(); + CodegenParameter bodyParam = null; + List allParams = new ArrayList(); + List bodyParams = new ArrayList(); + List pathParams = new ArrayList(); + List queryParams = new ArrayList(); + List headerParams = new ArrayList(); + List cookieParams = new ArrayList(); + List formParams = new ArrayList(); + + if (parameters != null) { + for (Parameter param : parameters) { + CodegenParameter p = fromParameter(param, imports); + allParams.add(p); + if (param instanceof QueryParameter) { + p.isQueryParam = new Boolean(true); + queryParams.add(p.copy()); + } else if (param instanceof PathParameter) { + p.required = true; + p.isPathParam = new Boolean(true); + pathParams.add(p.copy()); + } else if (param instanceof HeaderParameter) { + p.isHeaderParam = new Boolean(true); + headerParams.add(p.copy()); + } else if (param instanceof CookieParameter) { + p.isCookieParam = new Boolean(true); + cookieParams.add(p.copy()); + } else if (param instanceof BodyParameter) { + p.isBodyParam = new Boolean(true); + bodyParam = p; + bodyParams.add(p.copy()); + } else if (param instanceof FormParameter) { + if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { + p.isFile = true; + } else { + p.notFile = true; + } + p.isFormParam = new Boolean(true); + formParams.add(p.copy()); + } + } + } + for (String i : imports) { + if (!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)) { + op.imports.add(i); + } + } + op.bodyParam = bodyParam; + op.httpMethod = httpMethod.toUpperCase(); + op.allParams = addHasMore(allParams); + op.bodyParams = addHasMore(bodyParams); + op.pathParams = addHasMore(pathParams); + op.queryParams = addHasMore(queryParams); + op.headerParams = addHasMore(headerParams); + // op.cookieParams = cookieParams; + op.formParams = addHasMore(formParams); + // legacy support + op.nickname = op.operationId; + + + if (op.allParams.size() > 0) { + op.hasParams = true; + } + op.externalDocs = operation.getExternalDocs(); + + return op; + } + + + + + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); + Set imports = new HashSet(); + + String operationId = operation.getOperationId(); + if (operationId == null) { + String tmpPath = path; + tmpPath = tmpPath.replaceAll("\\{", ""); + tmpPath = tmpPath.replaceAll("\\}", ""); + String[] parts = (tmpPath + "/" + httpMethod).split("/"); + StringBuilder builder = new StringBuilder(); + if ("/".equals(tmpPath)) { + // must be root tmpPath + builder.append("root"); + } + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + if (part.length() > 0) { + if (builder.toString().length() == 0) { + part = Character.toLowerCase(part.charAt(0)) + part.substring(1); + } else { + part = initialCaps(part); + } + builder.append(part); + } + } + operationId = builder.toString(); + LOGGER.warn("generated operationId " + operationId); + } + operationId = removeNonNameElementToCamelCase(operationId); + op.path = path; + op.operationId = toOperationId(operationId); + op.summary = escapeText(operation.getSummary()); + op.notes = escapeText(operation.getDescription()); + op.tags = operation.getTags(); + + if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for (String key : operation.getConsumes()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getConsumes().size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + op.consumes = c; + op.hasConsumes = true; + } + + if (operation.getProduces() != null && operation.getProduces().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for (String key : operation.getProduces()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getProduces().size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + op.produces = c; + op.hasProduces = true; + } + + if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { + Response methodResponse = findMethodResponse(operation.getResponses()); + + for (Map.Entry entry : operation.getResponses().entrySet()) { + Response response = entry.getValue(); + CodegenResponse r = fromResponse(entry.getKey(), response); + r.hasMore = true; + if (r.baseType != null && + !defaultIncludes.contains(r.baseType) && + !languageSpecificPrimitives.contains(r.baseType)) { + imports.add(r.baseType); + } + r.isDefault = response == methodResponse; + op.responses.add(r); + } + op.responses.get(op.responses.size() - 1).hasMore = false; + + if (methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + + Property responseProperty = methodResponse.getSchema(); + + if (responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + op.returnBaseType = innerProperty.baseType; + } else { + if (cm.complexType != null) { + op.returnBaseType = cm.complexType; + } else { + op.returnBaseType = cm.baseType; + } + } + op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); + op.defaultResponse = toDefaultValue(responseProperty); + op.returnType = cm.datatype; + if (cm.isContainer != null) { + op.returnContainer = cm.containerType; + if ("map".equals(cm.containerType)) { + op.isMapContainer = Boolean.TRUE; + } else if ("list".equalsIgnoreCase(cm.containerType)) { + op.isListContainer = Boolean.TRUE; + } else if ("array".equalsIgnoreCase(cm.containerType)) { + op.isListContainer = Boolean.TRUE; + } + } else { + op.returnSimpleType = true; + } + if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) { + op.returnTypeIsPrimitive = true; + } + } + addHeaders(methodResponse, op.responseHeaders); + } + } + + List parameters = operation.getParameters(); + CodegenParameter bodyParam = null; + List allParams = new ArrayList(); + List bodyParams = new ArrayList(); + List pathParams = new ArrayList(); + List queryParams = new ArrayList(); + List headerParams = new ArrayList(); + List cookieParams = new ArrayList(); + List formParams = new ArrayList(); + + if (parameters != null) { + for (Parameter param : parameters) { + CodegenParameter p = fromParameter(param, imports); + allParams.add(p); + if (param instanceof QueryParameter) { + p.isQueryParam = new Boolean(true); + queryParams.add(p.copy()); + } else if (param instanceof PathParameter) { + p.required = true; + p.isPathParam = new Boolean(true); + pathParams.add(p.copy()); + } else if (param instanceof HeaderParameter) { + p.isHeaderParam = new Boolean(true); + headerParams.add(p.copy()); + } else if (param instanceof CookieParameter) { + p.isCookieParam = new Boolean(true); + cookieParams.add(p.copy()); + } else if (param instanceof BodyParameter) { + p.isBodyParam = new Boolean(true); + bodyParam = p; + bodyParams.add(p.copy()); + } else if (param instanceof FormParameter) { + if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { + p.isFile = true; + } else { + p.notFile = true; + } + p.isFormParam = new Boolean(true); + formParams.add(p.copy()); + } + } + } + for (String i : imports) { + if (!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)) { + op.imports.add(i); + } + } + op.bodyParam = bodyParam; + op.httpMethod = httpMethod.toUpperCase(); + op.allParams = addHasMore(allParams); + op.bodyParams = addHasMore(bodyParams); + op.pathParams = addHasMore(pathParams); + op.queryParams = addHasMore(queryParams); + op.headerParams = addHasMore(headerParams); + // op.cookieParams = cookieParams; + op.formParams = addHasMore(formParams); + // legacy support + op.nickname = op.operationId; + + + if (op.allParams.size() > 0) { + op.hasParams = true; + } + op.externalDocs = operation.getExternalDocs(); + + return op; + } + + public CodegenResponse fromResponse(String responseCode, Response response) { + CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); + if ("default".equals(responseCode)) { + r.code = "0"; + } else { + r.code = responseCode; + } + r.message = response.getDescription(); + r.schema = response.getSchema(); + r.examples = toExamples(response.getExamples()); + r.jsonSchema = Json.pretty(response); + addHeaders(response, r.headers); + + if (r.schema != null) { + Property responseProperty = response.getSchema(); + responseProperty.setRequired(true); + CodegenProperty cm = fromProperty("response", responseProperty); + + if (responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + r.baseType = innerProperty.baseType; + } else { + if (cm.complexType != null) { + r.baseType = cm.complexType; + } else { + r.baseType = cm.baseType; + } + } + r.dataType = cm.datatype; + if (cm.isContainer != null) { + r.simpleType = false; + r.containerType = cm.containerType; + r.isMapContainer = "map".equals(cm.containerType); + r.isListContainer = "list".equals(cm.containerType); + } else { + r.simpleType = true; + } + r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); + } + if (r.baseType == null) { + r.isMapContainer = false; + r.isListContainer = false; + r.primitiveType = true; + r.simpleType = true; + } + return r; + } + + public CodegenParameter fromParameter(Parameter param, Set imports) { + CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + p.baseName = param.getName(); + p.description = escapeText(param.getDescription()); + if (param.getRequired()) { + p.required = param.getRequired(); + } + p.jsonSchema = Json.pretty(param); + + // move the defaultValue for headers, forms and params + if (param instanceof QueryParameter) { + p.defaultValue = ((QueryParameter) param).getDefaultValue(); + } else if (param instanceof HeaderParameter) { + p.defaultValue = ((HeaderParameter) param).getDefaultValue(); + } else if (param instanceof FormParameter) { + p.defaultValue = ((FormParameter) param).getDefaultValue(); + } + + if (param instanceof SerializableParameter) { + SerializableParameter qp = (SerializableParameter) param; + Property property = null; + String collectionFormat = null; + if ("array".equals(qp.getType())) { + Property inner = qp.getItems(); + if (inner == null) { + LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); + inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + } + property = new ArrayProperty(inner); + collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("inner", inner); + p.baseType = pr.datatype; + p.isContainer = true; + imports.add(pr.baseType); + } else if ("object".equals(qp.getType())) { + Property inner = qp.getItems(); + if (inner == null) { + LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); + inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + } + property = new MapProperty(inner); + collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("inner", inner); + p.baseType = pr.datatype; + imports.add(pr.baseType); + } else { + property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null); + } + if (property == null) { + LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); + property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); + } + property.setRequired(param.getRequired()); + CodegenProperty model = fromProperty(qp.getName(), property); + p.collectionFormat = collectionFormat; + p.dataType = model.datatype; + p.paramName = toParamName(qp.getName()); + + if (model.complexType != null) { + imports.add(model.complexType); + } + } else { + BodyParameter bp = (BodyParameter) param; + Model model = bp.getSchema(); + + if (model instanceof ModelImpl) { + ModelImpl impl = (ModelImpl) model; + CodegenModel cm = fromModel(bp.getName(), impl); + if (cm.emptyVars != null && cm.emptyVars == false) { + p.dataType = getTypeDeclaration(cm.classname); + imports.add(p.dataType); + } else { + // TODO: missing format, so this will not always work + Property prop = PropertyBuilder.build(impl.getType(), null, null); + prop.setRequired(bp.getRequired()); + CodegenProperty cp = fromProperty("property", prop); + if (cp != null) { + p.dataType = cp.datatype; + } + } + } else if (model instanceof ArrayModel) { + // to use the built-in model parsing, we unwrap the ArrayModel + // and get a single property from it + ArrayModel impl = (ArrayModel) model; + CodegenModel cm = fromModel(bp.getName(), impl); + // get the single property + ArrayProperty ap = new ArrayProperty().items(impl.getItems()); + ap.setRequired(param.getRequired()); + CodegenProperty cp = fromProperty("inner", ap); + if (cp.complexType != null) { + imports.add(cp.complexType); + } + imports.add(cp.baseType); + p.dataType = cp.datatype; + p.isContainer = true; + } else { + Model sub = bp.getSchema(); + if (sub instanceof RefModel) { + String name = ((RefModel) sub).getSimpleRef(); + if (typeMapping.containsKey(name)) { + name = typeMapping.get(name); + } else { + name = toModelName(name); + if (defaultIncludes.contains(name)) { + imports.add(name); + } + imports.add(name); + name = getTypeDeclaration(name); + } + p.dataType = name; + } + } + p.paramName = toParamName(bp.getName()); + } + return p; + } + + public List fromSecurity(Map schemes) { + if (schemes == null) { + return null; + } + + List secs = new ArrayList(schemes.size()); + for (Iterator> it = schemes.entrySet().iterator(); it.hasNext(); ) { + final Map.Entry entry = it.next(); + final SecuritySchemeDefinition schemeDefinition = entry.getValue(); + + CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); + sec.name = entry.getKey(); + sec.type = schemeDefinition.getType(); + + if (schemeDefinition instanceof ApiKeyAuthDefinition) { + final ApiKeyAuthDefinition apiKeyDefinition = (ApiKeyAuthDefinition) schemeDefinition; + sec.isBasic = sec.isOAuth = false; + sec.isApiKey = true; + sec.keyParamName = apiKeyDefinition.getName(); + sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; + sec.isKeyInQuery = !sec.isKeyInHeader; + } else { + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = false; + sec.isBasic = schemeDefinition instanceof BasicAuthDefinition; + sec.isOAuth = !sec.isBasic; + } + + sec.hasMore = it.hasNext(); + secs.add(sec); + } + return secs; + } + + protected List> toExamples(Map examples) { + if (examples == null) { + return null; + } + + final List> output = new ArrayList>(examples.size()); + for (Map.Entry entry : examples.entrySet()) { + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", entry.getValue()); + output.add(kv); + } + return output; + } + + private void addHeaders(Response response, List target) { + if (response.getHeaders() != null) { + for (Map.Entry headers : response.getHeaders().entrySet()) { + target.add(fromProperty(headers.getKey(), headers.getValue())); + } + } + } + + private List addHasMore(List objs) { + if (objs != null) { + for (int i = 0; i < objs.size(); i++) { + if (i > 0) { + objs.get(i).secondaryParam = new Boolean(true); + } + if (i < objs.size() - 1) { + objs.get(i).hasMore = new Boolean(true); + } + } + } + return objs; + } + + private Map addHasMore(Map objs) { + if (objs != null) { + for (int i = 0; i < objs.size() - 1; i++) { + if (i > 0) { + objs.put("secondaryParam", new Boolean(true)); + } + if (i < objs.size() - 1) { + objs.put("hasMore", true); + } + } + } + return objs; + } + + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + List opList = operations.get(tag); + if (opList == null) { + opList = new ArrayList(); + operations.put(tag, opList); + } + opList.add(co); + co.baseName = tag; + } /* underscore and camelize are copied from Twitter elephant bird * https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/util/Strings.java */ - /** - * Underscore the given word. - * @param word The word - * @return The underscored version of the word - */ - public static String underscore(String word) { - String firstPattern = "([A-Z]+)([A-Z][a-z])"; - String secondPattern = "([a-z\\d])([A-Z])"; - String replacementPattern = "$1_$2"; - // Replace package separator with slash. - word = word.replaceAll("\\.", "/"); - // Replace $ with two underscores for inner classes. - word = word.replaceAll("\\$", "__"); - // Replace capital letter with _ plus lowercase letter. - word = word.replaceAll(firstPattern, replacementPattern); - word = word.replaceAll(secondPattern, replacementPattern); - word = word.replace('-', '_'); - word = word.toLowerCase(); - return word; - } - - /** - * Remove characters not suitable for variable or method name from the input and camelize it - * @param name - * @return - */ - public String removeNonNameElementToCamelCase(String name) { - String nonNameElementPattern = "[-_:;#]"; - name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function() { - @Nullable - @Override - public String apply(String input) { - return StringUtils.capitalize(input); - } - }), ""); - if (name.length() > 0) { - name = name.substring(0, 1).toLowerCase() + name.substring(1); - } - return name; - } - - public static String camelize(String word) { - return camelize(word, false); - } - - public static String camelize(String word, boolean lowercaseFirstLetter) { - // Replace all slashes with dots (package separator) - Pattern p = Pattern.compile("\\/(.?)"); - Matcher m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); - m = p.matcher(word); + private void addParentContainer(CodegenModel m, String name, Property property) { + final CodegenProperty tmp = fromProperty(name, property); + addImport(m, tmp.complexType); + m.parent = toInstantiationType(property); + final String containerType = tmp.containerType; + final String instantiationType = instantiationTypes.get(containerType); + if (instantiationType != null) { + addImport(m, instantiationType); + } + final String mappedType = typeMapping.get(containerType); + if (mappedType != null) { + addImport(m, mappedType); + } + } /** + * Underscore the given word. + * + * @param word The word + * @return The underscored version of the word + */ + public static String underscore(String word) { + String firstPattern = "([A-Z]+)([A-Z][a-z])"; + String secondPattern = "([a-z\\d])([A-Z])"; + String replacementPattern = "$1_$2"; + // Replace package separator with slash. + word = word.replaceAll("\\.", "/"); + // Replace $ with two underscores for inner classes. + word = word.replaceAll("\\$", "__"); + // Replace capital letter with _ plus lowercase letter. + word = word.replaceAll(firstPattern, replacementPattern); + word = word.replaceAll(secondPattern, replacementPattern); + word = word.replace('-', '_'); + word = word.toLowerCase(); + return word; } - // case out dots - String[] parts = word.split("\\."); - StringBuilder f = new StringBuilder(); - for(String z : parts) { - if(z.length() > 0) - f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1)); - } - word = f.toString(); - - m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/); - m = p.matcher(word); + private void addImport(CodegenModel m, String type) { + if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { + m.imports.add(type); + } } - // Uppercase the class name. - p = Pattern.compile("(\\.?)(\\w)([^\\.]*)$"); - m = p.matcher(word); - if (m.find()) { - String rep = m.group(1) + m.group(2).toUpperCase() + m.group(3); - rep = rep.replaceAll("\\$", "\\\\\\$"); - word = m.replaceAll(rep); + private void addVars(CodegenModel m, Map properties, Collection required) { + if (properties != null && properties.size() > 0) { + m.hasVars = true; + m.hasEnums = false; + final int totalCount = properties.size(); + final Set mandatory = required == null ? Collections.emptySet() : new HashSet(required); + int count = 0; + for (Map.Entry entry : properties.entrySet()) { + final String key = entry.getKey(); + final Property prop = entry.getValue(); + + if (prop == null) { + LOGGER.warn("null property for " + key); + } else { + final CodegenProperty cp = fromProperty(key, prop); + cp.required = mandatory.contains(key) ? true : null; + if (cp.isEnum) { + m.hasEnums = true; + } + count += 1; + if (count != totalCount) { + cp.hasMore = true; + } + if (cp.isContainer != null) { + addImport(m, typeMapping.get("array")); + } + addImport(m, cp.baseType); + addImport(m, cp.complexType); + m.vars.add(cp); + } + } + } else { + m.emptyVars = true; + } + } public static String camelize(String word) { + return camelize(word, false); } - // Replace two underscores with $ to support inner classes. - p = Pattern.compile("(__)(.)"); - m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst("\\$" + m.group(2).toUpperCase()); - m = p.matcher(word); + /** + * Remove characters not suitable for variable or method name from the input and camelize it + * + * @param name + * @return + */ + public String removeNonNameElementToCamelCase(String name) { + String nonNameElementPattern = "[-_:;#]"; + name = StringUtils.join(Lists.transform(Lists.newArrayList(name.split(nonNameElementPattern)), new Function() { + @Nullable + @Override + public String apply(String input) { + return StringUtils.capitalize(input); + } + }), ""); + if (name.length() > 0) { + name = name.substring(0, 1).toLowerCase() + name.substring(1); + } + return name; + } public static String camelize(String word, boolean lowercaseFirstLetter) { + // Replace all slashes with dots (package separator) + Pattern p = Pattern.compile("\\/(.?)"); + Matcher m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst("." + m.group(1)/*.toUpperCase()*/); + m = p.matcher(word); + } + + // case out dots + String[] parts = word.split("\\."); + StringBuilder f = new StringBuilder(); + for (String z : parts) { + if (z.length() > 0) { + f.append(Character.toUpperCase(z.charAt(0))).append(z.substring(1)); + } + } + word = f.toString(); + + m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst("" + Character.toUpperCase(m.group(1).charAt(0)) + m.group(1).substring(1)/*.toUpperCase()*/); + m = p.matcher(word); + } + + // Uppercase the class name. + p = Pattern.compile("(\\.?)(\\w)([^\\.]*)$"); + m = p.matcher(word); + if (m.find()) { + String rep = m.group(1) + m.group(2).toUpperCase() + m.group(3); + rep = rep.replaceAll("\\$", "\\\\\\$"); + word = m.replaceAll(rep); + } + + // Replace two underscores with $ to support inner classes. + p = Pattern.compile("(__)(.)"); + m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst("\\$" + m.group(2).toUpperCase()); + m = p.matcher(word); + } + + // Remove all underscores + p = Pattern.compile("(_)(.)"); + m = p.matcher(word); + while (m.find()) { + word = m.replaceFirst(m.group(2).toUpperCase()); + m = p.matcher(word); + } + + if (lowercaseFirstLetter) { + word = word.substring(0, 1).toLowerCase() + word.substring(1); + } + + return word; } - // Remove all underscores - p = Pattern.compile("(_)(.)"); - m = p.matcher(word); - while (m.find()) { - word = m.replaceFirst(m.group(2).toUpperCase()); - m = p.matcher(word); + public String apiFilename(String templateName, String tag) { + String suffix = apiTemplateFiles().get(templateName); + return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; } - if (lowercaseFirstLetter) { - word = word.substring(0, 1).toLowerCase() + word.substring(1); + public boolean shouldOverwrite(String filename) { + return true; } - - return word; - } - - - public String apiFilename(String templateName, String tag) - { - String suffix = apiTemplateFiles().get(templateName); - return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; - } - - public boolean shouldOverwrite( String filename ){ - return true; - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 1f9da14119d..a04e517bee5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -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; @@ -35,453 +32,453 @@ import static org.apache.commons.lang3.StringUtils.capitalize; import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class DefaultGenerator extends AbstractGenerator implements Generator { - protected CodegenConfig config; - protected ClientOptInput opts = null; - protected Swagger swagger = null; + protected CodegenConfig config; + protected ClientOptInput opts = null; + protected Swagger swagger = null; - public Generator opts(ClientOptInput opts) { - this.opts = opts; + public Generator opts(ClientOptInput opts) { + this.opts = opts; - this.swagger = opts.getSwagger(); - this.config = opts.getConfig(); - this.config.additionalProperties().putAll(opts.getOpts().getProperties()); + this.swagger = opts.getSwagger(); + this.config = opts.getConfig(); + this.config.additionalProperties().putAll(opts.getOpts().getProperties()); - return this; - } - - public List generate() { - if (swagger == null || config == null) { - throw new RuntimeException("missing swagger input or config!"); + return this; } - if (System.getProperty("debugSwagger") != null) { - Json.prettyPrint(swagger); - } - List files = new ArrayList(); - try { - config.processOpts(); - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); - if (info.getTitle() != null) { - config.additionalProperties().put("appName", info.getTitle()); + + public List generate() { + if (swagger == null || config == null) { + throw new RuntimeException("missing swagger input or config!"); } - if (info.getVersion() != null) { - config.additionalProperties().put("appVersion", info.getVersion()); + if (System.getProperty("debugSwagger") != null) { + Json.prettyPrint(swagger); } - if (info.getDescription() != null) { - config.additionalProperties().put("appDescription", - config.escapeText(info.getDescription())); - } - if (info.getContact() != null) { - Contact contact = info.getContact(); - config.additionalProperties().put("infoUrl", contact.getUrl()); - if (contact.getEmail() != null) { - config.additionalProperties().put("infoEmail", contact.getEmail()); - } - } - if (info.getLicense() != null) { - License license = info.getLicense(); - if (license.getName() != null) { - config.additionalProperties().put("licenseInfo", license.getName()); - } - if (license.getUrl() != null) { - config.additionalProperties().put("licenseUrl", license.getUrl()); - } - } - if (info.getVersion() != null) { - config.additionalProperties().put("version", info.getVersion()); - } - } - - StringBuilder hostBuilder = new StringBuilder(); - String scheme; - if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { - scheme = swagger.getSchemes().get(0).toValue(); - } else { - scheme = "https"; - } - hostBuilder.append(scheme); - hostBuilder.append("://"); - if (swagger.getHost() != null) { - hostBuilder.append(swagger.getHost()); - } else { - hostBuilder.append("localhost"); - } - if (swagger.getBasePath() != null) { - hostBuilder.append(swagger.getBasePath()); - } else { - hostBuilder.append("/"); - } - String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath(); - String basePath = hostBuilder.toString(); - - - List allOperations = new ArrayList(); - List allModels = new ArrayList(); - - // models - Map definitions = swagger.getDefinitions(); - if (definitions != null) { - for (String name : definitions.keySet()) { - Model model = definitions.get(name); - Map modelMap = new HashMap(); - modelMap.put(name, model); - Map models = processModels(config, modelMap); - models.putAll(config.additionalProperties()); - - allModels.add(((List) models.get("models")).get(0)); - - for (String templateName : config.modelTemplateFiles().keySet()) { - String suffix = config.modelTemplateFiles().get(templateName); - String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; - String template = readTemplate(config.templateDir() + File.separator + templateName); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); - } - }) - .defaultValue("") - .compile(template); - writeToFile(filename, tmpl.execute(models)); - files.add(new File(filename)); - } - } - } - if (System.getProperty("debugModels") != null) { - System.out.println("############ Model info ############"); - Json.prettyPrint(allModels); - } - - // apis - Map> paths = processPaths(swagger.getPaths()); - for (String tag : paths.keySet()) { - List ops = paths.get(tag); - Map operation = processOperations(config, tag, ops); - - operation.put("basePath", basePath); - operation.put("contextPath", contextPath); - operation.put("baseName", tag); - operation.put("modelPackage", config.modelPackage()); - operation.putAll(config.additionalProperties()); - operation.put("classname", config.toApiName(tag)); - operation.put("classVarName", config.toApiVarName(tag)); - operation.put("importPath", config.toApiImport(tag)); - - processMimeTypes(swagger.getConsumes(), operation, "consumes"); - processMimeTypes(swagger.getProduces(), operation, "produces"); - - allOperations.add(new HashMap(operation)); - for (int i = 0; i < allOperations.size(); i++) { - Map oo = (Map) allOperations.get(i); - if (i < (allOperations.size() - 1)) { - oo.put("hasMore", "true"); - } - } - - for (String templateName : config.apiTemplateFiles().keySet()) { - - String filename = config.apiFilename( templateName, tag ); - if( new File( filename ).exists() && !config.shouldOverwrite( filename )){ - continue; - } - - String template = readTemplate(config.templateDir() + File.separator + templateName); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + List files = new ArrayList(); + try { + config.processOpts(); + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (info.getTitle() != null) { + config.additionalProperties().put("appName", info.getTitle()); + } + if (info.getVersion() != null) { + config.additionalProperties().put("appVersion", info.getVersion()); + } + if (info.getDescription() != null) { + config.additionalProperties().put("appDescription", + config.escapeText(info.getDescription())); + } + if (info.getContact() != null) { + Contact contact = info.getContact(); + config.additionalProperties().put("infoUrl", contact.getUrl()); + if (contact.getEmail() != null) { + config.additionalProperties().put("infoEmail", contact.getEmail()); } - }) - .defaultValue("") - .compile(template); - - writeToFile(filename, tmpl.execute(operation)); - files.add(new File(filename)); - } - } - if (System.getProperty("debugOperations") != null) { - System.out.println("############ Operation info ############"); - Json.prettyPrint(allOperations); - } - - // supporting files - Map bundle = new HashMap(); - bundle.putAll(config.additionalProperties()); - bundle.put("apiPackage", config.apiPackage()); - - Map apis = new HashMap(); - apis.put("apis", allOperations); - if (swagger.getHost() != null) { - bundle.put("host", swagger.getHost()); - } - bundle.put("basePath", basePath); - bundle.put("scheme", scheme); - bundle.put("contextPath", contextPath); - bundle.put("apiInfo", apis); - bundle.put("models", allModels); - bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); - bundle.put("modelPackage", config.modelPackage()); - bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions())); - if (swagger.getExternalDocs() != null) { - bundle.put("externalDocs", swagger.getExternalDocs()); - } - for (int i = 0; i < allModels.size() - 1; i++) { - HashMap cm = (HashMap) allModels.get(i); - CodegenModel m = cm.get("model"); - m.hasMoreModels = true; - } - - config.postProcessSupportingFileData(bundle); - - if (System.getProperty("debugSupportingFiles") != null) { - System.out.println("############ Supporting file info ############"); - Json.prettyPrint(bundle); - } - - for (SupportingFile support : config.supportingFiles()) { - String outputFolder = config.outputFolder(); - if (isNotEmpty(support.folder)) { - outputFolder += File.separator + support.folder; - } - File of = new File(outputFolder); - if (!of.isDirectory()) { - of.mkdirs(); - } - String outputFilename = outputFolder + File.separator + support.destinationFilename; - - if (support.templateFile.endsWith("mustache")) { - String template = readTemplate(config.templateDir() + File.separator + support.templateFile); - Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + if (info.getLicense() != null) { + License license = info.getLicense(); + if (license.getName() != null) { + config.additionalProperties().put("licenseInfo", license.getName()); } - }) - .defaultValue("") - .compile(template); + if (license.getUrl() != null) { + config.additionalProperties().put("licenseUrl", license.getUrl()); + } + } + if (info.getVersion() != null) { + config.additionalProperties().put("version", info.getVersion()); + } + } - writeToFile(outputFilename, tmpl.execute(bundle)); - files.add(new File(outputFilename)); - } else { - InputStream in = null; + StringBuilder hostBuilder = new StringBuilder(); + String scheme; + if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + scheme = swagger.getSchemes().get(0).toValue(); + } else { + scheme = "https"; + } + hostBuilder.append(scheme); + hostBuilder.append("://"); + if (swagger.getHost() != null) { + hostBuilder.append(swagger.getHost()); + } else { + hostBuilder.append("localhost"); + } + if (swagger.getBasePath() != null) { + hostBuilder.append(swagger.getBasePath()); + } else { + hostBuilder.append("/"); + } + String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath(); + String basePath = hostBuilder.toString(); - try { - in = new FileInputStream(config.templateDir() + File.separator + support.templateFile); - } - catch (Exception e) { - // continue - } - 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) - System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input"); - if(out == null) - System.out.println("can't open " + outputFile + " for output"); - } - files.add(outputFile); + List allOperations = new ArrayList(); + List allModels = new ArrayList(); + + // models + Map definitions = swagger.getDefinitions(); + if (definitions != null) { + for (String name : definitions.keySet()) { + Model model = definitions.get(name); + Map modelMap = new HashMap(); + modelMap.put(name, model); + Map models = processModels(config, modelMap); + models.putAll(config.additionalProperties()); + + allModels.add(((List) models.get("models")).get(0)); + + for (String templateName : config.modelTemplateFiles().keySet()) { + String suffix = config.modelTemplateFiles().get(templateName); + String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; + String template = readTemplate(config.templateDir() + File.separator + templateName); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); + writeToFile(filename, tmpl.execute(models)); + files.add(new File(filename)); + } + } + } + if (System.getProperty("debugModels") != null) { + System.out.println("############ Model info ############"); + Json.prettyPrint(allModels); + } + + // apis + Map> paths = processPaths(swagger.getPaths()); + for (String tag : paths.keySet()) { + List ops = paths.get(tag); + Map operation = processOperations(config, tag, ops); + + operation.put("basePath", basePath); + operation.put("contextPath", contextPath); + operation.put("baseName", tag); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); + + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); + + allOperations.add(new HashMap(operation)); + for (int i = 0; i < allOperations.size(); i++) { + Map oo = (Map) allOperations.get(i); + if (i < (allOperations.size() - 1)) { + oo.put("hasMore", "true"); + } + } + + for (String templateName : config.apiTemplateFiles().keySet()) { + + String filename = config.apiFilename(templateName, tag); + if (new File(filename).exists() && !config.shouldOverwrite(filename)) { + continue; + } + + String template = readTemplate(config.templateDir() + File.separator + templateName); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(filename, tmpl.execute(operation)); + files.add(new File(filename)); + } + } + if (System.getProperty("debugOperations") != null) { + System.out.println("############ Operation info ############"); + Json.prettyPrint(allOperations); + } + + // supporting files + Map bundle = new HashMap(); + bundle.putAll(config.additionalProperties()); + bundle.put("apiPackage", config.apiPackage()); + + Map apis = new HashMap(); + apis.put("apis", allOperations); + if (swagger.getHost() != null) { + bundle.put("host", swagger.getHost()); + } + bundle.put("basePath", basePath); + bundle.put("scheme", scheme); + bundle.put("contextPath", contextPath); + bundle.put("apiInfo", apis); + bundle.put("models", allModels); + bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); + bundle.put("modelPackage", config.modelPackage()); + bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions())); + if (swagger.getExternalDocs() != null) { + bundle.put("externalDocs", swagger.getExternalDocs()); + } + for (int i = 0; i < allModels.size() - 1; i++) { + HashMap cm = (HashMap) allModels.get(i); + CodegenModel m = cm.get("model"); + m.hasMoreModels = true; + } + + config.postProcessSupportingFileData(bundle); + + if (System.getProperty("debugSupportingFiles") != null) { + System.out.println("############ Supporting file info ############"); + Json.prettyPrint(bundle); + } + + for (SupportingFile support : config.supportingFiles()) { + String outputFolder = config.outputFolder(); + if (isNotEmpty(support.folder)) { + outputFolder += File.separator + support.folder; + } + File of = new File(outputFolder); + if (!of.isDirectory()) { + of.mkdirs(); + } + String outputFilename = outputFolder + File.separator + support.destinationFilename; + + if (support.templateFile.endsWith("mustache")) { + String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(bundle)); + files.add(new File(outputFilename)); + } else { + InputStream in = null; + + try { + in = new FileInputStream(config.templateDir() + File.separator + support.templateFile); + } catch (Exception e) { + // continue + } + 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) { + System.out.println("can't open " + config.templateDir() + File.separator + support.templateFile + " for input"); + } + if (out == null) { + System.out.println("can't open " + outputFile + " for output"); + } + } + + files.add(outputFile); + } + } + + config.processSwagger(swagger); + } catch (Exception e) { + e.printStackTrace(); } - } - - config.processSwagger(swagger); - } catch (Exception e) { - e.printStackTrace(); + return files; } - return files; - } - private void processMimeTypes(List mimeTypeList, Map operation, String source) { - if(mimeTypeList != null && mimeTypeList.size() > 0) { - List> c = new ArrayList>(); - int count = 0; - for(String key: mimeTypeList) { - Map mediaType = new HashMap(); - mediaType.put("mediaType", key); - count += 1; - if (count < mimeTypeList.size()) { - mediaType.put("hasMore", "true"); + private void processMimeTypes(List mimeTypeList, Map operation, String source) { + if (mimeTypeList != null && mimeTypeList.size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for (String key : mimeTypeList) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < mimeTypeList.size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + operation.put(source, c); + String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); + operation.put(flagFieldName, true); } - else { - mediaType.put("hasMore", null); + } + + public Map> processPaths(Map paths) { + Map> ops = new HashMap>(); + + for (String resourcePath : paths.keySet()) { + Path path = paths.get(resourcePath); + processOperation(resourcePath, "get", path.getGet(), ops); + processOperation(resourcePath, "put", path.getPut(), ops); + processOperation(resourcePath, "post", path.getPost(), ops); + processOperation(resourcePath, "delete", path.getDelete(), ops); + processOperation(resourcePath, "patch", path.getPatch(), ops); + processOperation(resourcePath, "options", path.getOptions(), ops); } - c.add(mediaType); - } - operation.put(source, c); - String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); - operation.put(flagFieldName, true); + return ops; } - } - public Map> processPaths(Map paths) { - Map> ops = new HashMap>(); - - for (String resourcePath : paths.keySet()) { - Path path = paths.get(resourcePath); - processOperation(resourcePath, "get", path.getGet(), ops); - processOperation(resourcePath, "put", path.getPut(), ops); - processOperation(resourcePath, "post", path.getPost(), ops); - processOperation(resourcePath, "delete", path.getDelete(), ops); - processOperation(resourcePath, "patch", path.getPatch(), ops); - processOperation(resourcePath, "options", path.getOptions(), ops); - } - return ops; - } - - public SecuritySchemeDefinition fromSecurity(String name) { - Map map = swagger.getSecurityDefinitions(); - if (map == null) { - return null; - } - return map.get(name); - } - - - public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations) { - if (operation != null) { - List tags = operation.getTags(); - if (tags == null) { - tags = new ArrayList(); - tags.add("default"); - } - - for (String tag : tags) { - CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); - co.tags = new ArrayList(); - co.tags.add(sanitizeTag(tag)); - config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); - - List>> securities = operation.getSecurity(); - if (securities == null) { - continue; + public SecuritySchemeDefinition fromSecurity(String name) { + Map map = swagger.getSecurityDefinitions(); + if (map == null) { + return null; } - Map authMethods = new HashMap(); - for (Map> security : securities) { - if (security.size() != 1) { - //Not sure what to do - continue; - } - String securityName = security.keySet().iterator().next(); - SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); - if (securityDefinition != null) { - authMethods.put(securityName, securityDefinition); - } + return map.get(name); + } + + + public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations) { + if (operation != null) { + List tags = operation.getTags(); + if (tags == null) { + tags = new ArrayList(); + tags.add("default"); + } + + for (String tag : tags) { + CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); + co.tags = new ArrayList(); + co.tags.add(sanitizeTag(tag)); + config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); + + List>> securities = operation.getSecurity(); + if (securities == null) { + continue; + } + Map authMethods = new HashMap(); + for (Map> security : securities) { + if (security.size() != 1) { + //Not sure what to do + continue; + } + String securityName = security.keySet().iterator().next(); + SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); + if (securityDefinition != null) { + authMethods.put(securityName, securityDefinition); + } + } + if (!authMethods.isEmpty()) { + co.authMethods = config.fromSecurity(authMethods); + } + } } - if (!authMethods.isEmpty()) { - co.authMethods = config.fromSecurity(authMethods); + } + + protected String sanitizeTag(String tag) { + // remove spaces and make strong case + String[] parts = tag.split(" "); + StringBuilder buf = new StringBuilder(); + for (String part : parts) { + if (isNotEmpty(part)) { + buf.append(capitalize(part)); + } } - } - } - } - - protected String sanitizeTag(String tag) { - // remove spaces and make strong case - String[] parts = tag.split(" "); - StringBuilder buf = new StringBuilder(); - for (String part : parts) { - if (isNotEmpty(part)) { - buf.append(capitalize(part)); - } - } - return buf.toString().replaceAll("[^a-zA-Z ]", ""); - } - - public Map processOperations(CodegenConfig config, String tag, List ops) { - Map operations = new HashMap(); - Map objs = new HashMap(); - objs.put("classname", config.toApiName(tag)); - - // check for operationId uniqueness - Set opIds = new HashSet(); - int counter = 0; - for(CodegenOperation op : ops) { - String opId = op.nickname; - if(opIds.contains(opId)) { - counter ++; - op.nickname += "_" + counter; - } - opIds.add(opId); - } - objs.put("operation", ops); - - operations.put("operations", objs); - operations.put("package", config.apiPackage()); - - - Set allImports = new LinkedHashSet(); - for (CodegenOperation op : ops) { - allImports.addAll(op.imports); + return buf.toString().replaceAll("[^a-zA-Z ]", ""); } - List> imports = new ArrayList>(); - for (String nextImport : allImports) { - Map im = new LinkedHashMap(); - String mapping = config.importMapping().get(nextImport); - if (mapping == null) { - mapping = config.toModelImport(nextImport); - } - if (mapping != null) { - im.put("import", mapping); - imports.add(im); - } + public Map processOperations(CodegenConfig config, String tag, List ops) { + Map operations = new HashMap(); + Map objs = new HashMap(); + objs.put("classname", config.toApiName(tag)); + + // check for operationId uniqueness + Set opIds = new HashSet(); + int counter = 0; + for (CodegenOperation op : ops) { + String opId = op.nickname; + if (opIds.contains(opId)) { + counter++; + op.nickname += "_" + counter; + } + opIds.add(opId); + } + objs.put("operation", ops); + + operations.put("operations", objs); + operations.put("package", config.apiPackage()); + + + Set allImports = new LinkedHashSet(); + for (CodegenOperation op : ops) { + allImports.addAll(op.imports); + } + + List> imports = new ArrayList>(); + for (String nextImport : allImports) { + Map im = new LinkedHashMap(); + String mapping = config.importMapping().get(nextImport); + if (mapping == null) { + mapping = config.toModelImport(nextImport); + } + if (mapping != null) { + im.put("import", mapping); + imports.add(im); + } + } + + operations.put("imports", imports); + config.postProcessOperations(operations); + if (objs.size() > 0) { + List os = (List) objs.get("operation"); + + if (os != null && os.size() > 0) { + CodegenOperation op = os.get(os.size() - 1); + op.hasMore = null; + } + } + return operations; } - operations.put("imports", imports); - config.postProcessOperations(operations); - if (objs.size() > 0) { - List os = (List) objs.get("operation"); + public Map processModels(CodegenConfig config, Map definitions) { + Map objs = new HashMap(); + objs.put("package", config.modelPackage()); + List models = new ArrayList(); + Set allImports = new LinkedHashSet(); + for (String key : definitions.keySet()) { + Model mm = definitions.get(key); + CodegenModel cm = config.fromModel(key, mm); + Map mo = new HashMap(); + mo.put("model", cm); + mo.put("importPath", config.toModelImport(key)); + models.add(mo); + allImports.addAll(cm.imports); + } + objs.put("models", models); - if (os != null && os.size() > 0) { - CodegenOperation op = os.get(os.size() - 1); - op.hasMore = null; - } + List> imports = new ArrayList>(); + for (String nextImport : allImports) { + Map im = new LinkedHashMap(); + String mapping = config.importMapping().get(nextImport); + if (mapping == null) { + mapping = config.toModelImport(nextImport); + } + if (mapping != null && !config.defaultIncludes().contains(mapping)) { + im.put("import", mapping); + imports.add(im); + } + // add instantiation types + mapping = config.instantiationTypes().get(nextImport); + if (mapping != null && !config.defaultIncludes().contains(mapping)) { + im.put("import", mapping); + imports.add(im); + } + } + + objs.put("imports", imports); + config.postProcessModels(objs); + + return objs; } - return operations; - } - - public Map processModels(CodegenConfig config, Map definitions) { - Map objs = new HashMap(); - objs.put("package", config.modelPackage()); - List models = new ArrayList(); - Set allImports = new LinkedHashSet(); - for (String key : definitions.keySet()) { - Model mm = definitions.get(key); - CodegenModel cm = config.fromModel(key, mm); - Map mo = new HashMap(); - mo.put("model", cm); - mo.put("importPath", config.toModelImport(key)); - models.add(mo); - allImports.addAll(cm.imports); - } - objs.put("models", models); - - List> imports = new ArrayList>(); - for (String nextImport : allImports) { - Map im = new LinkedHashMap(); - String mapping = config.importMapping().get(nextImport); - if (mapping == null) { - mapping = config.toModelImport(nextImport); - } - if (mapping != null && !config.defaultIncludes().contains(mapping)) { - im.put("import", mapping); - imports.add(im); - } - // add instantiation types - mapping = config.instantiationTypes().get(nextImport); - if (mapping != null && !config.defaultIncludes().contains(mapping)) { - im.put("import", mapping); - imports.add(im); - } - } - - objs.put("imports", imports); - config.postProcessModels(objs); - - return objs; - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java index cf44f46e637..926eb54b2b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java @@ -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 generate(); + Generator opts(ClientOptInput opts); + + List generate(); } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java index a6fdd93f271..8c8308471ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -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} @@ -22,164 +25,172 @@ import java.util.*; */ @Deprecated public class MetaGenerator extends AbstractGenerator { - static Map configs = new HashMap(); - static String configString; - static { - List extensions = getExtensions(); - StringBuilder sb = new StringBuilder(); + static Map configs = new HashMap(); + static String configString; - 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 void main(String[] args) { - new MetaGenerator().generate(args); - } - - protected void generate(String[] args) { - StringBuilder sb = new StringBuilder(); - String targetLanguage = null; - String outputFolder = null; - String name = null; - String targetPackage = "io.swagger.codegen"; - final String templateDir = "codegen"; - - Options options = new Options(); - options.addOption("h", "help", false, "shows this message"); - options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); - options.addOption("o", "output", true, "where to write the generated files"); - options.addOption("n", "name", true, "the human-readable name of the generator"); - options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen"); - - ClientOptInput clientOptInput = new ClientOptInput(); - Swagger swagger = null; - CommandLine cmd = null; - try { - CommandLineParser parser = new BasicParser(); - - cmd = parser.parse(options, args); - if (cmd.hasOption("h")) { - usage(options); - return; - } - if (cmd.hasOption("n")) - name = cmd.getOptionValue("n"); - else { - System.out.println("name is required"); - usage(options); - return; - } - if (cmd.hasOption("l")) - targetLanguage = cmd.getOptionValue("l"); - if (cmd.hasOption("p")) - targetPackage = cmd.getOptionValue("p"); - if (cmd.hasOption("o")) - outputFolder = cmd.getOptionValue("o"); - else { - System.out.println("output folder is required"); - usage(options); - return; - } - } - catch (Exception e) { - usage(options); - return; - } - System.out.println("writing to folder " + outputFolder); - File outputFolderLocation = new File(outputFolder); - if(!outputFolderLocation.exists()) - outputFolderLocation.mkdirs(); - File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar)); - if(!sourceFolder.exists()) - sourceFolder.mkdirs(); - File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services"); - if(!resourcesFolder.exists()) - resourcesFolder.mkdirs(); - - String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator"; - - List supportingFiles = new ArrayList(); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("generatorClass.mustache", - "src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar), - mainClass + ".java")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache")); - supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache")); - - supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig")); - - List files = new ArrayList(); - - Map data = new HashMap(); - data.put("generatorPackage", targetPackage); - data.put("generatorClass", mainClass); - data.put("name", name); - data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass); - - for(SupportingFile support : supportingFiles) { - try { - String destinationFolder = outputFolder; - if(support.folder != null && !"".equals(support.folder)) - destinationFolder += File.separator + support.folder; - File of = new File(destinationFolder); - if(!of.isDirectory()) - of.mkdirs(); - String outputFilename = destinationFolder + File.separator + support.destinationFilename; - - 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) { - return getTemplateReader(templateDir + File.separator + name + ".mustache"); - }; - }) - .defaultValue("") - .compile(template); - - writeToFile(outputFilename, tmpl.execute(data)); - files.add(new File(outputFilename)); + public static List getExtensions() { + ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); + List output = new ArrayList(); + Iterator itr = loader.iterator(); + while (itr.hasNext()) { + output.add(itr.next()); } - 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)); + 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); } - } - catch (java.io.IOException e) { - e.printStackTrace(); - } + return null; } - } - public static List getExtensions() { - ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); - List output = new ArrayList(); - Iterator itr = loader.iterator(); - while(itr.hasNext()) { - output.add(itr.next()); + protected void generate(String[] args) { + StringBuilder sb = new StringBuilder(); + String targetLanguage = null; + String outputFolder = null; + String name = null; + String targetPackage = "io.swagger.codegen"; + final String templateDir = "codegen"; + + Options options = new Options(); + options.addOption("h", "help", false, "shows this message"); + options.addOption("l", "lang", false, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); + options.addOption("o", "output", true, "where to write the generated files"); + options.addOption("n", "name", true, "the human-readable name of the generator"); + options.addOption("p", "package", true, "the package to put the main class into (defaults to io.swagger.codegen"); + + ClientOptInput clientOptInput = new ClientOptInput(); + Swagger swagger = null; + CommandLine cmd = null; + try { + CommandLineParser parser = new BasicParser(); + + cmd = parser.parse(options, args); + if (cmd.hasOption("h")) { + usage(options); + return; + } + if (cmd.hasOption("n")) { + name = cmd.getOptionValue("n"); + } else { + System.out.println("name is required"); + usage(options); + return; + } + if (cmd.hasOption("l")) { + targetLanguage = cmd.getOptionValue("l"); + } + if (cmd.hasOption("p")) { + targetPackage = cmd.getOptionValue("p"); + } + if (cmd.hasOption("o")) { + outputFolder = cmd.getOptionValue("o"); + } else { + System.out.println("output folder is required"); + usage(options); + return; + } + } catch (Exception e) { + usage(options); + return; + } + System.out.println("writing to folder " + outputFolder); + File outputFolderLocation = new File(outputFolder); + if (!outputFolderLocation.exists()) { + outputFolderLocation.mkdirs(); + } + File sourceFolder = new File(outputFolder + File.separator + "src/main/java/" + targetPackage.replace('.', File.separatorChar)); + if (!sourceFolder.exists()) { + sourceFolder.mkdirs(); + } + File resourcesFolder = new File(outputFolder + File.separator + "src/main/resources/META-INF/services"); + if (!resourcesFolder.exists()) { + resourcesFolder.mkdirs(); + } + + String mainClass = Character.toUpperCase(name.charAt(0)) + name.substring(1) + "Generator"; + + List supportingFiles = new ArrayList(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("generatorClass.mustache", + "src/main/java/" + File.separator + targetPackage.replace('.', File.separatorChar), + mainClass + ".java")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache")); + supportingFiles.add(new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache")); + + supportingFiles.add(new SupportingFile("services.mustache", "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig")); + + List files = new ArrayList(); + + Map data = new HashMap(); + data.put("generatorPackage", targetPackage); + data.put("generatorClass", mainClass); + data.put("name", name); + data.put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass); + + for (SupportingFile support : supportingFiles) { + try { + String destinationFolder = outputFolder; + if (support.folder != null && !"".equals(support.folder)) { + destinationFolder += File.separator + support.folder; + } + File of = new File(destinationFolder); + if (!of.isDirectory()) { + of.mkdirs(); + } + String outputFilename = destinationFolder + File.separator + support.destinationFilename; + + 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) { + return getTemplateReader(templateDir + File.separator + name + ".mustache"); + } + + ; + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(data)); + files.add(new File(outputFilename)); + } 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) { + e.printStackTrace(); + } + } } - 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 ); - } + static { + List extensions = getExtensions(); + StringBuilder sb = new StringBuilder(); - public static CodegenConfig getConfig(String name) { - if(configs.containsKey(name)) { - return configs.get(name); + for (CodegenConfig config : extensions) { + if (sb.toString().length() != 0) { + sb.append(", "); + } + sb.append(config.getName()); + configs.put(config.getName(), config); + configString = sb.toString(); + } } - return null; - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java index 133a6259f24..6be69b85d54 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -1,13 +1,13 @@ package io.swagger.codegen; public class SupportingFile { - public String templateFile; - public String folder; - public String destinationFilename; + public String templateFile; + public String folder; + public String destinationFilename; - public SupportingFile(String templateFile, String folder, String destinationFilename) { - this.templateFile = templateFile; - this.folder = folder; - this.destinationFilename = destinationFilename; - } + public SupportingFile(String templateFile, String folder, String destinationFilename) { + this.templateFile = templateFile; + this.folder = folder; + this.destinationFilename = destinationFilename; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java index 94b43f59888..9a526f1ecf1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java @@ -1,6 +1,7 @@ package io.swagger.codegen.auth; public interface AuthMethod { - String getType(); - void setType(String type); + String getType(); + + void setType(String type); } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index d6ee8ac642c..855739af1fd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -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,147 +20,139 @@ 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 examples; + protected Map examples; - public ExampleGenerator(Map examples) { - this.examples = examples; - } + public ExampleGenerator(Map examples) { + this.examples = examples; + } - public List> generate(Map examples, List mediaTypes, Property property) { - List> output = new ArrayList>(); - Set processedModels = new HashSet(); - if(examples == null ) { - if(mediaTypes == null) { - // assume application/json for this - mediaTypes = Arrays.asList("application/json"); - } - for(String mediaType : mediaTypes) { - Map kv = new HashMap(); - kv.put("contentType", mediaType); - if(property != null && mediaType.startsWith("application/json")) { - String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); + public List> generate(Map examples, List mediaTypes, Property property) { + List> output = new ArrayList>(); + Set processedModels = new HashSet(); + if (examples == null) { + if (mediaTypes == null) { + // assume application/json for this + mediaTypes = Arrays.asList("application/json"); + } + for (String mediaType : mediaTypes) { + Map kv = new HashMap(); + kv.put("contentType", mediaType); + if (property != null && mediaType.startsWith("application/json")) { + String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); - if(example != null) { - kv.put("example", example); - output.add(kv); - } + if (example != null) { + kv.put("example", example); + output.add(kv); + } + } else if (property != null && mediaType.startsWith("application/xml")) { + String example = new XmlExampleGenerator(this.examples).toXml(property); + if (example != null) { + kv.put("example", example); + output.add(kv); + } + } + } + } else { + for (Map.Entry entry : examples.entrySet()) { + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", Json.pretty(entry.getValue())); + output.add(kv); + } } - else if(property != null && mediaType.startsWith("application/xml")) { - String example = new XmlExampleGenerator(this.examples).toXml(property); - if(example != null) { - kv.put("example", example); + if (output.size() == 0) { + Map kv = new HashMap(); + kv.put("output", "none"); output.add(kv); - } } - } - } - else { - for(Map.Entry entry: examples.entrySet()) { - final Map kv = new HashMap(); - kv.put("contentType", entry.getKey()); - kv.put("example", Json.pretty(entry.getValue())); - output.add(kv); - } - } - if(output.size() == 0) { - Map kv = new HashMap(); - kv.put("output", "none"); - output.add(kv); - } - return output; - } - - protected Object resolvePropertyToExample(String mediaType, Property property, Set processedModels) { - if(property.getExample() != null) { - return property.getExample(); - } - else if(property instanceof StringProperty) { - return "aeiou"; - } - else if(property instanceof BooleanProperty) { - return Boolean.TRUE; - } - 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) { - return new java.util.Date(System.currentTimeMillis()); - } - else if(property instanceof DateTimeProperty) { - return new java.util.Date(System.currentTimeMillis()); - } - else if(property instanceof DecimalProperty) { - return new BigDecimal(1.3579); - } - else if(property instanceof DoubleProperty) { - return new Double(3.149); - } - else if(property instanceof FileProperty) { - return ""; // TODO - } - else if(property instanceof FloatProperty) { - return new Float(1.23); - } - else if(property instanceof IntegerProperty) { - return new Integer(123); - } - else if(property instanceof LongProperty) { - return new Long(123456789); - } - else if(property instanceof MapProperty) { - Map mp = new HashMap(); - if(property.getName() != null) { - mp.put(property.getName(), - resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels)); - } - else { - mp.put("key", - resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels)); - } - return mp; - } - else if(property instanceof ObjectProperty) { - return "{}"; - } - else if(property instanceof RefProperty) { - String simpleName = ((RefProperty)property).getSimpleRef(); - Model model = examples.get(simpleName); - if(model != null) - return resolveModelToExample(simpleName, mediaType, model, processedModels); - } - else if(property instanceof UUIDProperty) { - return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; } - return ""; - } - - public Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { - if(processedModels.contains(name)) { - return ""; - } - if(model instanceof ModelImpl) { - processedModels.add(name); - ModelImpl impl = (ModelImpl) model; - Map values = new HashMap(); - - 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)); + protected Object resolvePropertyToExample(String mediaType, Property property, Set processedModels) { + if (property.getExample() != null) { + return property.getExample(); + } else if (property instanceof StringProperty) { + return "aeiou"; + } else if (property instanceof BooleanProperty) { + return Boolean.TRUE; + } 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) { + return new java.util.Date(System.currentTimeMillis()); + } else if (property instanceof DateTimeProperty) { + return new java.util.Date(System.currentTimeMillis()); + } else if (property instanceof DecimalProperty) { + return new BigDecimal(1.3579); + } else if (property instanceof DoubleProperty) { + return new Double(3.149); + } else if (property instanceof FileProperty) { + return ""; // TODO + } else if (property instanceof FloatProperty) { + return new Float(1.23); + } else if (property instanceof IntegerProperty) { + return new Integer(123); + } else if (property instanceof LongProperty) { + return new Long(123456789); + } else if (property instanceof MapProperty) { + Map mp = new HashMap(); + if (property.getName() != null) { + mp.put(property.getName(), + resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + } else { + mp.put("key", + resolvePropertyToExample(mediaType, ((MapProperty) property).getAdditionalProperties(), processedModels)); + } + return mp; + } else if (property instanceof ObjectProperty) { + return "{}"; + } else if (property instanceof RefProperty) { + String simpleName = ((RefProperty) property).getSimpleRef(); + Model model = examples.get(simpleName); + if (model != null) { + return resolveModelToExample(simpleName, mediaType, model, processedModels); + } + } else if (property instanceof UUIDProperty) { + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; } - } - return values; + return ""; } - return ""; - } + public Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { + if (processedModels.contains(name)) { + return ""; + } + if (model instanceof ModelImpl) { + processedModels.add(name); + ModelImpl impl = (ModelImpl) model; + Map values = new HashMap(); + + 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)); + } + } + + return values; + } + + return ""; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index 99765195d87..73294268f39 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -1,206 +1,226 @@ package io.swagger.codegen.examples; -import io.swagger.util.Json; -import io.swagger.models.*; -import io.swagger.models.properties.*; - -import java.text.SimpleDateFormat; -import java.util.*; - +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.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 = " 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 static String NEWLINE = "\n"; + public static String TAG_START = "<"; + public static String CLOSE_TAG = ">"; + public static String TAG_END = " 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'"); - public XmlExampleGenerator(Map examples) { - this.examples = examples; - if(examples == null) - examples = new HashMap(); - } - - public String toXml(Property property) { - return toXml(null, property, 0, Collections.emptySet()); - } - - protected String toXml(Model model, int indent, Collection path) { - if(model instanceof RefModel) { - RefModel ref = (RefModel) model; - Model actualModel = examples.get(ref.getSimpleRef()); - if(actualModel instanceof ModelImpl) - return modelImplToXml((ModelImpl) actualModel, indent, path); - } - else if(model instanceof ModelImpl) { - return modelImplToXml((ModelImpl) model, indent, path); - } - return null; - } - - protected String modelImplToXml(ModelImpl model, int indent, Collection path) { - final String modelName = model.getName(); - if (path.contains(modelName)) { - return EMPTY; - } - final Set selfPath = new HashSet(path); - selfPath.add(modelName); - - StringBuilder sb = new StringBuilder(); - // attributes - Map attributes = new LinkedHashMap(); - Map elements = new LinkedHashMap(); - - String name = modelName; - String namespace; - String prefix; - Boolean wrapped; - - Xml xml = model.getXml(); - if(xml != null) { - if(xml.getName() != null) - name = xml.getName(); - } - for(String pName : model.getProperties().keySet()) { - Property p = model.getProperties().get(pName); - if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) - attributes.put(pName, p); - else - elements.put(pName, p); - } - sb.append(indent(indent)).append(TAG_START); - sb.append(name); - 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()) { - Property p = elements.get(pName); - final String asXml = toXml(pName, p, indent + 1, selfPath); - if (StringUtils.isEmpty(asXml)) { - continue; - } - sb.append(asXml); - sb.append(NEWLINE); - } - sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); - - return sb.toString(); - } - - protected String quote(String string) { - return "\"" + string + "\""; - } - - protected String toXml(String name, Property property, int indent, Collection path) { - if(property == null) { - return ""; - } - StringBuilder sb = new StringBuilder(); - - if(property instanceof ArrayProperty) { - ArrayProperty p = (ArrayProperty) property; - Property inner = p.getItems(); - boolean wrapped = false; - if(property.getXml() != null && property.getXml().getWrapped()) - wrapped = true; - if(wrapped) { - String prefix = EMPTY; - if(name != null) { - sb.append(indent(indent)); - sb.append(openTag(name)); - prefix = NEWLINE; + public XmlExampleGenerator(Map examples) { + this.examples = examples; + if (examples == null) { + examples = new HashMap(); } - final String asXml = toXml(name, inner, indent + 1, path); - if (StringUtils.isNotEmpty(asXml)) { - sb.append(prefix).append(asXml); + } + + public String toXml(Property property) { + return toXml(null, property, 0, Collections.emptySet()); + } + + protected String toXml(Model model, int indent, Collection path) { + if (model instanceof RefModel) { + RefModel ref = (RefModel) model; + Model actualModel = examples.get(ref.getSimpleRef()); + if (actualModel instanceof ModelImpl) { + return modelImplToXml((ModelImpl) actualModel, indent, path); + } + } else if (model instanceof ModelImpl) { + return modelImplToXml((ModelImpl) model, indent, path); } - if(name != null) { - sb.append(NEWLINE); - sb.append(indent(indent)); - sb.append(closeTag(name)); + return null; + } + + protected String modelImplToXml(ModelImpl model, int indent, Collection path) { + final String modelName = model.getName(); + if (path.contains(modelName)) { + return EMPTY; } - } - else - sb.append(toXml(name, inner, indent, path)); - } - 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) { - sb.append(indent(indent)); - sb.append(openTag(name)); - } - sb.append(getExample(property)); - if(name != null) - sb.append(closeTag(name)); - } - return sb.toString(); - } + final Set selfPath = new HashSet(path); + selfPath.add(modelName); - protected String getExample(Property property) { - if(property instanceof DateTimeProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return dtFormat.format(new Date()); - } - else if(property instanceof StringProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return "string"; - } - else if(property instanceof DateProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return dateFormat.format(new Date()); - } - else if(property instanceof IntegerProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return "0"; - } - else if(property instanceof BooleanProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return "true"; - } - else if(property instanceof LongProperty) { - if(property.getExample() != null) - return property.getExample(); - else - return "123456"; - } - return "not implemented " + property; - } + StringBuilder sb = new StringBuilder(); + // attributes + Map attributes = new LinkedHashMap(); + Map elements = new LinkedHashMap(); - protected String openTag(String name) { - return "<" + name + ">"; - } + String name = modelName; + String namespace; + String prefix; + Boolean wrapped; - protected String closeTag(String name) { - return ""; - } + Xml xml = model.getXml(); + if (xml != null) { + if (xml.getName() != null) { + name = xml.getName(); + } + } + for (String pName : model.getProperties().keySet()) { + Property p = model.getProperties().get(pName); + if (p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) { + attributes.put(pName, p); + } else { + elements.put(pName, p); + } + } + sb.append(indent(indent)).append(TAG_START); + sb.append(name); + 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()) { + Property p = elements.get(pName); + final String asXml = toXml(pName, p, indent + 1, selfPath); + if (StringUtils.isEmpty(asXml)) { + continue; + } + sb.append(asXml); + sb.append(NEWLINE); + } + sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); - protected String indent(int indent) { - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < indent; i++) { - sb.append(" "); + return sb.toString(); + } + + protected String quote(String string) { + return "\"" + string + "\""; + } + + protected String toXml(String name, Property property, int indent, Collection path) { + if (property == null) { + return ""; + } + StringBuilder sb = new StringBuilder(); + + if (property instanceof ArrayProperty) { + ArrayProperty p = (ArrayProperty) property; + Property inner = p.getItems(); + boolean wrapped = false; + if (property.getXml() != null && property.getXml().getWrapped()) { + wrapped = true; + } + if (wrapped) { + String prefix = EMPTY; + if (name != null) { + sb.append(indent(indent)); + sb.append(openTag(name)); + prefix = NEWLINE; + } + final String asXml = toXml(name, inner, indent + 1, path); + if (StringUtils.isNotEmpty(asXml)) { + sb.append(prefix).append(asXml); + } + if (name != null) { + sb.append(NEWLINE); + sb.append(indent(indent)); + sb.append(closeTag(name)); + } + } else { + sb.append(toXml(name, inner, indent, path)); + } + } 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) { + sb.append(indent(indent)); + sb.append(openTag(name)); + } + sb.append(getExample(property)); + if (name != null) { + sb.append(closeTag(name)); + } + } + return sb.toString(); + } + + protected String getExample(Property property) { + if (property instanceof DateTimeProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return dtFormat.format(new Date()); + } + } else if (property instanceof StringProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return "string"; + } + } else if (property instanceof DateProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return dateFormat.format(new Date()); + } + } else if (property instanceof IntegerProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return "0"; + } + } else if (property instanceof BooleanProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return "true"; + } + } else if (property instanceof LongProperty) { + if (property.getExample() != null) { + return property.getExample(); + } else { + return "123456"; + } + } + return "not implemented " + property; + } + + protected String openTag(String name) { + return "<" + name + ">"; + } + + protected String closeTag(String name) { + return ""; + } + + protected String indent(int indent) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < indent; i++) { + sb.append(" "); + } + return sb.toString(); } - return sb.toString(); - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index fd53c6db3e2..efcd771ac10 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -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,352 +31,369 @@ 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"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String resourcesFolder = "src/main/resources"; + protected String configKey = "apiRequest"; + protected int defaultTimeoutInMs = 5000; + protected String configKeyPath = mainPackage; + protected boolean registerNonStandardStatusCodes = true; + protected boolean renderJavadoc = true; + protected boolean removeOAuthSecurities = true; + /** + * If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all + * others as ApiErrors. + * If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, + * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. + */ + protected boolean onlyOneSuccess = true; + Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); - protected String mainPackage = "io.swagger.client"; + public AkkaScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "akka-scala"; + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; - protected String invokerPackage = mainPackage + ".core"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; - protected String resourcesFolder = "src/main/resources"; - protected String configKey = "apiRequest"; - protected int defaultTimeoutInMs = 5000; - protected String configKeyPath = mainPackage; + reservedWords = new HashSet( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); - protected boolean registerNonStandardStatusCodes = true; - protected boolean renderJavadoc = true; - protected boolean removeOAuthSecurities = true; - /** - * If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all - * others as ApiErrors. - * If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, - * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. - */ - protected boolean onlyOneSuccess = true; + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("configKey", configKey); + additionalProperties.put("configKeyPath", configKeyPath); + additionalProperties.put("defaultTimeout", defaultTimeoutInMs); + if (renderJavadoc) { + additionalProperties.put("javadocRenderer", new JavadocLambda()); + } + additionalProperties.put("fnCapitalize", new CapitalizeLambda()); + additionalProperties.put("fnCamelize", new CamelizeLambda(false)); + additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); + additionalProperties.put("onlyOneSuccess", onlyOneSuccess); - public CodegenType getTag() { - return CodegenType.CLIENT; - } + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); + final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); - public String getName() { - return "akka-scala"; - } + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); - public String getHelp() { - return "Generates a Scala client library base on Akka/Spray."; - } + importMapping.put("DateTime", "org.joda.time.DateTime"); - public AkkaScalaClientCodegen() { - super(); - outputFolder = "generated-code/scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "akka-scala"; - apiPackage = mainPackage + ".api"; - modelPackage = mainPackage + ".model"; + typeMapping = new HashMap(); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + typeMapping.put("number", "Double"); - reservedWords = new HashSet( - Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Seq", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + } - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - additionalProperties.put("configKey", configKey); - additionalProperties.put("configKeyPath", configKeyPath); - additionalProperties.put("defaultTimeout", defaultTimeoutInMs); - if (renderJavadoc) - additionalProperties.put("javadocRenderer", new JavadocLambda()); - additionalProperties.put("fnCapitalize", new CapitalizeLambda()); - additionalProperties.put("fnCamelize", new CamelizeLambda(false)); - additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); - additionalProperties.put("onlyOneSuccess", onlyOneSuccess); + public CodegenType getTag() { + return CodegenType.CLIENT; + } - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); - final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); - supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); - supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); - supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); - final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); - supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + public String getName() { + return "akka-scala"; + } - importMapping.remove("Seq"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); + public String getHelp() { + return "Generates a Scala client library base on Akka/Spray."; + } - importMapping.put("DateTime", "org.joda.time.DateTime"); + @Override + public String escapeReservedWord(String name) { + return "`" + name + "`"; + } - typeMapping = new HashMap(); - typeMapping.put("array", "Seq"); - typeMapping.put("set", "Set"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("int", "Int"); - typeMapping.put("integer", "Int"); - typeMapping.put("long", "Long"); - typeMapping.put("float", "Float"); - typeMapping.put("byte", "Byte"); - typeMapping.put("short", "Short"); - typeMapping.put("char", "Char"); - typeMapping.put("long", "Long"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "Any"); - typeMapping.put("file", "File"); - typeMapping.put("number", "Double"); + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Seq", - "Map") - ); - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "Map"); - } + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } - @Override - public String escapeReservedWord(String name) { - return "`" + name + "`"; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public Map postProcessOperations(Map objs) { - if (registerNonStandardStatusCodes) { - try { - @SuppressWarnings("unchecked") - Map> opsMap = (Map>) objs.get("operations"); - HashSet unknownCodes = new HashSet(); - for (CodegenOperation operation : opsMap.get("operation")) { - for (CodegenResponse response : operation.responses) { - if ("default".equals(response.code)) - continue; + @Override + public Map postProcessOperations(Map objs) { + if (registerNonStandardStatusCodes) { try { - int code = Integer.parseInt(response.code); - if (code >= 600) { - unknownCodes.add(code); - } - } catch (NumberFormatException e) { - LOGGER.error("Status code is not an integer : response.code", e); + @SuppressWarnings("unchecked") + Map> opsMap = (Map>) objs.get("operations"); + HashSet unknownCodes = new HashSet(); + for (CodegenOperation operation : opsMap.get("operation")) { + for (CodegenResponse response : operation.responses) { + if ("default".equals(response.code)) { + continue; + } + try { + int code = Integer.parseInt(response.code); + if (code >= 600) { + unknownCodes.add(code); + } + } catch (NumberFormatException e) { + LOGGER.error("Status code is not an integer : response.code", e); + } + } + } + if (!unknownCodes.isEmpty()) { + additionalProperties.put("unknownStatusCodes", unknownCodes); + } + } catch (Exception e) { + LOGGER.error("Unable to find operations List", e); } - } } - if (!unknownCodes.isEmpty()) { - additionalProperties.put("unknownStatusCodes", unknownCodes); + return super.postProcessOperations(objs); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; } - } catch (Exception e) { - LOGGER.error("Unable to find operations List", e); - } - } - return super.postProcessOperations(objs); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - - @Override - public List fromSecurity(Map schemes) { - final List codegenSecurities = super.fromSecurity(schemes); - if (!removeOAuthSecurities) - return codegenSecurities; - - // Remove OAuth securities - Iterator it = codegenSecurities.iterator(); - while (it.hasNext()) { - final CodegenSecurity security = it.next(); - if (security.isOAuth) - it.remove(); - } - // Adapt 'hasMore' - it = codegenSecurities.iterator(); - while (it.hasNext()) { - final CodegenSecurity security = it.next(); - security.hasMore = it.hasNext(); + return super.getTypeDeclaration(p); } - if (codegenSecurities.isEmpty()) - return null; - return codegenSecurities; - } + @Override + public List fromSecurity(Map schemes) { + final List codegenSecurities = super.fromSecurity(schemes); + if (!removeOAuthSecurities) { + return codegenSecurities; + } - @Override - public String toOperationId(String operationId) { - return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); - } + // Remove OAuth securities + Iterator it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + if (security.isOAuth) { + it.remove(); + } + } + // Adapt 'hasMore' + it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + security.hasMore = it.hasNext(); + } - private String formatIdentifier(String name, boolean capitalized) { - String identifier = camelize(name, true); - if (capitalized) - identifier = StringUtils.capitalize(identifier); - if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) - return identifier; - return escapeReservedWord(identifier); - } + if (codegenSecurities.isEmpty()) { + return null; + } + return codegenSecurities; + } - @Override - public String toParamName(String name) { return formatIdentifier(name, false); } + @Override + public String toOperationId(String operationId) { + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); + } - @Override - public String toVarName(String name) { - return formatIdentifier(name, false); - } + private String formatIdentifier(String name, boolean capitalized) { + String identifier = camelize(name, true); + if (capitalized) { + identifier = StringUtils.capitalize(identifier); + } + if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) { + return identifier; + } + return escapeReservedWord(identifier); + } - @Override - public String toEnumName(CodegenProperty property) - { - return formatIdentifier(property.baseName, true); - } + @Override + public String toParamName(String name) { + return formatIdentifier(name, false); + } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) + @Override + public String toVarName(String name) { + return formatIdentifier(name, false); + } + + @Override + public String toEnumName(CodegenProperty property) { + return formatIdentifier(property.baseName, true); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); - } else - type = swaggerType; - return toModelName(type); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } else - return null; - } - - public String toDefaultValue(Property p) { - if (!p.getRequired()) - return "None"; - if (p instanceof StringProperty) - return "null"; - else if (p instanceof BooleanProperty) - return "null"; - else if (p instanceof DateProperty) - return "null"; - else if (p instanceof DateTimeProperty) - return "null"; - else if (p instanceof DoubleProperty) - return "null"; - else if (p instanceof FloatProperty) - return "null"; - else if (p instanceof IntegerProperty) - return "null"; - else if (p instanceof LongProperty) - return "null"; - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "Map[String, " + inner + "].empty "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "Seq[" + inner + "].empty "; - } else - return "null"; - } - - private static abstract class CustomLambda implements Mustache.Lambda { - @Override - public void execute(Template.Fragment frag, Writer out) throws IOException { - final StringWriter tempWriter = new StringWriter(); - frag.execute(tempWriter); - out.write(formatFragment(tempWriter.toString())); - } - public abstract String formatFragment(String fragment); - } - - - private static class JavadocLambda extends CustomLambda { - @Override - public String formatFragment(String fragment) { - final String[] lines = fragment.split("\\r?\\n"); - final StringBuilder sb = new StringBuilder(); - sb.append(" /**\n"); - for (String line : lines) { - sb.append(" * ").append(line).append("\n"); - } - sb.append(" */\n"); - return sb.toString(); - } - } - - private static class CapitalizeLambda extends CustomLambda { - @Override - public String formatFragment(String fragment) { - return StringUtils.capitalize(fragment); - } - } - - private static class CamelizeLambda extends CustomLambda { - private final boolean capitalizeFirst; - - public CamelizeLambda(boolean capitalizeFirst) { - this.capitalizeFirst = capitalizeFirst; } @Override - public String formatFragment(String fragment) { - return camelize(fragment, !capitalizeFirst); + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else { + return null; + } } - } - private class EnumEntryLambda extends CustomLambda { - @Override - public String formatFragment(String fragment) { - return formatIdentifier(fragment, true); + public String toDefaultValue(Property p) { + if (!p.getRequired()) { + return "None"; + } + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + return "null"; + } else if (p instanceof FloatProperty) { + return "null"; + } else if (p instanceof IntegerProperty) { + return "null"; + } else if (p instanceof LongProperty) { + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "Map[String, " + inner + "].empty "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "Seq[" + inner + "].empty "; + } else { + return "null"; + } + } + + private static abstract class CustomLambda implements Mustache.Lambda { + @Override + public void execute(Template.Fragment frag, Writer out) throws IOException { + final StringWriter tempWriter = new StringWriter(); + frag.execute(tempWriter); + out.write(formatFragment(tempWriter.toString())); + } + + public abstract String formatFragment(String fragment); + } + + + private static class JavadocLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + final String[] lines = fragment.split("\\r?\\n"); + final StringBuilder sb = new StringBuilder(); + sb.append(" /**\n"); + for (String line : lines) { + sb.append(" * ").append(line).append("\n"); + } + sb.append(" */\n"); + return sb.toString(); + } + } + + private static class CapitalizeLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return StringUtils.capitalize(fragment); + } + } + + private static class CamelizeLambda extends CustomLambda { + private final boolean capitalizeFirst; + + public CamelizeLambda(boolean capitalizeFirst) { + this.capitalizeFirst = capitalizeFirst; + } + + @Override + public String formatFragment(String fragment) { + return camelize(fragment, !capitalizeFirst); + } + } + + private class EnumEntryLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return formatIdentifier(fragment, true); + } } - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index b1bc4f0b08b..9a3237d92ca 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -1,259 +1,265 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-android-client"; - protected String artifactVersion = "1.0.0"; - protected String projectFolder = "src/main"; - protected String sourceFolder = projectFolder + "/java"; - protected Boolean useAndroidMavenGradlePlugin = true; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-android-client"; + protected String artifactVersion = "1.0.0"; + protected String projectFolder = "src/main"; + protected String sourceFolder = projectFolder + "/java"; + protected Boolean useAndroidMavenGradlePlugin = true; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public AndroidClientCodegen() { + super(); + outputFolder = "generated-code/android"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "android-java"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; - public String getName() { - return "android"; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); - public String getHelp() { - return "Generates an Android client library."; - } + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); - public AndroidClientCodegen() { - super(); - outputFolder = "generated-code/android"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "android-java"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - - cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code")); - cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code")); + cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String getName() { + return "android"; + } + + public String getHelp() { + return "Generates an Android client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } - // camelize (lower first character) the variable name - // pet_id => petId - name = camelize(name, true); + // 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.*")) - name = escapeReservedWord(name); + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - - return camelize(operationId, true); - } - - @Override - public void processOpts() { - super.processOpts(); - - 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{ - //not set, use to be passed to template - additionalProperties.put("groupId", groupId); - } - - 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{ - //not set, use to be passed to template - additionalProperties.put("artifactVersion", artifactVersion); - } - - if(additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String)additionalProperties.get("sourceFolder")); + return name; } - if(additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { - this.setUseAndroidMavenGradlePlugin((Boolean)additionalProperties.get("useAndroidMavenGradlePlugin")); + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); } - else{ - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); } - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("httpPatch.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java")); - supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); - } + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } - public Boolean getUseAndroidMavenGradlePlugin() { - return useAndroidMavenGradlePlugin; - } + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) { - this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin; - } + return camelize(operationId, true); + } - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } + @Override + public void processOpts() { + super.processOpts(); - public void setGroupId(String groupId) { - this.groupId = groupId; - } + if (additionalProperties.containsKey("invokerPackage")) { + this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + } else { + //not set, use default to be passed to template + additionalProperties.put("invokerPackage", invokerPackage); + } - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } + if (additionalProperties.containsKey("groupId")) { + this.setGroupId((String) additionalProperties.get("groupId")); + } else { + //not set, use to be passed to template + additionalProperties.put("groupId", groupId); + } - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } + if (additionalProperties.containsKey("artifactId")) { + this.setArtifactId((String) additionalProperties.get("artifactId")); + } else { + //not set, use to be passed to template + additionalProperties.put("artifactId", artifactId); + } - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } + 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("useAndroidMavenGradlePlugin")) { + this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin")); + } else { + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + } + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("httpPatch.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java")); + supportingFiles.add(new SupportingFile("jsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + } + + public Boolean getUseAndroidMavenGradlePlugin() { + return useAndroidMavenGradlePlugin; + } + + public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) { + this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 5e06d3fd3f5..c941d8b8d97 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -1,194 +1,207 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-async-scala-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; - protected String clientName = "SwaggerClient"; - protected String authScheme = ""; - protected boolean authPreemptive = false; - protected boolean asyncHttpClient = !authScheme.isEmpty(); + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-async-scala-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String clientName = "SwaggerClient"; + protected String authScheme = ""; + protected boolean authPreemptive = false; + protected boolean asyncHttpClient = !authScheme.isEmpty(); - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "async-scala"; - } + public AsyncScalaClientCodegen() { + super(); + outputFolder = "generated-code/async-scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "asyncscala"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; - public String getHelp() { - return "Generates an Asynchronous Scala client library."; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); - public AsyncScalaClientCodegen() { - super(); - outputFolder = "generated-code/async-scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "asyncscala"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("asyncHttpClient", asyncHttpClient); + additionalProperties.put("authScheme", authScheme); + additionalProperties.put("authPreemptive", authPreemptive); + additionalProperties.put("clientName", clientName); - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("client.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - additionalProperties.put("asyncHttpClient", asyncHttpClient); - additionalProperties.put("authScheme", authScheme); - additionalProperties.put("authPreemptive", authPreemptive); - additionalProperties.put("clientName", clientName); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); - supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt")); - supportingFiles.add(new SupportingFile("client.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("array", "List"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); - importMapping.put("DateTime", "org.joda.time.DateTime"); - importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); - - typeMapping = new HashMap(); - typeMapping.put("enum", "NSString"); - typeMapping.put("array", "List"); - typeMapping.put("set", "Set"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Long"); - typeMapping.put("float", "Float"); - typeMapping.put("byte", "Byte"); - typeMapping.put("short", "Short"); - typeMapping.put("char", "Char"); - typeMapping.put("long", "Long"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "Any"); - typeMapping.put("file", "File"); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Map") - ); - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "HashMap"); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "HashMap"); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String getName() { + return "async-scala"; + } + + public String getHelp() { + return "Generates an Asynchronous Scala client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else { + return null; + } } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; - } - else - return null; - } - public String toDefaultValue(Property p) { - if(p instanceof StringProperty) - return "null"; - else if (p instanceof BooleanProperty) - return "null"; - else if(p instanceof DateProperty) - return "null"; - else if(p instanceof DateTimeProperty) - return "null"; - else if (p instanceof DoubleProperty) - return "null"; - else if (p instanceof FloatProperty) - return "null"; - else if (p instanceof IntegerProperty) - return "null"; - else if (p instanceof LongProperty) - return "null"; - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + return "null"; + } else if (p instanceof FloatProperty) { + return "null"; + } else if (p instanceof IntegerProperty) { + return "null"; + } else if (p instanceof LongProperty) { + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } else { + return "null"; + } } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } - else - return "null"; - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 3a756ab074e..a564ec5f883 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -1,192 +1,203 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-csharp-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/csharp"; + protected String invokerPackage = "IO.Swagger.Client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-csharp-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/csharp"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public CSharpClientCodegen() { + super(); + outputFolder = "generated-code/csharp"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + templateDir = "csharp"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; - public String getName() { - return "csharp"; - } + reservedWords = new HashSet( + 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") + ); - public String getHelp() { - return "Generates a CSharp client library."; - } + additionalProperties.put("invokerPackage", invokerPackage); - public CSharpClientCodegen() { - super(); - outputFolder = "generated-code/csharp"; - modelTemplateFiles.put("model.mustache", ".cs"); - apiTemplateFiles.put("api.mustache", ".cs"); - templateDir = "csharp"; - apiPackage = "IO.Swagger.Api"; - modelPackage = "IO.Swagger.Model"; + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); + supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); + supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); + supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); - reservedWords = new HashSet ( - 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") - ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "string", + "bool?", + "double?", + "int?", + "long?", + "float?", + "byte[]", + "List", + "Dictionary", + "DateTime?", + "String", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "List"); + instantiationTypes.put("map", "Dictionary"); - additionalProperties.put("invokerPackage", invokerPackage); + typeMapping = new HashMap(); + typeMapping.put("string", "string"); + typeMapping.put("boolean", "bool?"); + typeMapping.put("integer", "int?"); + typeMapping.put("float", "float?"); + typeMapping.put("long", "long?"); + typeMapping.put("double", "double?"); + typeMapping.put("number", "double?"); + typeMapping.put("datetime", "DateTime?"); + typeMapping.put("date", "DateTime?"); + typeMapping.put("file", "string"); // path to file + typeMapping.put("array", "List"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("object", "Object"); - supportingFiles.add(new SupportingFile("Configuration.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs")); - supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); - supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); - supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "string", - "bool?", - "double?", - "int?", - "long?", - "float?", - "byte[]", - "List", - "Dictionary", - "DateTime?", - "String", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "List"); - instantiationTypes.put("map", "Dictionary"); - - typeMapping = new HashMap(); - typeMapping.put("string", "string"); - typeMapping.put("boolean", "bool?"); - typeMapping.put("integer", "int?"); - typeMapping.put("float", "float?"); - typeMapping.put("long", "long?"); - typeMapping.put("double", "double?"); - typeMapping.put("number", "double?"); - typeMapping.put("datetime", "DateTime?"); - typeMapping.put("date", "DateTime?"); - typeMapping.put("file", "string"); // path to file - typeMapping.put("array", "List"); - typeMapping.put("list", "List"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("object", "Object"); - - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/')).replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return (outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/')).replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize 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.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType.toLowerCase())) { - type = typeMapping.get(swaggerType.toLowerCase()); - if(languageSpecificPrimitives.contains(type)) - return type; + public String getName() { + return "csharp"; } - 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)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + public String getHelp() { + return "Generates a CSharp client library."; + } - return camelize(operationId); - } + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/')).replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return (outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/')).replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize 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.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(operationId); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index b8011d3d459..fcec455e9b3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -1,241 +1,247 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-java-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-java-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public JavaClientCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "Java"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; - public String getName() { - return "java"; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); - public String getHelp() { - return "Generates a Java client library."; - } + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); - public JavaClientCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "Java"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - ); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - - cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); - cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml")); - cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); - cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - } - - @Override - public void processOpts() { - super.processOpts(); - - if(additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String)additionalProperties.get("invokerPackage")); - } - else{ - //not set, use default to be passed to template - additionalProperties.put("invokerPackage", invokerPackage); + cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); + cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml")); + cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); + cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); } - if(additionalProperties.containsKey("groupId")) { - this.setGroupId((String)additionalProperties.get("groupId")); - } - else{ - //not set, use to be passed to template - additionalProperties.put("groupId", groupId); + public CodegenType getTag() { + return CodegenType.CLIENT; } - if(additionalProperties.containsKey("artifactId")) { - this.setArtifactId((String)additionalProperties.get("artifactId")); - } - else{ - //not set, use to be passed to template - additionalProperties.put("artifactId", artifactId); + public String getName() { + return "java"; } - if(additionalProperties.containsKey("artifactVersion")) { - this.setArtifactVersion((String)additionalProperties.get("artifactVersion")); - } - else{ - //not set, use to be passed to template - additionalProperties.put("artifactVersion", artifactVersion); + public String getHelp() { + return "Generates a Java client library."; } - if(additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String)additionalProperties.get("sourceFolder")); + @Override + public void processOpts() { + super.processOpts(); + + 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 { + //not set, use to be passed to template + additionalProperties.put("groupId", groupId); + } + + 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 { + //not set, use to be passed to template + additionalProperties.put("artifactVersion", artifactVersion); + } + + if (additionalProperties.containsKey("sourceFolder")) { + this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + } + + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); + supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); + supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); + supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + + final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); } - final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); - supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); - supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); - supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); - } - - - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize (lower 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.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + @Override + public String escapeReservedWord(String name) { + return "_" + name; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize (lower 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.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - 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)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - return camelize(operationId, true); - } + return camelize(operationId, true); + } - public void setInvokerPackage(String invokerPackage) { - this.invokerPackage = invokerPackage; - } + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; + } - public void setArtifactVersion(String artifactVersion) { - this.artifactVersion = artifactVersion; - } + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index 0720f6517e1..ac541157458 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -1,200 +1,206 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-jaxrs-server"; - protected String artifactVersion = "1.0.0"; - protected String title = "Swagger Server"; + protected String invokerPackage = "io.swagger.api"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-jaxrs-server"; + protected String artifactVersion = "1.0.0"; + protected String title = "Swagger Server"; - public CodegenType getTag() { - return CodegenType.SERVER; - } + public JaxRSServerCodegen() { + super.processOpts(); - public String getName() { - return "jaxrs"; - } + sourceFolder = "src/gen/java"; - public String getHelp() { - return "Generates a Java JAXRS Server application."; - } + 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"); - public JaxRSServerCodegen() { - super.processOpts(); - - sourceFolder = "src/gen/java"; - - 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" ); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - additionalProperties.put("title", title); + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("title", title); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); - } - - - @Override - public void processOpts() { - super.processOpts(); - - supportingFiles.clear(); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); - supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); - supportingFiles.add(new SupportingFile("NotFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); - supportingFiles.add(new SupportingFile("web.mustache", - ("src/main/webapp/WEB-INF"), "web.xml")); - - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getTypeDeclaration(inner); + public CodegenType getTag() { + return CodegenType.SERVER; } - return super.getTypeDeclaration(p); - } - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - String basePath = resourcePath; - if(basePath.startsWith("/")) - basePath = basePath.substring(1); - int pos = basePath.indexOf("/"); - if(pos > 0) - basePath = basePath.substring(0, pos); - - if(basePath == "") - basePath = "default"; - else { - if(co.path.startsWith("/" + basePath)) - co.path = co.path.substring(("/" + basePath).length()); - co.subresourceOperation = !co.path.isEmpty(); + public String getName() { + return "jaxrs"; } - List opList = operations.get(basePath); - if(opList == null) { - opList = new ArrayList(); - operations.put(basePath, opList); - } - opList.add(co); - co.baseName = basePath; - } - public Map postProcessOperations(Map objs) { - Map operations = (Map)objs.get("operations"); - if(operations != null) { - List ops = (List) operations.get("operation"); - for(CodegenOperation operation : ops) { - if(operation.returnType == null) - operation.returnType = "Void"; - else if(operation.returnType.startsWith("List")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if(end > 0) { - operation.returnType = rt.substring("List<".length(), end); - operation.returnContainer = "List"; - } + public String getHelp() { + return "Generates a Java JAXRS Server application."; + } + + @Override + public void processOpts() { + super.processOpts(); + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("NotFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getTypeDeclaration(inner); } - else if(operation.returnType.startsWith("Map")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if(end > 0) { - operation.returnType = rt.substring("Map<".length(), end); - operation.returnContainer = "Map"; - } + return super.getTypeDeclaration(p); + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); } - else if(operation.returnType.startsWith("Set")) { - String rt = operation.returnType; - int end = rt.lastIndexOf(">"); - if(end > 0) { - operation.returnType = rt.substring("Set<".length(), end); - operation.returnContainer = "Set"; - } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); } - } - } - return objs; - } - @Override - public String apiFilename(String templateName, String tag) { - - 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"; - - 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"; - - String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); - if( output != null ){ - result = result.replace( apiFileFolder(), implFileFolder(output)); - } - } - else if( templateName.endsWith( "Service.mustache")) { - int ix = result.lastIndexOf('.'); - result = result.substring(0, ix) + "Service.java"; + if (basePath == "") { + basePath = "default"; + } else { + if (co.path.startsWith("/" + basePath)) { + co.path = co.path.substring(("/" + basePath).length()); + } + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; } - return result; - } + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.returnType == null) { + operation.returnType = "Void"; + } else if (operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("List<".length(), end); + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Map<".length(), end); + operation.returnContainer = "Map"; + } + } else if (operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Set<".length(), end); + operation.returnContainer = "Set"; + } + } + } + } + return objs; + } - private String implFileFolder(String output) { - return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); - } + @Override + public String apiFilename(String templateName, String tag) { - public boolean shouldOverwrite( String filename ){ + String result = super.apiFilename(templateName, tag); - return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.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)); + } + } 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)); + } + } else if (templateName.endsWith("Service.mustache")) { + int ix = result.lastIndexOf('.'); + result = result.substring(0, ix) + "Service.java"; + } + + return result; + } + + private String implFileFolder(String output) { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); + } + + public boolean shouldOverwrite(String filename) { + + return !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index eb80937bab7..28a0abfb6f7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.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,182 +8,193 @@ 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"; + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; - public String apiPackage() { - return "controllers"; - } + public NodeJSServerCodegen() { + super(); - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.SERVER; - } + // set the output folder here + outputFolder = "generated-code/nodejs"; - /** - * 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"; - } + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); - /** - * 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."; - } + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "controller.mustache", // the template to use + ".js"); // the extension for each file to write - public NodeJSServerCodegen() { - super(); + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "nodejs"; - // set the output folder here - outputFolder = "generated-code/nodejs"; + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet( + Arrays.asList( + "break", "case", "class", "catch", "const", "continue", "debugger", + "default", "delete", "do", "else", "export", "extends", "finally", + "for", "function", "if", "import", "in", "instanceof", "let", "new", + "return", "super", "switch", "this", "throw", "try", "typeof", "var", + "void", "while", "with", "yield") + ); - /** - * Models. You can write model files using the modelTemplateFiles map. - * if you want to create one template for file, you can do so here. - * for multiple files for model, just put another entry in the `modelTemplateFiles` with - * a different extension - */ - modelTemplateFiles.clear(); + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("serverPort", serverPort); - /** - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class - */ - apiTemplateFiles.put( - "controller.mustache", // the template to use - ".js"); // the extension for each file to write - - /** - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. - */ - templateDir = "nodejs"; - - /** - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "break", "case", "class", "catch", "const", "continue", "debugger", - "default", "delete", "do", "else", "export", "extends", "finally", - "for", "function", "if", "import", "in", "instanceof", "let", "new", - "return", "super", "switch", "this", "throw", "try", "typeof", "var", - "void", "while", "with", "yield") - ); - - /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ - additionalProperties.put("apiVersion", apiVersion); - additionalProperties.put("serverPort", serverPort); - - /** - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied - */ - // supportingFiles.add(new SupportingFile("controller.mustache", - // "controllers", - // "controller.js") - // ); - supportingFiles.add(new SupportingFile("swagger.mustache", - "api", - "swagger.json") - ); - supportingFiles.add(new SupportingFile("index.mustache", - "", - "index.js") - ); - supportingFiles.add(new SupportingFile("package.mustache", - "", - "package.json") - ); - if(System.getProperty("noservice") == null) { - apiTemplateFiles.put( - "service.mustache", // the template to use - "Service.js"); // the extension for each file to write - } - } - - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultController"; - return initialCaps(name); - } - - @Override - 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 - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); - } - - @Override - public Map postProcessOperations(Map objs) { - @SuppressWarnings("unchecked") - Map objectMap = (Map) objs.get("operations"); - @SuppressWarnings("unchecked") - List operations = (List) objectMap.get("operation"); - for(CodegenOperation operation : operations) { - operation.httpMethod = operation.httpMethod.toLowerCase(); - List params = operation.allParams; - if(params != null && params.size() == 0) - operation.allParams = null; - List responses = operation.responses; - if(responses != null) { - for(CodegenResponse resp : responses) { - if("0".equals(resp.code)) - resp.code = "default"; + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + // supportingFiles.add(new SupportingFile("controller.mustache", + // "controllers", + // "controller.js") + // ); + supportingFiles.add(new SupportingFile("swagger.mustache", + "api", + "swagger.json") + ); + supportingFiles.add(new SupportingFile("index.mustache", + "", + "index.js") + ); + supportingFiles.add(new SupportingFile("package.mustache", + "", + "package.json") + ); + if (System.getProperty("noservice") == null) { + apiTemplateFiles.put( + "service.mustache", // the template to use + "Service.js"); // the extension for each file to write } - } - if(operation.examples != null && !operation.examples.isEmpty()) { - // Leave application/json* items only - for (Iterator> it = operation.examples.iterator(); it.hasNext();) { - final Map example = it.next(); - final String contentType = example.get("contentType"); - if (contentType == null || !contentType.startsWith("application/json")) { - it.remove(); - } - } - } } - return objs; - } + + 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) { + return "DefaultController"; + } + return initialCaps(name); + } + + @Override + 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 + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public Map postProcessOperations(Map objs) { + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); + for (CodegenOperation operation : operations) { + operation.httpMethod = operation.httpMethod.toLowerCase(); + List params = operation.allParams; + if (params != null && params.size() == 0) { + operation.allParams = null; + } + List responses = operation.responses; + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { + resp.code = "default"; + } + } + } + if (operation.examples != null && !operation.examples.isEmpty()) { + // Leave application/json* items only + for (Iterator> it = operation.examples.iterator(); it.hasNext(); ) { + final Map example = it.next(); + final String contentType = example.get("contentType"); + if (contentType == null || !contentType.startsWith("application/json")) { + it.remove(); + } + } + } + } + return objs; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index d8de7597f1c..f0c0a8ffa80 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -1,347 +1,361 @@ 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 foundationClasses = new HashSet(); - protected String sourceFolder = "client"; - protected String classPrefix = "SWG"; - protected String projectName = "swaggerClient"; + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected String classPrefix = "SWG"; + protected String projectName = "swaggerClient"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "objc"; - } + public ObjcClientCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "objc"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + templateDir = "objc"; + modelPackage = ""; - public String getHelp() { - return "Generates an Objective-C client library."; - } + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "BOOL", + "int", + "NSString", + "NSObject", + "NSArray", + "NSNumber", + "NSDate", + "NSDictionary", + "NSMutableArray", + "NSMutableDictionary") + ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "NSNumber", + "NSString", + "NSObject", + "NSDate", + "bool", + "BOOL") + ); - public ObjcClientCodegen() { - super(); - outputFolder = "generated-code" + File.separator + "objc"; - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".m"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".m"); - templateDir = "objc"; - modelPackage = ""; + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + reservedWords = new HashSet( + Arrays.asList( + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly" + )); - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "BOOL", - "int", - "NSString", - "NSObject", - "NSArray", - "NSNumber", - "NSDate", - "NSDictionary", - "NSMutableArray", - "NSMutableDictionary") - ); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "NSNumber", - "NSString", - "NSObject", - "NSDate", - "bool", - "BOOL") - ); + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "BOOL"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - reservedWords = new HashSet( - Arrays.asList( - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly" - )); + importMapping = new HashMap(); - typeMapping = new HashMap(); - typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "BOOL"); - typeMapping.put("string", "NSString"); - typeMapping.put("integer", "NSNumber"); - typeMapping.put("int", "NSNumber"); - typeMapping.put("float", "NSNumber"); - typeMapping.put("long", "NSNumber"); - typeMapping.put("double", "NSNumber"); - typeMapping.put("array", "NSArray"); - typeMapping.put("map", "NSDictionary"); - typeMapping.put("number", "NSNumber"); - typeMapping.put("List", "NSArray"); - typeMapping.put("object", "NSObject"); + foundationClasses = new HashSet( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSDictionary") + ); - importMapping = new HashMap (); + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); - foundationClasses = new HashSet ( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSDictionary") - ); - - instantiationTypes.put("array", "NSMutableArray"); - instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.add(new CliOption("classPrefix", "prefix for generated classes")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile")); - } - - @Override - public void processOpts() { - super.processOpts(); - - if(additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String)additionalProperties.get("sourceFolder")); + cliOptions.add(new CliOption("classPrefix", "prefix for generated classes")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile")); } - - if(additionalProperties.containsKey("classPrefix")) { - this.setClassPrefix((String)additionalProperties.get("classPrefix")); - } - - if(additionalProperties.containsKey("projectName")) { - this.setProjectName((String)additionalProperties.get("projectName")); - } - else{ - additionalProperties.put("projectName", projectName); - } - - supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h")); - supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m")); - supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h")); - supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m")); - supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h")); - supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); - supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); - supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m")); - supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h")); - supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); - } - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map"); + public CodegenType getTag() { + return CodegenType.CLIENT; } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array"); + + public String getName() { + return "objc"; } - else - return null; - } - @Override - public String getTypeDeclaration(String name) { - if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) - return name; - else - return name + "*"; - } + public String getHelp() { + return "Generates an Objective-C client library."; + } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("sourceFolder")) { + this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + } + + if (additionalProperties.containsKey("classPrefix")) { + this.setClassPrefix((String) additionalProperties.get("classPrefix")); + } + + if (additionalProperties.containsKey("projectName")) { + this.setProjectName((String) additionalProperties.get("projectName")); + } else { + additionalProperties.put("projectName", projectName); + } + + supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h")); + supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m")); + supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h")); + supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m")); + supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h")); + supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); + supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); + supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m")); + supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h")); + supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); + } + + @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) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerType = getSwaggerType(inner); + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerType = getSwaggerType(inner); - // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray*' - if (languageSpecificPrimitives.contains(innerType)) - return getSwaggerType(p) + "*"; + // In this codition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray*' + 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*' - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - else { - String swaggerType = getSwaggerType(p); + // In this codition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + String innerTypeDeclaration = getTypeDeclaration(inner); - // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this codition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this codition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `SWGPet*' - else { - return swaggerType + "*"; - } - } - } + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } - @Override - public String toModelName(String type) { - type = type.replaceAll("[^0-9a-zA-Z_]", "_"); + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } else { + String swaggerType = getSwaggerType(p); - // language build-in classes - if(typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return camelize(type); + // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this codition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this codition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' + else { + return swaggerType + "*"; + } + } } - // custom classes - else { - return classPrefix + camelize(type); - } - } - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } + @Override + public String toModelName(String type) { + type = type.replaceAll("[^0-9a-zA-Z_]", "_"); + + // language build-in classes + if (typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return camelize(type); + } + // custom classes + else { + return classPrefix + camelize(type); + } + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } @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())) - return name; - else - return modelPackage() + "." + name; - } + public String toModelImport(String name) { + if ("".equals(modelPackage())) { + return name; + } else { + return modelPackage() + "." + name; + } + } - @Override - public String toDefaultValue(Property p) { - return null; - } + @Override + public String toDefaultValue(Property p) { + return null; + } - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder; - } + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; + } - @Override - public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder; - } + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; + } - @Override - public String toApiName(String name) { - return classPrefix + camelize(name) + "Api"; - } + @Override + public String toApiName(String name) { + return classPrefix + camelize(name) + "Api"; + } - public String toApiFilename(String name) { - return classPrefix + camelize(name) + "Api"; - } + public String toApiFilename(String name) { + return classPrefix + camelize(name) + "Api"; + } - @Override - public String toVarName(String name) { - // replace non-word characters to `_` - // e.g. `created-at` to `created_at` - name = name.replaceAll("[^a-zA-Z0-9_]","_"); + @Override + public String toVarName(String name) { + // replace non-word characters to `_` + // e.g. `created-at` to `created_at` + name = name.replaceAll("[^a-zA-Z0-9_]", "_"); - // if it's all upper case, do noting - if (name.matches("^[A-Z_]$")) - return name; + // if it's all upper case, do noting + if (name.matches("^[A-Z_]$")) { + return name; + } - // camelize (lower first character) the variable name - // e.g. `pet_id` to `petId` - name = camelize(name, true); + // 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.*")) - name = escapeReservedWord(name); + // for reserved word or word starting with number, prepend `_` + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + return name; + } - public String escapeReservedWord(String name) { - return "_" + name; - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + public String escapeReservedWord(String name) { + return "_" + name; + } - return camelize(operationId, true); - } + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } + return camelize(operationId, true); + } - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } - public void setProjectName(String projectName) { - this.projectName = projectName; - } + public void setClassPrefix(String classPrefix) { + this.classPrefix = classPrefix; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 4e381b112f7..1b0da2698e2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -1,200 +1,208 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String invokerPackage = "SwaggerClient"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public PerlClientCodegen() { + super(); + modelPackage = File.separatorChar + "Object"; + outputFolder = "generated-code" + File.separatorChar + "perl"; + modelTemplateFiles.put("object.mustache", ".pm"); + apiTemplateFiles.put("api.mustache", ".pm"); + templateDir = "perl"; - public String getName() { - return "perl"; - } + typeMapping.clear(); + languageSpecificPrimitives.clear(); - public String getHelp() { - return "Generates a Perl client library."; - } + reservedWords = new HashSet( + Arrays.asList( + "else", "lock", "qw", + "__END__", "elsif", "lt", "qx", + "__FILE__", "eq", "m", "s", + "__LINE__", "exp", "ne", "sub", + "__PACKAGE__", "for", "no", "tr", + "and", "foreach", "or", "unless", + "cmp", "ge", "package", "until", + "continue", "gt", "q", "while", + "CORE", "if", "qq", "xor", + "do", "le", "qr", "y" + ) + ); - public PerlClientCodegen() { - super(); - modelPackage = File.separatorChar + "Object"; - outputFolder = "generated-code" + File.separatorChar + "perl"; - modelTemplateFiles.put("object.mustache", ".pm"); - apiTemplateFiles.put("api.mustache", ".pm"); - templateDir = "perl"; + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - typeMapping.clear(); - languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("double"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("boolean"); + languageSpecificPrimitives.add("DateTime"); + languageSpecificPrimitives.add("ARRAY"); + languageSpecificPrimitives.add("HASH"); + languageSpecificPrimitives.add("object"); - reservedWords = new HashSet ( - Arrays.asList( - "else", "lock", "qw", - "__END__", "elsif", "lt", "qx", - "__FILE__", "eq", "m", "s", - "__LINE__", "exp", "ne", "sub", - "__PACKAGE__", "for", "no", "tr", - "and", "foreach", "or", "unless", - "cmp", "ge", "package", "until", - "continue", "gt", "q", "while", - "CORE", "if", "qq", "xor", - "do", "le", "qr", "y" - ) - ); + typeMapping.put("integer", "int"); + typeMapping.put("long", "int"); + typeMapping.put("float", "double"); + typeMapping.put("double", "double"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("date", "DateTime"); + typeMapping.put("dateTime", "DateTime"); + typeMapping.put("password", "string"); + typeMapping.put("array", "ARRAY"); + typeMapping.put("map", "HASH"); + typeMapping.put("object", "object"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("double"); - languageSpecificPrimitives.add("string"); - languageSpecificPrimitives.add("boolean"); - languageSpecificPrimitives.add("DateTime"); - languageSpecificPrimitives.add("ARRAY"); - languageSpecificPrimitives.add("HASH"); - languageSpecificPrimitives.add("object"); - - typeMapping.put("integer", "int"); - typeMapping.put("long", "int"); - typeMapping.put("float", "double"); - typeMapping.put("double", "double"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("date", "DateTime"); - typeMapping.put("dateTime", "DateTime"); - typeMapping.put("password", "string"); - typeMapping.put("array", "ARRAY"); - typeMapping.put("map", "HASH"); - typeMapping.put("object", "object"); - - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm")); - supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm")); - supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar); - } - - public String modelFileFolder() { - return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm")); + supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm")); + supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) { + 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; + } + + @Override + public String apiFileFolder() { + return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar); + } + + public String modelFileFolder() { + return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } return type; - } } - else - type = swaggerType; - if(type == null) - return null; - return type; - } - public String toDefaultValue(Property p) { - return "null"; - } - - - @Override - public String toVarName(String name) { - // parameter name starting with number won't compile - // need to escape it by appending _ at the beginning - if (name.matches("^[0-9]")) { - name = "_" + name; + public String toDefaultValue(Property p) { + return "null"; } - - // return the name in underscore style - // PhoneNumber => phone_number - return underscore(name); - } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword - if(reservedWords.contains(name)) - escapeReservedWord(name); // e.g. return => _return + @Override + public String toVarName(String name) { + // parameter name starting with number won't compile + // need to escape it by appending _ at the beginning + if (name.matches("^[0-9]")) { + name = "_" + name; + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + // return the name in underscore style + // PhoneNumber => phone_number + return underscore(name); + } - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword + if (reservedWords.contains(name)) { + escapeReservedWord(name); // e.g. return => _return + } - // e.g. phone_number_api.rb => PhoneNumberApi.rb - return camelize(name) + "Api"; - } + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - return underscore(operationId); - } + // e.g. phone_number_api.rb => PhoneNumberApi.rb + return camelize(name) + "Api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(operationId); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 340e58ab106..10c03fe4381 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -1,184 +1,190 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public PhpClientCodegen() { + super(); - public String getName() { - return "php"; - } + invokerPackage = camelize("SwaggerClient"); - public String getHelp() { - return "Generates a PHP client library."; - } + String packagePath = invokerPackage + "-php"; - public PhpClientCodegen() { - super(); + modelPackage = packagePath + "/lib/models"; + apiPackage = packagePath + "/lib"; + outputFolder = "generated-code/php"; + modelTemplateFiles.put("model.mustache", ".php"); + apiTemplateFiles.put("api.mustache", ".php"); + templateDir = "php"; - invokerPackage = camelize("SwaggerClient"); + reservedWords = new HashSet( + 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") + ); - String packagePath = invokerPackage + "-php"; + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - modelPackage = packagePath + "/lib/models"; - apiPackage = packagePath + "/lib"; - outputFolder = "generated-code/php"; - modelTemplateFiles.put("model.mustache", ".php"); - apiTemplateFiles.put("api.mustache", ".php"); - templateDir = "php"; + // ref: http://php.net/manual/en/language.types.intro.php + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "boolean", + "int", + "integer", + "double", + "float", + "string", + "object", + "DateTime", + "mixed", + "number") + ); - reservedWords = new HashSet ( - 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") - ); + instantiationTypes.put("array", "array"); + instantiationTypes.put("map", "map"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types + typeMapping = new HashMap(); + typeMapping.put("integer", "int"); + typeMapping.put("long", "int"); + typeMapping.put("float", "float"); + typeMapping.put("double", "double"); + typeMapping.put("string", "string"); + typeMapping.put("byte", "int"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("date", "DateTime"); + typeMapping.put("datetime", "DateTime"); + typeMapping.put("file", "string"); + typeMapping.put("map", "map"); + typeMapping.put("array", "array"); + typeMapping.put("list", "array"); + typeMapping.put("object", "object"); - // ref: http://php.net/manual/en/language.types.intro.php - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "boolean", - "int", - "integer", - "double", - "float", - "string", - "object", - "DateTime", - "mixed", - "number") - ); - - instantiationTypes.put("array", "array"); - instantiationTypes.put("map", "map"); - - // ref: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#data-types - typeMapping = new HashMap(); - typeMapping.put("integer", "int"); - typeMapping.put("long", "int"); - typeMapping.put("float", "float"); - typeMapping.put("double", "double"); - typeMapping.put("string", "string"); - typeMapping.put("byte", "int"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("date", "DateTime"); - typeMapping.put("datetime", "DateTime"); - typeMapping.put("file", "string"); - typeMapping.put("map", "map"); - typeMapping.put("array", "array"); - typeMapping.put("list", "array"); - typeMapping.put("object", "object"); - - supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php")); - supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); - } - - public String modelFileFolder() { - return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json")); + supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php")); + supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) { - return type; - } - else if (instantiationTypes.containsKey(type)) { - return type; - } + public String getName() { + return "php"; } - else - type = swaggerType; - if(type == null) - return null; - return toModelName(type); - } - public String toDefaultValue(Property p) { - return "null"; - } - - - @Override - public String toVarName(String name) { - // parameter name starting with number won't compile - // need to escape it by appending _ at the beginning - if (name.matches("^[0-9]")) { - name = "_" + name; + public String getHelp() { + return "Generates a PHP client library."; } - - // return the name in underscore style - // PhoneNumber => phone_number - return underscore(name); - } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword - if(reservedWords.contains(name)) - escapeReservedWord(name); // e.g. return => _return + @Override + public String apiFileFolder() { + return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + public String modelFileFolder() { + return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar); + } - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } else if (instantiationTypes.containsKey(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } + return toModelName(type); + } + + public String toDefaultValue(Property p) { + return "null"; + } + + + @Override + public String toVarName(String name) { + // parameter name starting with number won't compile + // need to escape it by appending _ at the beginning + if (name.matches("^[0-9]")) { + name = "_" + name; + } + + // return the name in underscore style + // PhoneNumber => phone_number + return underscore(name); + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword + if (reservedWords.contains(name)) { + escapeReservedWord(name); // e.g. return => _return + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java index 04f3cd6598d..4911ca06850 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java @@ -1,198 +1,210 @@ 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"; + String module = "client"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public Python3ClientCodegen() { + super(); + outputFolder = "generated-code/python3"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python3"; - public String getName() { - return "python3"; - } + apiPackage = module; + modelPackage = module + ".models"; - public String getHelp() { - return "Generates a Python3 client library."; - } + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + //languageSpecificPrimitives.add("long"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); - public Python3ClientCodegen() { - super(); - outputFolder = "generated-code/python3"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python3"; + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "int"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "map"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "datetime"); - apiPackage = module; - modelPackage = module + ".models"; + // from https://docs.python.org/release/2.5.4/ref/keywords.html + reservedWords = new HashSet( + Arrays.asList( + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try")); - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - //languageSpecificPrimitives.add("long"); - languageSpecificPrimitives.add("list"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("str"); - languageSpecificPrimitives.add("datetime"); - - typeMapping.clear(); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("long", "int"); - typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "map"); - typeMapping.put("boolean", "bool"); - typeMapping.put("string", "str"); - typeMapping.put("date", "datetime"); - - // from https://docs.python.org/release/2.5.4/ref/keywords.html - reservedWords = new HashSet ( - Arrays.asList( - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try")); - - //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py")); - supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) { + public String getName() { + return "python3"; + } + + public String getHelp() { + return "Generates a Python3 client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } return type; - } } - else - type = swaggerType; - return type; - } - public String toDefaultValue(Property p) { - // TODO: Support Python def value - return "null"; - } + public String toDefaultValue(Property p) { + // TODO: Support Python def value + return "null"; + } - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) - name = name.toLowerCase(); + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } - // camelize (lower first character) the variable name - // petId => pet_id - name = underscore(name); + // 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.*")) - name = escapeReservedWord(name); + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } + return name; + } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } - @Override - public String toModelFilename(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + 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 - return underscore(name); - } + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } + @Override + public String toApiName(String name) { + 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) - return "default_api"; - return underscore(name) + "_api"; - } + @Override + public String toApiVarName(String name) { + 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)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - return underscore(operationId); - } + return underscore(operationId); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index ba3574d9f67..9553f4ad133 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -1,215 +1,227 @@ 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; + protected String module = "SwaggerPetstore"; + protected String invokerPackage; + protected String eggPackage; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public PythonClientCodegen() { + super(); - public String getName() { - return "python"; - } + eggPackage = module + "-python"; - public String getHelp() { - return "Generates a Python client library."; - } + invokerPackage = eggPackage + File.separatorChar + module; - public PythonClientCodegen() { - super(); + outputFolder = "generated-code" + File.separatorChar + "python"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python"; - eggPackage = module + "-python"; - - invokerPackage = eggPackage + File.separatorChar + module; + apiPackage = invokerPackage + File.separatorChar + "apis"; + modelPackage = invokerPackage + File.separatorChar + "models"; - outputFolder = "generated-code" + File.separatorChar + "python"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python"; + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); - apiPackage = invokerPackage + File.separatorChar + "apis"; - modelPackage = invokerPackage + File.separatorChar + "models"; + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "int"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "map"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "datetime"); - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("list"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("str"); - languageSpecificPrimitives.add("datetime"); + // from https://docs.python.org/release/2.5.4/ref/keywords.html + reservedWords = new HashSet( + Arrays.asList( + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try")); - typeMapping.clear(); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("long", "int"); - typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "map"); - typeMapping.put("boolean", "bool"); - typeMapping.put("string", "str"); - typeMapping.put("date", "datetime"); + additionalProperties.put("module", module); - // from https://docs.python.org/release/2.5.4/ref/keywords.html - reservedWords = new HashSet ( - Arrays.asList( - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try")); - - additionalProperties.put("module", module); - - supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); - supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); - supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); - supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); - supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); - supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); + supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); + supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); + supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); + supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) { + 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; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } return type; - } - } else { - type = toModelName(swaggerType); } - return type; - } - public String toDefaultValue(Property p) { - // TODO: Support Python def value - return "null"; - } + public String toDefaultValue(Property p) { + // TODO: Support Python def value + return "null"; + } - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) - name = name.toLowerCase(); + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } - // underscore the variable name - // petId => pet_id - name = underscore(dropDots(name)); + // 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.*")) - name = escapeReservedWord(name); + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } + return name; + } - private static String dropDots(String str) { - return str.replaceAll("\\.", "_"); - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } - @Override - public String toModelFilename(String name) { - // model name cannot use reserved keyword, e.g. return - 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 + return underscore(dropDots(name)); + } - // underscore the model file name - // PhoneNumber => phone_number - return underscore(dropDots(name)); - } + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } - @Override - public String toApiName(String name) { - 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) { + return "default_api"; + } + return underscore(name) + "_api"; + } - @Override - public String toApiVarName(String name) { - 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)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - - return underscore(operationId); - } + return underscore(operationId); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 2b3962fb528..ff58dbd9440 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -1,308 +1,324 @@ 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 Set foundationClasses = new HashSet(); + protected final String PREFIX = "SWG"; + protected Set foundationClasses = new HashSet(); + // source folder where to write the files + protected String sourceFolder = "client"; + protected String apiVersion = "1.0.0"; + protected Map namespaces = new HashMap(); + protected Set systemIncludes = new HashSet(); - // source folder where to write the files - protected String sourceFolder = "client"; - protected String apiVersion = "1.0.0"; - protected final String PREFIX = "SWG"; - protected Map namespaces = new HashMap(); - protected Set systemIncludes = new HashSet(); + public Qt5CPPGenerator() { + super(); - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } + // set the output folder here + outputFolder = "generated-code/qt5cpp"; - /** - * 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"; - } + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.put( + "model-header.mustache", + ".h"); - /** - * 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."; - } + modelTemplateFiles.put( + "model-body.mustache", + ".cpp"); - public Qt5CPPGenerator() { - super(); + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api-header.mustache", // the template to use + ".h"); // the extension for each file to write - // set the output folder here - outputFolder = "generated-code/qt5cpp"; + apiTemplateFiles.put( + "api-body.mustache", // the template to use + ".cpp"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + templateDir = "qt5cpp"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties().put("prefix", PREFIX); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "qint32", + "qint64") + ); + + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h")); + supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp")); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); + supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + + super.typeMapping = new HashMap(); + + typeMapping.put("Date", "QDate"); + typeMapping.put("DateTime", "QDateTime"); + typeMapping.put("string", "QString"); + typeMapping.put("integer", "qint32"); + typeMapping.put("long", "qint64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "QList"); + typeMapping.put("map", "QMap"); + typeMapping.put("file", "SWGHttpRequestInputFileElement"); + typeMapping.put("object", PREFIX + "Object"); + + importMapping = new HashMap(); + + importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\""); + + namespaces = new HashMap(); + + foundationClasses.add("QString"); + + systemIncludes.add("QString"); + systemIncludes.add("QList"); + } /** - * Models. You can write model files using the modelTemplateFiles map. - * if you want to create one template for file, you can do so here. - * for multiple files for model, just put another entry in the `modelTemplateFiles` with - * a different extension + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType */ - modelTemplateFiles.put( - "model-header.mustache", - ".h"); - - modelTemplateFiles.put( - "model-body.mustache", - ".cpp"); + public CodegenType getTag() { + return CodegenType.CLIENT; + } /** - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class + * 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 */ - apiTemplateFiles.put( - "api-header.mustache", // the template to use - ".h"); // the extension for each file to write - - apiTemplateFiles.put( - "api-body.mustache", // the template to use - ".cpp"); // the extension for each file to write + public String getName() { + return "qt5cpp"; + } /** - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message */ - templateDir = "qt5cpp"; + public String getHelp() { + return "Generates a qt5 C++ client library."; + } + + @Override + public String toModelImport(String name) { + if (namespaces.containsKey(name)) { + return "using " + namespaces.get(name) + ";"; + } else if (systemIncludes.contains(name)) { + return "#include <" + name + ">"; + } + return "#include \"" + name + ".h\""; + } /** - * Reserved words. Override this with reserved words specific to your language + * 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 + * + * @return the escaped term */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") - ); + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated */ - additionalProperties.put("apiVersion", apiVersion); - additionalProperties().put("prefix", PREFIX); + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "bool", - "qint32", - "qint64") - ); - - supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); - supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); - supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h")); - supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp")); - supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); - supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); - - super.typeMapping = new HashMap(); - - typeMapping.put("Date", "QDate"); - typeMapping.put("DateTime", "QDateTime"); - typeMapping.put("string", "QString"); - typeMapping.put("integer", "qint32"); - typeMapping.put("long", "qint64"); - typeMapping.put("boolean", "bool"); - typeMapping.put("array", "QList"); - typeMapping.put("map", "QMap"); - typeMapping.put("file", "SWGHttpRequestInputFileElement"); - typeMapping.put("object", PREFIX + "Object"); - - importMapping = new HashMap(); - - importMapping.put("SWGHttpRequestInputFileElement", "#include \"" + PREFIX + "HttpRequest.h\""); - - namespaces = new HashMap (); - - foundationClasses.add("QString"); - - systemIncludes.add("QString"); - systemIncludes.add("QList"); - } - - @Override - public String toModelImport(String name) { - if(namespaces.containsKey(name)) { - return "using " + namespaces.get(name) + ";"; + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } - else if(systemIncludes.contains(name)) { - return "#include <" + name + ">"; + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); } - return "#include \"" + name + ".h\""; - } - /** - * 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 - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - /** - * Location to write model files. You can use the modelPackage() as defined when the class is - * instantiated - */ - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String toModelFilename(String name) { - return PREFIX + initialCaps(name); - } - - @Override - public String toApiFilename(String name) { - return PREFIX + initialCaps(name) + "Api"; - } - - /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types - * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*"; + @Override + public String toApiFilename(String name) { + return PREFIX + initialCaps(name) + "Api"; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "*"; - } - if(foundationClasses.contains(swaggerType)) - return swaggerType + "*"; - else if(languageSpecificPrimitives.contains(swaggerType)) - return toModelName(swaggerType); - else - return swaggerType + "*"; - } - @Override - public String toDefaultValue(Property p) { - if(p instanceof StringProperty) - return "new QString(\"\")"; - else if (p instanceof BooleanProperty) - return "false"; - else if(p instanceof DateProperty) - return "NULL"; - else if(p instanceof DateTimeProperty) - return "NULL"; - else if (p instanceof DoubleProperty) - return "0.0"; - else if (p instanceof FloatProperty) - return "0.0f"; - else if (p instanceof IntegerProperty) - return "0"; - else if (p instanceof LongProperty) - return "0L"; - else if (p instanceof DecimalProperty) - return "0.0"; - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new QMap()"; + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">*"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "*"; + } + if (foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } else if (languageSpecificPrimitives.contains(swaggerType)) { + return toModelName(swaggerType); + } else { + return swaggerType + "*"; + } } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - if(!languageSpecificPrimitives.contains(inner)) { - inner += "*"; - } - return "new QList<" + inner + ">()"; + + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "new QString(\"\")"; + } else if (p instanceof BooleanProperty) { + return "false"; + } else if (p instanceof DateProperty) { + return "NULL"; + } else if (p instanceof DateTimeProperty) { + return "NULL"; + } else if (p instanceof DoubleProperty) { + return "0.0"; + } else if (p instanceof FloatProperty) { + return "0.0f"; + } else if (p instanceof IntegerProperty) { + return "0"; + } else if (p instanceof LongProperty) { + return "0L"; + } else if (p instanceof DecimalProperty) { + return "0.0"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new QMap()"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + if (!languageSpecificPrimitives.contains(inner)) { + inner += "*"; + } + return "new QList<" + inner + ">()"; + } + // else + if (p instanceof RefProperty) { + RefProperty rp = (RefProperty) p; + return "new " + toModelName(rp.getSimpleRef()) + "()"; + } + return "NULL"; } - // else - if(p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; - } - return "NULL"; - } - /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + if (foundationClasses.contains(type)) { + return type; + } + } else { + type = swaggerType; + } return toModelName(type); - if(foundationClasses.contains(type)) - return type; } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String toModelName(String type) { - if(typeMapping.keySet().contains(type) || - typeMapping.values().contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { - return type; + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || + typeMapping.values().contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return type; + } else { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } } - else { - return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); - } - } - @Override - public String toApiName(String type) { - return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; - } + @Override + public String toApiName(String type) { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java index 1b9bf41aa45..e043c68baf9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java @@ -1,190 +1,202 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-java-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-java-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public RetrofitClientCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "retrofit"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; - public String getName() { - return "retrofit"; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); - public String getHelp() { - return "Generates a Retrofit client library."; - } + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - public RetrofitClientCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "retrofit"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("service.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java")); - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - ); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("service.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize (lower 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.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String getName() { + return "retrofit"; + } + + public String getHelp() { + return "Generates a Retrofit client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize (lower 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.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - 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)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - - return camelize(operationId, true); - } - - public Map postProcessOperations(Map objs) { - Map operations = (Map)objs.get("operations"); - if(operations != null) { - List ops = (List) operations.get("operation"); - for(CodegenOperation operation : ops) { - if (operation.hasConsumes == Boolean.TRUE) { - Map firstType = operation.consumes.get(0); - if (firstType != null) { - if ("multipart/form-data".equals(firstType.get("mediaType"))) { - operation.isMultipart = Boolean.TRUE; - } - } + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - if(operation.returnType == null) { - operation.returnType = "Void"; - } - } + + return camelize(operationId, true); + } + + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.hasConsumes == Boolean.TRUE) { + Map firstType = operation.consumes.get(0); + if (firstType != null) { + if ("multipart/form-data".equals(firstType.get("mediaType"))) { + operation.isMultipart = Boolean.TRUE; + } + } + } + if (operation.returnType == null) { + operation.returnType = "Void"; + } + } + } + return objs; } - return objs; - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 941b4fa64ad..01fe6c6eed4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -1,220 +1,231 @@ 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"; + protected String gemName = "swagger_client"; + protected String moduleName = null; + protected String libFolder = "lib"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public RubyClientCodegen() { + super(); + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; + outputFolder = "generated-code" + File.separatorChar + "ruby"; + modelTemplateFiles.put("model.mustache", ".rb"); + apiTemplateFiles.put("api.mustache", ".rb"); + templateDir = "ruby"; - public String getName() { - return "ruby"; - } + typeMapping.clear(); + languageSpecificPrimitives.clear(); - public String getHelp() { - return "Generates a Ruby client library."; - } + reservedWords = new HashSet( + Arrays.asList( + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") + ); - /** - * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". - */ - public String generateModuleName() { - return camelize(gemName.replaceAll("[^\\w]+", "_")); - } + additionalProperties.put("gemName", gemName); + additionalProperties.put("moduleName", moduleName); - public RubyClientCodegen() { - super(); - moduleName = generateModuleName(); - modelPackage = gemName + "/models"; - apiPackage = gemName + "/api"; - outputFolder = "generated-code" + File.separatorChar + "ruby"; - modelTemplateFiles.put("model.mustache", ".rb"); - apiTemplateFiles.put("api.mustache", ".rb"); - templateDir = "ruby"; + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); - typeMapping.clear(); - languageSpecificPrimitives.clear(); + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); - reservedWords = new HashSet ( - Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", - "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", - "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", - "if", "not", "return", "undef", "yield") - ); - - additionalProperties.put("gemName", gemName); - additionalProperties.put("moduleName", moduleName); - - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("array"); - languageSpecificPrimitives.add("map"); - languageSpecificPrimitives.add("string"); - languageSpecificPrimitives.add("DateTime"); - - typeMapping.put("long", "int"); - typeMapping.put("integer", "int"); - typeMapping.put("Array", "array"); - typeMapping.put("String", "string"); - typeMapping.put("List", "array"); - typeMapping.put("map", "map"); - - String baseFolder = "lib" + File.separatorChar + gemName; - String swaggerFolder = baseFolder + File.separatorChar + "swagger"; - String modelFolder = baseFolder + File.separatorChar + "models"; - supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); - supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb")); - supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); - supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb")); - supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; - } - - public String modelFileFolder() { - return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + String baseFolder = "lib" + File.separatorChar + gemName; + String swaggerFolder = baseFolder + File.separatorChar + "swagger"; + String modelFolder = baseFolder + File.separatorChar + "models"; + supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); + supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); + supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb")); + supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb")); + supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) { + 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; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; + } + + public String modelFileFolder() { + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + if (type == null) { + return null; + } return type; - } } - else - type = swaggerType; - if(type == null) - return null; - return type; - } - public String toDefaultValue(Property p) { - return "null"; - } + public String toDefaultValue(Property p) { + return "null"; + } - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) - name = name.toLowerCase(); + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } - // camelize (lower first character) the variable name - // petId => pet_id - name = underscore(name); + // 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.*")) - name = escapeReservedWord(name); + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } - return name; - } + return name; + } - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } - @Override - public String toModelFilename(String name) { - // model name cannot use reserved keyword, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + 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 - return underscore(name); - } + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - return underscore(operationId); - } + return underscore(operationId); + } - @Override - public String toModelImport(String name) { - return modelPackage() + "/" + toModelFilename(name); - } + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } - @Override - public String toApiImport(String name) { - return apiPackage() + "/" + toApiFilename(name); - } + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 1d1dc579d78..d8c143aad1d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -1,203 +1,217 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-scala-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; - protected String authScheme = ""; - protected boolean authPreemptive = false; - protected boolean asyncHttpClient = !authScheme.isEmpty(); + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-scala-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String authScheme = ""; + protected boolean authPreemptive = false; + protected boolean asyncHttpClient = !authScheme.isEmpty(); - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "scala"; - } + public ScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "scala"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; - public String getHelp() { - return "Generates a Scala client library."; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); - public ScalaClientCodegen() { - super(); - outputFolder = "generated-code/scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scala"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("asyncHttpClient", asyncHttpClient); + additionalProperties.put("authScheme", authScheme); + additionalProperties.put("authPreemptive", authPreemptive); - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") - ); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - additionalProperties.put("asyncHttpClient", asyncHttpClient); - additionalProperties.put("authScheme", authScheme); - additionalProperties.put("authPreemptive", authPreemptive); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("array", "List"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); - importMapping.put("DateTime", "org.joda.time.DateTime"); - importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); - - typeMapping = new HashMap(); - typeMapping.put("enum", "NSString"); - typeMapping.put("array", "List"); - typeMapping.put("set", "Set"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("string", "String"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Long"); - typeMapping.put("float", "Float"); - typeMapping.put("byte", "Byte"); - typeMapping.put("short", "Short"); - typeMapping.put("char", "Char"); - typeMapping.put("long", "Long"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "Any"); - typeMapping.put("file", "File"); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Map") - ); - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "HashMap"); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "HashMap"); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public CodegenType getTag() { + return CodegenType.CLIENT; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String getName() { + return "scala"; + } + + public String getHelp() { + return "Generates a Scala client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map") + "[String, " + inner + "]"; + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else { + return null; + } } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; + + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "null"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + return "null"; + } else if (p instanceof FloatProperty) { + return "null"; + } else if (p instanceof IntegerProperty) { + return "null"; + } else if (p instanceof LongProperty) { + return "null"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } else { + return "null"; + } } - else - return null; - } - public String toDefaultValue(Property p) { - if(p instanceof StringProperty) - return "null"; - else if (p instanceof BooleanProperty) - return "null"; - else if(p instanceof DateProperty) - return "null"; - else if(p instanceof DateTimeProperty) - return "null"; - else if (p instanceof DoubleProperty) - return "null"; - else if (p instanceof FloatProperty) - return "null"; - else if (p instanceof IntegerProperty) - return "null"; - else if (p instanceof LongProperty) - return "null"; - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap[String, " + inner + "]() "; + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(operationId, true); } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; - } - else - return "null"; - } - - - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if(reservedWords.contains(operationId)) - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - - return camelize(operationId, true); - } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index 30b96ca5aa7..d6b0f78253a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -1,178 +1,187 @@ 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"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; - public CodegenType getTag() { - return CodegenType.SERVER; - } + public ScalatraServerCodegen() { + super(); + outputFolder = "generated-code/scalatra"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "scalatra"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.client.model"; - public String getName() { - return "scalatra"; - } + reservedWords = new HashSet( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); - public String getHelp() { - return "Generates a Scala server application with Scalatra."; - } + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); - public ScalatraServerCodegen() { - super(); - outputFolder = "generated-code/scalatra"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scalatra"; - apiPackage = "com.wordnik.client.api"; - modelPackage = "com.wordnik.client.model"; + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); - reservedWords = new HashSet ( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - ); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "http://swagger.io"); + additionalProperties.put("infoEmail", "apiteam@swagger.io"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - defaultIncludes = new HashSet( - Arrays.asList("double", - "Int", - "Long", - "Float", - "Double", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "List", - "Set", - "Map") - ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); + supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); + supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala")); + supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); + supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); + supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); + supportingFiles.add(new SupportingFile("sbt", "", "sbt")); - typeMapping.put("integer", "Int"); - typeMapping.put("long", "Long"); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); - additionalProperties.put("appName", "Swagger Sample"); - additionalProperties.put("appName", "Swagger Sample"); - additionalProperties.put("appDescription", "A sample swagger server"); - additionalProperties.put("infoUrl", "http://swagger.io"); - additionalProperties.put("infoEmail", "apiteam@swagger.io"); - additionalProperties.put("licenseInfo", "All rights reserved"); - additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); - supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); - supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala")); - supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); - supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); - supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); - supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); - supportingFiles.add(new SupportingFile("sbt", "", "sbt")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - - importMapping = new HashMap (); - importMapping.put("BigDecimal", "java.math.BigDecimal"); - importMapping.put("UUID", "java.util.UUID"); - importMapping.put("File", "java.io.File"); - importMapping.put("Date", "java.util.Date"); - importMapping.put("Timestamp", "java.sql.Timestamp"); - importMapping.put("Map", "java.util.Map"); - importMapping.put("HashMap", "java.util.HashMap"); - importMapping.put("Array", "java.util.List"); - importMapping.put("ArrayList", "java.util.ArrayList"); - importMapping.put("DateTime", "org.joda.time.DateTime"); - importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); - importMapping.put("LocalDate", "org.joda.time.LocalDate"); - importMapping.put("LocalTime", "org.joda.time.LocalTime"); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - List operationList = (List) operations.get("operation"); - for(CodegenOperation op: operationList) { - op.httpMethod = op.httpMethod.toLowerCase(); + importMapping = new HashMap(); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("Array", "java.util.List"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); + importMapping.put("LocalDate", "org.joda.time.LocalDate"); + importMapping.put("LocalTime", "org.joda.time.LocalTime"); } - return objs; - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + public CodegenType getTag() { + return CodegenType.SERVER; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getName() { + return "scalatra"; } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + public String getHelp() { + return "Generates a Scala server application with Scalatra."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 9120315ab3a..a90533a3614 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -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"; @@ -51,17 +46,29 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen additionalProperties.put("configPackage", configPackage); languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") ); } + 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> 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 opList = operations.get(basePath); - if(opList == null) { + if (opList == null) { opList = new ArrayList(); operations.put(basePath, opList); } @@ -133,32 +142,30 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen } public Map postProcessOperations(Map objs) { - Map operations = (Map)objs.get("operations"); - if(operations != null) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { List ops = (List) 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"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index 3d1a8f6b62c..bfee70f1732 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -1,76 +1,77 @@ 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 { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "docs"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "docs"; - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } + public StaticDocCodegen() { + super(); + outputFolder = "docs"; + modelTemplateFiles.put("model.mustache", ".html"); + apiTemplateFiles.put("operation.mustache", ".html"); + templateDir = "swagger-static"; - public String getName() { - return "dynamic-html"; - } + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - public String getHelp() { - return "Generates a dynamic HTML site."; - } + supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css", + outputFolder + "/assets/css", "bootstrap-responsive.css")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap.css", + outputFolder + "/assets/css", "bootstrap.css")); + supportingFiles.add(new SupportingFile("assets/css/style.css", + outputFolder + "/assets/css", "style.css")); + supportingFiles.add(new SupportingFile("assets/images/logo.png", + outputFolder + "/assets/images", "logo.png")); + supportingFiles.add(new SupportingFile("assets/js/bootstrap.js", + outputFolder + "/assets/js", "bootstrap.js")); + supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js", + outputFolder + "/assets/js", "jquery-1.8.3.min.js")); + supportingFiles.add(new SupportingFile("assets/js/main.js", + outputFolder + "/assets/js", "main.js")); + supportingFiles.add(new SupportingFile("index.mustache", + outputFolder, "index.html")); - public StaticDocCodegen() { - super(); - outputFolder = "docs"; - modelTemplateFiles.put("model.mustache", ".html"); - apiTemplateFiles.put("operation.mustache", ".html"); - templateDir = "swagger-static"; + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + } - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } - supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); - supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); - supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css", - outputFolder + "/assets/css", "bootstrap-responsive.css")); - supportingFiles.add(new SupportingFile("assets/css/bootstrap.css", - outputFolder + "/assets/css", "bootstrap.css")); - supportingFiles.add(new SupportingFile("assets/css/style.css", - outputFolder + "/assets/css", "style.css")); - supportingFiles.add(new SupportingFile("assets/images/logo.png", - outputFolder + "/assets/images", "logo.png")); - supportingFiles.add(new SupportingFile("assets/js/bootstrap.js", - outputFolder + "/assets/js", "bootstrap.js")); - supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js", - outputFolder + "/assets/js", "jquery-1.8.3.min.js")); - supportingFiles.add(new SupportingFile("assets/js/main.js", - outputFolder + "/assets/js", "main.js")); - supportingFiles.add(new SupportingFile("index.mustache", - outputFolder, "index.html")); + public String getName() { + return "dynamic-html"; + } - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - } + public String getHelp() { + return "Generates a dynamic HTML site."; + } - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + "operations"; - } + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + "operations"; + } - public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + "models"; - } + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + "models"; + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 6a1c530b837..8a3244b0097 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -1,97 +1,104 @@ 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 = ""; - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; + private static final String ALL_OPERATIONS = ""; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } + public StaticHtmlGenerator() { + super(); + outputFolder = "docs"; + templateDir = "htmlDocs"; - public String getName() { - return "html"; - } + defaultIncludes = new HashSet(); - public String getHelp() { - return "Generates a static HTML file."; - } + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); - public StaticHtmlGenerator() { - super(); - outputFolder = "docs"; - templateDir = "htmlDocs"; + supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); + reservedWords = new HashSet(); - defaultIncludes = new HashSet(); - - additionalProperties.put("appName", "Swagger Sample"); - additionalProperties.put("appDescription", "A sample swagger server"); - additionalProperties.put("infoUrl", "https://helloreverb.com"); - additionalProperties.put("infoEmail", "hello@helloreverb.com"); - additionalProperties.put("licenseInfo", "All rights reserved"); - additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); - reservedWords = new HashSet(); - - languageSpecificPrimitives = new HashSet(); - importMapping = new HashMap (); - } - - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap(); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; } - return super.getTypeDeclaration(p); - } - @Override - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - List operationList = (List) operations.get("operation"); - for(CodegenOperation op: operationList) { - op.httpMethod = op.httpMethod.toLowerCase(); + public String getName() { + return "html"; } - return objs; - } - @Override - public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - List opList = operations.get(ALL_OPERATIONS); - if(opList == null) { - opList = new ArrayList(); - operations.put(ALL_OPERATIONS, opList); + public String getHelp() { + return "Generates a static HTML file."; } - 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; - } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + List opList = operations.get(ALL_OPERATIONS); + if (opList == null) { + opList = new ArrayList(); + operations.put(ALL_OPERATIONS, 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; + } + } + opList.add(co); } - opList.add(co); - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index 525d8f6a9a9..94f6279f46f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -1,45 +1,46 @@ 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 CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } + public SwaggerGenerator() { + super(); + templateDir = "swagger"; + outputFolder = "generated-code/swagger"; - public String getName() { - return "swagger"; - } - - public String getHelp() { - 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{ - String outputFile = outputFolder + File.separator + "swagger.json"; - FileUtils.writeStringToFile(new File(outputFile), swaggerString); - System.out.println("wrote file to " + outputFile); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); } - catch(Exception e) { - e.printStackTrace(); + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "swagger"; + } + + public String getHelp() { + return "Creates a static swagger.json file."; + } + + @Override + public void processSwagger(Swagger swagger) { + String swaggerString = Json.pretty(swagger); + + try { + String outputFile = outputFolder + File.separator + "swagger.json"; + FileUtils.writeStringToFile(new File(outputFile), swaggerString); + System.out.println("wrote file to " + outputFile); + } catch (Exception e) { + e.printStackTrace(); + } } - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index ad25ee69913..35874390e0f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -1,44 +1,45 @@ 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 CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } + public SwaggerYamlGenerator() { + super(); + templateDir = "swagger"; + outputFolder = "generated-code/swagger"; - public String getName() { - return "swagger-yaml"; - } - - public String getHelp() { - 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{ - 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); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); } - catch(Exception e) { - e.printStackTrace(); + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "swagger-yaml"; + } + + public String getHelp() { + return "Creates a static swagger.yaml file."; + } + + @Override + public void processSwagger(Swagger swagger) { + 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) { + e.printStackTrace(); + } } - } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java index 033781beb36..2b384f36a7d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java @@ -3,248 +3,263 @@ 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; public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { - private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); - protected String sourceFolder = "Classes/Swaggers"; + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected String sourceFolder = "Classes/Swaggers"; - public CodegenType getTag() { - return CodegenType.CLIENT; - } + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; - public String getName() { - return "swift"; - } + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); - public String getHelp() { - return "Generates a swift client library."; - } + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); + } - public SwiftGenerator() { - super(); - outputFolder = "generated-code/swift"; - modelTemplateFiles.put("model.mustache", ".swift"); - apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; + sourceFolder = appName + "/" + sourceFolder; - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; - } - additionalProperties.put("projectName", appName); + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Int", + "Float", + "Double", + "Bool", + "Void", + "String", + "Character") + ); + defaultIncludes = new HashSet( + Arrays.asList( + "NSDate", + "Array", + "Dictionary", + "Set", + "Any", + "Empty", + "AnyObject") + ); + reservedWords = new HashSet( + Arrays.asList( + "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak") + ); + + typeMapping = new HashMap(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("date", "NSDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("string", "String"); + typeMapping.put("char", "Character"); + typeMapping.put("short", "Int"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("Integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "Double"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "AnyObject"); + typeMapping.put("file", "NSData"); + + importMapping = new HashMap(); } - sourceFolder = appName + "/" + sourceFolder; + private static String normalizePath(String path) { + StringBuilder builder = new StringBuilder(); - supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); - supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); - supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); - supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + 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); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Int", - "Float", - "Double", - "Bool", - "Void", - "String", - "Character") - ); - defaultIncludes = new HashSet( - Arrays.asList( - "NSDate", - "Array", - "Dictionary", - "Set", - "Any", - "Empty", - "AnyObject") - ); - reservedWords = new HashSet( - Arrays.asList( - "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") - ); + String group = matcher.group().substring(1, matcher.group().length() - 1); + group = camelize(group, true); + builder + .append("{") + .append(group) + .append("}"); - typeMapping = new HashMap(); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("date", "NSDate"); - typeMapping.put("Date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "Bool"); - typeMapping.put("string", "String"); - typeMapping.put("char", "Character"); - typeMapping.put("short", "Int"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Int"); - typeMapping.put("integer", "Int"); - typeMapping.put("Integer", "Int"); - typeMapping.put("float", "Float"); - typeMapping.put("number", "Double"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "AnyObject"); - typeMapping.put("file", "NSData"); + cursor = matcher.end(); + found = matcher.find(); + } - importMapping = new HashMap(); - } + String stringAfterMatch = path.substring(cursor); + builder.append(stringAfterMatch); - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return "[String:" + getTypeDeclaration(inner) + "]"; + return builder.toString(); } - return super.getTypeDeclaration(p); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) + 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 + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "[String:" + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); - } else - type = swaggerType; - return toModelName(type); - } - - @Override - public String toDefaultValue(Property p) { - // nil - return null; - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "[String:" + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "[" + inner + "]"; - } - return null; - } - - @Override - public CodegenProperty fromProperty(String name, Property p) { - CodegenProperty codegenProperty = super.fromProperty(name, p); - if (codegenProperty.isEnum) { - List> swiftEnums = new ArrayList>(); - List values = (List) codegenProperty.allowableValues.get("values"); - for (String value : values) { - Map map = new HashMap(); - map.put("enum", StringUtils.capitalize(value)); - map.put("raw", value); - swiftEnums.add(map); - } - codegenProperty.allowableValues.put("values", swiftEnums); - codegenProperty.datatypeWithEnum = - StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); - } - return codegenProperty; - } - - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultAPI"; - return initialCaps(name) + "API"; - } - - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - path = normalizePath(path); - List parameters = operation.getParameters(); - parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { - @Override - public boolean apply(@Nullable Parameter parameter) { - return !(parameter instanceof HeaderParameter); - } - })); - 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); + @Override + public String toDefaultValue(Property p) { + // nil + return null; + } - return builder.toString(); - } + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "[String:" + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[" + inner + "]"; + } + return null; + } + + @Override + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty codegenProperty = super.fromProperty(name, p); + if (codegenProperty.isEnum) { + List> swiftEnums = new ArrayList>(); + List values = (List) codegenProperty.allowableValues.get("values"); + for (String value : values) { + Map map = new HashMap(); + map.put("enum", StringUtils.capitalize(value)); + map.put("raw", value); + swiftEnums.add(map); + } + codegenProperty.allowableValues.put("values", swiftEnums); + codegenProperty.datatypeWithEnum = + StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); + } + return codegenProperty; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultAPI"; + } + return initialCaps(name) + "API"; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + path = normalizePath(path); + List parameters = operation.getParameters(); + parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { + @Override + public boolean apply(@Nullable Parameter parameter) { + return !(parameter instanceof HeaderParameter); + } + })); + operation.setParameters(parameters); + return super.fromOperation(path, httpMethod, operation, definitions); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 460befb6609..34305d7c56f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -1,258 +1,277 @@ 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 Set foundationClasses = new HashSet(); - protected String sourceFolder = "client"; - protected static String PREFIX = "Sami"; - protected Map namespaces = new HashMap(); + protected static String PREFIX = "Sami"; + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected Map namespaces = new HashMap(); - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "tizen"; - } + public TizenClientCodegen() { + super(); + outputFolder = "generated-code/tizen"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".cpp"); + templateDir = "tizen"; + modelPackage = ""; - public String getHelp() { - return "Generates a Samsung Tizen C++ client library."; - } + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long") + ); + languageSpecificPrimitives = new HashSet(); - public TizenClientCodegen() { - super(); - outputFolder = "generated-code/tizen"; - modelTemplateFiles.put("model-header.mustache", ".h"); - modelTemplateFiles.put("model-body.mustache", ".cpp"); - apiTemplateFiles.put("api-header.mustache", ".h"); - apiTemplateFiles.put("api-body.mustache", ".cpp"); - templateDir = "tizen"; - modelPackage = ""; + additionalProperties().put("prefix", PREFIX); - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "int", - "long") - ); - languageSpecificPrimitives = new HashSet(); + reservedWords = new HashSet( + // VERIFY + Arrays.asList( + "void", "char", "short", "int", "void", "char", "short", "int", + "long", "float", "double", "signed", "unsigned", "id", "const", + "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", + "self", "super" + )); - additionalProperties().put("prefix", PREFIX); + super.typeMapping = new HashMap(); - reservedWords = new HashSet( - // VERIFY - Arrays.asList( - "void", "char", "short", "int", "void", "char", "short", "int", - "long", "float", "double", "signed", "unsigned", "id", "const", - "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", "super" - )); + typeMapping.put("Date", "DateTime"); + typeMapping.put("DateTime", "DateTime"); + typeMapping.put("string", "String"); + typeMapping.put("integer", "Integer"); + typeMapping.put("float", "Float"); + typeMapping.put("long", "Long"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("double", "Double"); + typeMapping.put("array", "IList"); + typeMapping.put("map", "HashMap"); + typeMapping.put("number", "Long"); + typeMapping.put("object", PREFIX + "Object"); - super.typeMapping = new HashMap(); + importMapping = new HashMap(); - typeMapping.put("Date", "DateTime"); - typeMapping.put("DateTime", "DateTime"); - typeMapping.put("string", "String"); - typeMapping.put("integer", "Integer"); - typeMapping.put("float", "Float"); - typeMapping.put("long", "Long"); - typeMapping.put("boolean", "Boolean"); - typeMapping.put("double", "Double"); - typeMapping.put("array", "IList"); - typeMapping.put("map", "HashMap"); - typeMapping.put("number", "Long"); - typeMapping.put("object", PREFIX + "Object"); + namespaces = new HashMap(); + namespaces.put("DateTime", "Tizen::Base::DateTime"); + namespaces.put("Integer", "Tizen::Base::Integer"); + namespaces.put("Long", "Tizen::Base::Long"); + namespaces.put("Boolean", "Tizen::Base::Boolean"); + namespaces.put("Float", "Tizen::Base::Float"); + namespaces.put("String", "Tizen::Base::String"); + namespaces.put("Double", "Tizen::Base::Double"); + namespaces.put("IList", "Tizen::Base::Collection::IList"); + namespaces.put("HashMap", "Tizen::Base::Collection::HashMap"); + namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList"); + namespaces.put("JsonNumber", "Tizen::Web::Json"); + namespaces.put("JsonString", "Tizen::Web::Json"); - importMapping = new HashMap(); - - namespaces = new HashMap (); - namespaces.put("DateTime", "Tizen::Base::DateTime"); - namespaces.put("Integer", "Tizen::Base::Integer"); - namespaces.put("Long", "Tizen::Base::Long"); - namespaces.put("Boolean", "Tizen::Base::Boolean"); - namespaces.put("Float", "Tizen::Base::Float"); - namespaces.put("String", "Tizen::Base::String"); - namespaces.put("Double", "Tizen::Base::Double"); - namespaces.put("IList", "Tizen::Base::Collection::IList"); - namespaces.put("HashMap", "Tizen::Base::Collection::HashMap"); - namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList"); - namespaces.put("JsonNumber", "Tizen::Web::Json"); - namespaces.put("JsonString", "Tizen::Web::Json"); - - foundationClasses = new HashSet ( - Arrays.asList( - "String", - "Integer", - "Float") - ); - supportingFiles.clear(); - supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); - supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); - supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); - supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h")); - supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp")); - supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); - supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h")); - supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp")); - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return instantiationTypes.get("map"); + foundationClasses = new HashSet( + Arrays.asList( + "String", + "Integer", + "Float") + ); + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h")); + supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp")); + supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h")); + supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp")); } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array"); + + public CodegenType getTag() { + return CodegenType.CLIENT; } - else - return null; - } - @Override - public String getTypeDeclaration(String name) { - if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) - return name; - else - return name + "*"; - } + public String getName() { + return "tizen"; + } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) + 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) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(String name) { + if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { + return name; + } else { + return name + "*"; + } + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } return toModelName(type); } - else - type = swaggerType; - return toModelName(type); - } - @Override - public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) - return toModelName(swaggerType); - else - return swaggerType + "*"; - } - - @Override - public String toModelName(String 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; + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) { + return toModelName(swaggerType); + } else { + return swaggerType + "*"; + } } - else { - return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + + @Override + public String toModelName(String 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 { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } } - } - @Override - public String toModelImport(String name) { - if(namespaces.containsKey(name)) { - return "using " + namespaces.get(name) + ";"; + @Override + public String toModelImport(String name) { + if (namespaces.containsKey(name)) { + return "using " + namespaces.get(name) + ";"; + } + return "#include \"" + name + ".h\""; } - return "#include \"" + name + ".h\""; - } - @Override - public String toDefaultValue(Property p) { - if(p instanceof StringProperty) - return "new String()"; - else if (p instanceof BooleanProperty) - return "new Boolean(false)"; - else if(p instanceof DateProperty) - return "new DateTime()"; - else if(p instanceof DateTimeProperty) - return "new DateTime()"; - else if (p instanceof DoubleProperty) - return "new Double()"; - else if (p instanceof FloatProperty) - return "new Float()"; - else if (p instanceof IntegerProperty) - return "new Integer()"; - else if (p instanceof LongProperty) - return "new Long()"; - else if (p instanceof DecimalProperty) - return "new Long()"; - else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap()"; + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "new String()"; + } else if (p instanceof BooleanProperty) { + return "new Boolean(false)"; + } else if (p instanceof DateProperty) { + return "new DateTime()"; + } else if (p instanceof DateTimeProperty) { + return "new DateTime()"; + } else if (p instanceof DoubleProperty) { + return "new Double()"; + } else if (p instanceof FloatProperty) { + return "new Float()"; + } else if (p instanceof IntegerProperty) { + return "new Integer()"; + } else if (p instanceof LongProperty) { + return "new Long()"; + } else if (p instanceof DecimalProperty) { + return "new Long()"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap()"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ArrayList()"; + } + // else + if (p instanceof RefProperty) { + RefProperty rp = (RefProperty) p; + return "new " + toModelName(rp.getSimpleRef()) + "()"; + } + return "null"; } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ArrayList()"; + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; } - // else - if(p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; } - return "null"; - } - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder; - } + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); + } - @Override - public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder; - } + @Override + public String toApiName(String name) { + return PREFIX + initialCaps(name) + "Api"; + } - @Override - public String toModelFilename(String name) { - return PREFIX + initialCaps(name); - } + public String toApiFilename(String name) { + return PREFIX + initialCaps(name) + "Api"; + } - @Override - public String toApiName(String name) { - return PREFIX + initialCaps(name) + "Api"; - } + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]", ""); + paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1); + return "p" + paramName; + } - public String toApiFilename(String name) { - return PREFIX + initialCaps(name) + "Api"; - } + public String escapeReservedWord(String name) { + return "_" + name; + } - @Override - public String toVarName(String name) { - String paramName = name.replaceAll("[^a-zA-Z0-9_]",""); - paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1); - return "p" + paramName; - } + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return$ + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return$ - 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); - } + // add_pet_by_id => addPetById + return camelize(operationId, true); + } } diff --git a/modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache b/modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache index 956b834c88c..725f7476afc 100644 --- a/modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache +++ b/modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache @@ -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) +} +} } diff --git a/modules/swagger-codegen/src/main/resources/Groovy/api.mustache b/modules/swagger-codegen/src/main/resources/Groovy/api.mustache index 6ff66a84720..8ab77047d4f 100644 --- a/modules/swagger-codegen/src/main/resources/Groovy/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Groovy/api.mustache @@ -1,9 +1,6 @@ package {{package}}; - - - import groovyx.net.http.* import static groovyx.net.http.ContentType.* import static groovyx.net.http.Method.* @@ -17,40 +14,40 @@ import java.util.*; @Mixin(ApiUtils) {{#operations}} -class {{classname}} { + class {{classname}} { String basePath = "{{basePath}}" String versionPath = "/api/v1" - {{#operation}} - def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) { - // create path and map variables - String resourcePath = "{{path}}" + {{#operation}} + def {{nickname}} ({{#allParams}} {{{dataType}}} {{paramName}},{{/allParams}} Closure onSuccess, Closure onFailure) { + // create path and map variables + String resourcePath = "{{path}}" - // query params - def queryParams = [:] - def headerParams = [:] + // query params + def queryParams = [:] + def headerParams = [:] - {{#requiredParamCount}} - // verify required params are set - if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new RuntimeException("missing required params") + {{#requiredParamCount}} + // verify required params are set + if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { + throw new RuntimeException("missing required params") + } + {{/requiredParamCount}} + + {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) + queryParams.put("{{paramName}}", String.valueOf({{paramName}})) + {{/queryParams}} + + {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}) + {{/headerParams}} + + invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, + "{{httpMethod}}", "{{returnContainer}}", + {{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}}) + + } + {{/operation}} } - {{/requiredParamCount}} - - {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) - queryParams.put("{{paramName}}", String.valueOf({{paramName}})) - {{/queryParams}} - - {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}) - {{/headerParams}} - - invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, - "{{httpMethod}}", "{{returnContainer}}", - {{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}}) - - } - {{/operation}} -} {{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache index d98f375c61d..ed8599e357b 100644 --- a/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache @@ -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' } diff --git a/modules/swagger-codegen/src/main/resources/Groovy/model.mustache b/modules/swagger-codegen/src/main/resources/Groovy/model.mustache index bc3ca28aaec..6e4843811b2 100644 --- a/modules/swagger-codegen/src/main/resources/Groovy/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Groovy/model.mustache @@ -4,18 +4,18 @@ import groovy.transform.Canonical {{#imports}}import {{import}}; {{/imports}} {{#models}} -{{#model}} -@Canonical -class {{classname}} { - {{#vars}} + {{#model}} + @Canonical + class {{classname}} { + {{#vars}} - {{#description}}/* {{{description}}} */ - {{/description}} - {{{datatype}}} {{name}} = {{{defaultValue}}} - {{/vars}} - + {{#description}}/* {{{description}}} */ + {{/description}} + {{{datatype}}} {{name}} = {{{defaultValue}}} + {{/vars}} -} -{{/model}} + } + + {{/model}} {{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 352401ba0d8..cab3d3f2618 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -40,468 +40,482 @@ import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; public class ApiClient { - private Map hostMap = new HashMap(); - private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; - private String basePath = "{{basePath}}"; +private Map + hostMap = new HashMap +(); +private Map + defaultHeaderMap = new HashMap +(); +private boolean debugging = false; +private String basePath = "{{basePath}}"; - private Map authentications; +private Map + 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();{{#authMethods}}{{#isBasic}} +// Setup authentications (key: authentication name, value: authentication). +authentications = new HashMap +();{{#authMethods}}{{#isBasic}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map 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 queryParams, Object body, Map headerParams, Map 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 queryParams, Map 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 formParams) { - StringBuilder formParamBuilder = new StringBuilder(); - - for (Entry 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 + 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 + queryParams, Object body, Map + headerParams, Map + 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 + queryParams, Map + 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 + formParams) { +StringBuilder formParamBuilder = new StringBuilder(); + +for (Entry + 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); +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index e936b423a91..473840fc0b0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache index 29d5f55ecee..1cba673ef29 100644 --- a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 035d6739dce..0add94b988d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -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; - } - - /** - * Join an array of strings with the given separator. - *

- * Note: This might be replaced by utility method from commons-lang or guava someday - * if one of those libraries is added as dependency. - *

- * - * @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(); - } +/** +* 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. +*

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+* +* @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(); +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 63357afd896..bcc9c5b0aa1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -21,105 +21,111 @@ import java.util.Map; import java.util.HashMap; {{#operations}} -public class {{classname}} { - private ApiClient apiClient; + public class {{classname}} { + private ApiClient apiClient; - public {{classname}}() { + public {{classname}}() { this(Configuration.getDefaultApiClient()); - } + } - public {{classname}}(ApiClient apiClient) { + public {{classname}}(ApiClient apiClient) { this.apiClient = apiClient; - } + } - public ApiClient getApiClient() { + public ApiClient getApiClient() { return apiClient; - } + } - public void setApiClient(ApiClient apiClient) { + public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; - } - - {{#operation}} - /** - * {{summary}} - * {{notes}} -{{#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}}; - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); } - {{/required}}{{/allParams}} - // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#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}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + // create path and map variables + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); - {{/queryParams}} + // query params + Map + queryParams = new HashMap + (); + Map + headerParams = new HashMap + (); + Map + formParams = new HashMap + (); - {{#headerParams}}if ({{paramName}} != null) - headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); - {{/headerParams}} + {{#queryParams}}if ({{paramName}} != null) + queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/queryParams}} - final String[] accepts = { - {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String accept = apiClient.selectHeaderAccept(accepts); + {{#headerParams}}if ({{paramName}} != null) + headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/headerParams}} - final String[] contentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); + final String[] accepts = { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String accept = apiClient.selectHeaderAccept(accepts); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - {{#formParams}}{{#notFile}} - if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); - } - {{/notFile}}{{#isFile}} - if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", {{paramName}}.getName()); - mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); - } - {{/isFile}}{{/formParams}} - if(hasFields) + final String[] contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + {{#formParams}}{{#notFile}} + if ({{paramName}} != null) { + hasFields = true; + mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); + } + {{/notFile}}{{#isFile}} + if ({{paramName}} != null) { + hasFields = true; + mp.field("{{baseName}}", {{paramName}}.getName()); + mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); + } + {{/isFile}}{{/formParams}} + if(hasFields) postBody = mp; - } - else { - {{#formParams}}{{#notFile}}if ({{paramName}} != null) + } + else { + {{#formParams}}{{#notFile}}if ({{paramName}} != null) formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} - {{/formParams}} - } + {{/formParams}} + } - try { - String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ + try { + String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; - } - else { + } + else { return {{#returnType}}null{{/returnType}}; - } - } catch (ApiException ex) { - throw ex; + } + } catch (ApiException ex) { + throw ex; + } + } + {{/operation}} } - } - {{/operation}} -} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index 9afe96c6ffb..04d8767036c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -4,44 +4,52 @@ import java.util.Map; import java.util.List; public class ApiException extends Exception { - private int code = 0; - private String message = null; - private Map> responseHeaders = null; - private String responseBody = null; +private int code = 0; +private String message = null; +private Map +> responseHeaders = null; + private String responseBody = null; - public ApiException() {} + public ApiException() {} - public ApiException(int code, String message) { + public ApiException(int code, String message) { this.code = code; this.message = message; - } + } - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } + public ApiException(int code, String message, Map + > responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } - public int getCode() { - return code; - } + public int getCode() { + return code; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } + /** + * Get the HTTP response headers. + */ + public Map + > getResponseHeaders() { + return responseHeaders; + } - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } -} + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index 65720b958cb..3c6f5ef970a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -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 queryParams, Map 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 + queryParams, Map + 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); +} +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 1b2e2bc2fbe..50ec5be52dc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -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 queryParams, Map headerParams); +/** Apply authentication settings to header and query params. */ +void applyToParams(Map + queryParams, Map + headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 22a64b1a24e..de8d8864c6a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -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 queryParams, Map 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 + queryParams, Map + 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); +} +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index ef84b8cc05e..98e4be6182b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -3,8 +3,10 @@ package {{invokerPackage}}.auth; import java.util.Map; public class OAuth implements Authentication { - @Override - public void applyToParams(Map queryParams, Map headerParams) { - // TODO: support oauth - } +@Override +public void applyToParams(Map + queryParams, Map + headerParams) { +// TODO: support oauth +} } diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 0e12f514c48..b38008ebc35 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -7,45 +7,45 @@ import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - }; - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + {{#model}}{{#description}} + /** + * {{description}} + **/{{/description}} + @ApiModel(description = "{{{description}}}") + public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{baseName}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{baseName}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } - {{/vars}} + {{/vars}} - @Override - public String toString() { + @Override + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{/vars}}sb.append("}\n"); return sb.toString(); - } -} -{{/model}} + } + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 592edeec051..d18fa9284c7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -1,167 +1,170 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen - - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - - com.sun.jersey - jersey-client - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.1.5 - - - joda-time - joda-time - ${jodatime-version} - + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + - - - junit - junit - ${junit-version} - test - - - - 1.5.0 - 1.18 - 2.4.2 - 2.3 - 1.0.0 - 4.8.1 - + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 1.18 + 2.4.2 + 2.3 + 1.0.0 + 4.8.1 + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache index ffab3b1088e..fbb96ab9039 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache index 68675432c64..123a8734f9f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache @@ -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 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 destroy() { +} - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } +@Override +public void init(FilterConfig filterConfig) throws ServletException { +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache index 94711b26efb..d625431db4d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache @@ -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; - - 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; - } +int code; +String type; +String message; - @XmlTransient - public int getCode() { - return code; - } +public ApiResponseMessage(){} - 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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache index 8ab2c99e4f8..499a1d1dcc7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache index 3ffa01fb257..4a80e8480a7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache @@ -1,7 +1,7 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This is an example of building a swagger-enabled scalatra server. diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 3216b60d516..654d6d64ae9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -27,26 +27,26 @@ 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}}(); + private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); -{{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @io.swagger.annotations.ApiResponses(value = { {{#responses}} - @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, - {{/hasMore}}{{/responses}} }) + {{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + {{/hasMore}}{{/responses}} }) - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) - throws NotFoundException { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) + throws NotFoundException { + return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + } + {{/operation}} } -{{/operation}} -} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 43e7cd8685c..6bc5dfcb869 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -19,10 +19,10 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; {{#operations}} -public abstract class {{classname}}Service { - {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) - throws NotFoundException; - {{/operation}} -} + public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException; + {{/operation}} + } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache index a434311d285..4a7ddfe1237 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index d49fa4952a2..1a3281118de 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -19,14 +19,14 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; {{#operations}} -public class {{classname}}ServiceImpl extends {{classname}}Service { - {{#operation}} - @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - {{/operation}} -} + public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} + } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache index ba842165f3d..1af86a79a2f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -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}} \ No newline at end of file +@ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index 300d5e61dd9..7e0640585bf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -7,45 +7,45 @@ import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - }; - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + {{#model}}{{#description}} + /** + * {{description}} + **/{{/description}} + @ApiModel(description = "{{{description}}}") + public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{name}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } - {{/vars}} + {{/vars}} - @Override - public String toString() { + @Override + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{/vars}}sb.append("}\n"); return sb.toString(); - } -} -{{/model}} + } + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 708ca6cac4d..f0f877813ee 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -1,159 +1,161 @@ - - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - src/main/java - - - org.apache.maven.plugins - maven-war-plugin - 2.1.1 - - - maven-failsafe-plugin - 2.6 - - - - integration-test - verify - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty-version} - - - / - - target/${project.artifactId}-${project.version} - 8079 - stopit - - 8080 - 60000 - - - - - start-jetty - pre-integration-test - - start - - - 0 - true - - - - stop-jetty - post-integration-test - - stop - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.9.1 - - - add-source - generate-sources - - add-source - - - - src/gen/java - - - - - - - - - - io.swagger - swagger-jersey-jaxrs - ${swagger-core-version} - - - org.slf4j - slf4j-log4j12 - ${slf4j-version} - - - com.sun.jersey - jersey-core - ${jersey-version} - - - com.sun.jersey - jersey-json - ${jersey-version} - - - com.sun.jersey - jersey-servlet - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - com.sun.jersey - jersey-server - ${jersey-version} - + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + 8080 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + + src/gen/java + + + + + + + + + + io.swagger + swagger-jersey-jaxrs + ${swagger-core-version} + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + + + com.sun.jersey + jersey-core + ${jersey-version} + + + com.sun.jersey + jersey-json + ${jersey-version} + + + com.sun.jersey + jersey-servlet + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + com.sun.jersey + jersey-server + ${jersey-version} + - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - javax.servlet - servlet-api - ${servlet-api-version} - - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - true - - - - - 1.5.0 - 9.2.9.v20150224 - 1.13 - 1.6.3 - 1.6.1 - 4.8.1 - 2.5 - + + org.scalatest + scalatest_2.9.1 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.5.0 + 9.2.9.v20150224 + 1.13 + 1.6.3 + 1.6.1 + 4.8.1 + 2.5 + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache index ae6f6d4d692..c98d523dc50 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache @@ -1,54 +1,54 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + > - - jersey - com.sun.jersey.spi.container.servlet.ServletContainer - - com.sun.jersey.config.property.packages - io.swagger.jaxrs.json;io.swagger.jaxrs.listing;{{apiPackage}} - - - com.sun.jersey.spi.container.ContainerRequestFilters - com.sun.jersey.api.container.filter.PostReplaceFilter - - - com.sun.jersey.api.json.POJOMappingFeature - true - - 1 - + + jersey + com.sun.jersey.spi.container.servlet.ServletContainer + + com.sun.jersey.config.property.packages + io.swagger.jaxrs.json;io.swagger.jaxrs.listing;{{apiPackage}} + + + com.sun.jersey.spi.container.ContainerRequestFilters + com.sun.jersey.api.container.filter.PostReplaceFilter + + + com.sun.jersey.api.json.POJOMappingFeature + true + + 1 + - - DefaultJaxrsConfig - io.swagger.jaxrs.config.DefaultJaxrsConfig - - api.version - 1.0.0 - - - swagger.api.title - {{{title}}} - - - swagger.api.basepath - http://localhost:8080 - - 2 - + + DefaultJaxrsConfig + io.swagger.jaxrs.config.DefaultJaxrsConfig + + api.version + 1.0.0 + + + swagger.api.title + {{{title}}} + + + swagger.api.basepath + http://localhost:8080 + + 2 + - - jersey - /* - - - ApiOriginFilter - {{apiPackage}}.ApiOriginFilter - - - ApiOriginFilter - /* - + + jersey + /* + + + ApiOriginFilter + {{apiPackage}}.ApiOriginFilter + + + ApiOriginFilter + /* + diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index d6a24b69311..657aab0e369 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -31,23 +31,23 @@ import static org.springframework.http.MediaType.*; @RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/{{baseName}}", description = "the {{baseName}} API") {{#operations}} -public class {{classname}} { - {{#operation}} + public class {{classname}} { + {{#operation}} - @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @ApiResponses(value = { {{#responses}} - @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) - @RequestMapping(value = "{{path}}", - {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} - {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} - method = RequestMethod.{{httpMethod}}) - public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, - {{/hasMore}}{{/allParams}}) - throws NotFoundException { - // do some magic! - return new ResponseEntity<{{returnType}}>(HttpStatus.OK); - } + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) + @RequestMapping(value = "{{path}}", + {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} + {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} + method = RequestMethod.{{httpMethod}}) + public ResponseEntity<{{returnType}}> {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return new ResponseEntity<{{returnType}}>(HttpStatus.OK); + } - {{/operation}} -} + {{/operation}} + } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache index ffab3b1088e..fbb96ab9039 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache index 68675432c64..123a8734f9f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache @@ -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 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 destroy() { +} - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } +@Override +public void init(FilterConfig filterConfig) throws ServletException { +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache index 94711b26efb..d625431db4d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache @@ -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; - - 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; - } +int code; +String type; +String message; - @XmlTransient - public int getCode() { - return code; - } +public ApiResponseMessage(){} - 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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache index 402a684f86a..c2773bc5da6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache @@ -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}} \ No newline at end of file + @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}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index 300d5e61dd9..7e0640585bf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -7,45 +7,45 @@ import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - }; - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + {{#model}}{{#description}} + /** + * {{description}} + **/{{/description}} + @ApiModel(description = "{{{description}}}") + public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{name}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } - {{/vars}} + {{/vars}} - @Override - public String toString() { + @Override + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{/vars}}sb.append("}\n"); return sb.toString(); - } -} -{{/model}} + } + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache index 8ab2c99e4f8..499a1d1dcc7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache @@ -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; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index 3b068adffdf..a6fe9f9a298 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -1,229 +1,232 @@ - - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - src/main/java - - - org.apache.maven.plugins - maven-war-plugin - 2.1.1 - - - maven-failsafe-plugin - 2.6 - - - - integration-test - verify - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty-version} - - - {{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} - - target/${project.artifactId}-${project-version} - ${project.basedir}/conf/jetty/webdefault.xml - 8079 - stopit - - 8002 - 60000 - - - - - start-jetty - pre-integration-test - - start - - - 0 - true - - - - stop-jetty - post-integration-test - - stop - - - - - - com.googlecode.maven-download-plugin - download-maven-plugin - 1.2.1 - - - swagger-ui - - wget - - - https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz - true - ${project.build.directory} - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - validate - - copy-resources - - - target/${project.artifactId}-${project.version} - - - ${project.build.directory}/swagger-ui-${swagger-ui-version}/dist - true - - index.html - - - - - - - - - - - - io.swagger - swagger-jersey-jaxrs - ${swagger-core-version} - - - org.slf4j - slf4j-log4j12 - ${slf4j-version} - - - com.sun.jersey - jersey-core - ${jersey-version} - - - com.sun.jersey - jersey-json - ${jersey-version} - - - com.sun.jersey - jersey-servlet - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - com.sun.jersey - jersey-server - ${jersey-version} - + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + {{^contextPath}} + /{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} + + target/${project.artifactId}-${project-version} + ${project.basedir}/conf/jetty/webdefault.xml + 8079 + stopit + + 8002 + 60000 + + + + + start-jetty + pre-integration-test + + start + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + com.googlecode.maven-download-plugin + download-maven-plugin + 1.2.1 + + + swagger-ui + + wget + + + https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz + true + ${project.build.directory} + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + validate + + copy-resources + + + target/${project.artifactId}-${project.version} + + + ${project.build.directory}/swagger-ui-${swagger-ui-version}/dist + + true + + index.html + + + + + + + + + + + + io.swagger + swagger-jersey-jaxrs + ${swagger-core-version} + + + org.slf4j + slf4j-log4j12 + ${slf4j-version} + + + com.sun.jersey + jersey-core + ${jersey-version} + + + com.sun.jersey + jersey-json + ${jersey-version} + + + com.sun.jersey + jersey-servlet + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + com.sun.jersey + jersey-server + ${jersey-version} + - - - org.springframework - spring-core - ${spring-version} - - - org.springframework - spring-webmvc - ${spring-version} - - - org.springframework - spring-web - ${spring-version} - + + + org.springframework + spring-core + ${spring-version} + + + org.springframework + spring-webmvc + ${spring-version} + + + org.springframework + spring-web + ${spring-version} + - - - io.springfox - springfox-core - ${springfox-version} - - - io.springfox - springfox-spi - ${springfox-version} - - - io.springfox - springfox-spring-web - ${springfox-version} - - - io.springfox - springfox-swagger2 - ${springfox-version} - - - io.springfox - springfox-swagger-ui - ${springfox-version} - + + + io.springfox + springfox-core + ${springfox-version} + + + io.springfox + springfox-spi + ${springfox-version} + + + io.springfox + springfox-spring-web + ${springfox-version} + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - javax.servlet - servlet-api - ${servlet-api-version} - - - - - jcenter-snapshots - jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ - - - - 1.5.0 - 9.2.9.v20150224 - 2.1.0-M2 - 1.13 - 1.6.3 - 1.6.1 - 4.8.1 - 2.5 - 2.0.0-SNAPSHOT - 4.0.9.RELEASE - + + org.scalatest + scalatest_2.9.1 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + + + jcenter-snapshots + jcenter + http://oss.jfrog.org/artifactory/oss-snapshot-local/ + + + + 1.5.0 + 9.2.9.v20150224 + 2.1.0-M2 + 1.13 + 1.6.3 + 1.6.1 + 4.8.1 + 2.5 + 2.0.0-SNAPSHOT + 4.0.9.RELEASE + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache index b33ee7fc994..9542585a694 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache @@ -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()); +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache index 652dc310358..78b0705f6c1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache @@ -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); +} +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache index 6910ad11b76..1a2c1bb094c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache @@ -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[] { "/" }; +} } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache index 03904e51e79..67ec632ab85 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache @@ -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(); +} } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache index fecf2827f04..890b3c8af99 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache @@ -1,43 +1,43 @@ 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}} - 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}}) - {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) - {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) - {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) - {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) - {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) - {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) - {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) - {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) - {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] - {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] - {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} - object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} - def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} - } - {{/responseHeaders.isEmpty}} -{{/operation}} + {{#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}}) + {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) + {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) + {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) + {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) + {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) + {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) + {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) + {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) + {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] + {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] + {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} + object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} + def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} + } + {{/responseHeaders.isEmpty}} + {{/operation}} -{{#unknownStatusCodes}} - ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false) -{{/unknownStatusCodes}} + {{#unknownStatusCodes}} + ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false) + {{/unknownStatusCodes}} -} + } {{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache index 0dde3673439..f2861fbe023 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -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] = - invoker.execute(request).map(_.content).mapTo[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 +} } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache index 3016768f7ac..54ad27d3815 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache @@ -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)) } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache index d3ffe3613ae..b6c629659dc 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache @@ -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")) +} } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache index 52f1fd3e330..a2151bb9675 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache @@ -6,37 +6,38 @@ 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) - extends Serializer[E#Value] { - import JsonDSL._ +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) => { - json match { - case JString(value) => - enum.withName(value) - case value => - throw new MappingException(s"Can't convert $value to $EnumerationClass") - } - } + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value]={ + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json)=> { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } } private[this] def isValid(json: JValue) = json match { - case JString(value) if enum.values.exists(_.toString == value) => true - case _ => false + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false } def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { - case i: E#Value => i.toString + case i: E#Value => i.toString + } } - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache index 0d22fd62374..64fda1ec2e8 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache @@ -1,21 +1,21 @@ {{^notes.isEmpty}} -{{notes}} + {{notes}} {{/notes.isEmpty}} Expected answers: {{#responses}} - code {{code}} : {{dataType}} {{^message.isEmpty}}({{message}}){{/message.isEmpty}}{{^headers.isEmpty}} - Headers :{{#headers}} - {{baseName}} - {{description}}{{/headers}}{{/headers.isEmpty}} + code {{code}} : {{dataType}} {{^message.isEmpty}}({{message}}){{/message.isEmpty}}{{^headers.isEmpty}} + Headers :{{#headers}} + {{baseName}} - {{description}}{{/headers}}{{/headers.isEmpty}} {{/responses}} {{#authMethods.0}} -Available security schemes: -{{#authMethods}} - {{name}} ({{type}}) -{{/authMethods}} + Available security schemes: + {{#authMethods}} + {{name}} ({{type}}) + {{/authMethods}} {{/authMethods.0}} {{#allParams}} -@param {{paramName}} {{description}} + @param {{paramName}} {{description}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache index a7395b5f03a..129c7e6bb55 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache @@ -4,27 +4,27 @@ import {{invokerPackage}}.ApiModel import org.joda.time.DateTime {{#models}} -{{#model}} + {{#model}} -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 + 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}} - val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") -{{/_enum}} - } + {{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}}{{/vars}} + {{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration { + {{#_enum}} + val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") + {{/_enum}} + } - {{/isEnum}}{{/vars}} -} -{{/hasEnums}} -{{/model}} + {{/isEnum}}{{/vars}} + } + {{/hasEnums}} + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache index 1a28a8962ed..786ad0ee12a 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache @@ -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 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache index 145354203fb..35bc96d817e 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache @@ -5,57 +5,57 @@ import java.net.URLEncoder import scala.util.Try sealed trait ApiReturnWithHeaders { - def headers: Map[String, String] - def header(name: String): Option[String] = headers.get(name) - def getStringHeader(name: String) = header(name) - def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) - def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) - def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) - def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) - def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) - private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +def headers: Map[String, String] +def header(name: String): Option[String] = headers.get(name) +def getStringHeader(name: String) = header(name) +def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) +def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) +def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) +def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) +def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) +private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } } sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) - extends ApiReturnWithHeaders +extends ApiReturnWithHeaders sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) - extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) - with ApiReturnWithHeaders +extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) +with ApiReturnWithHeaders sealed case class ApiMethod(value: String) object ApiMethods { - val CONNECT = ApiMethod("CONNECT") - val DELETE = ApiMethod("DELETE") - val GET = ApiMethod("GET") - val HEAD = ApiMethod("HEAD") - val OPTIONS = ApiMethod("OPTIONS") - val PATCH = ApiMethod("PATCH") - val POST = ApiMethod("POST") - val PUT = ApiMethod("PUT") - val TRACE = ApiMethod("TRACE") +val CONNECT = ApiMethod("CONNECT") +val DELETE = ApiMethod("DELETE") +val GET = ApiMethod("GET") +val HEAD = ApiMethod("HEAD") +val OPTIONS = ApiMethod("OPTIONS") +val PATCH = ApiMethod("PATCH") +val POST = ApiMethod("POST") +val PUT = ApiMethod("PUT") +val TRACE = ApiMethod("TRACE") } /** - * This trait needs to be added to any model defined by the api. - */ +* This trait needs to be added to any model defined by the api. +*/ trait ApiModel /** - * Single trait defining a credential that can be transformed to a paramName / paramValue tupple - */ +* Single trait defining a credential that can be transformed to a paramName / paramValue tupple +*/ sealed trait Credentials { - def asQueryParam: Option[(String, String)] = None +def asQueryParam: Option[(String, String)] = None } sealed case class BasicCredentials(user: String, password: String) extends Credentials sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { - override def asQueryParam: Option[(String, String)] = location match { - case ApiKeyLocations.QUERY => Some((keyName, key.value)) - case _ => None - } +override def asQueryParam: Option[(String, String)] = location match { +case ApiKeyLocations.QUERY => Some((keyName, key.value)) +case _ => None +} } sealed case class ApiKeyValue(value: String) @@ -64,103 +64,103 @@ sealed trait ApiKeyLocation object ApiKeyLocations { - case object QUERY extends ApiKeyLocation +case object QUERY extends ApiKeyLocation - case object HEADER extends ApiKeyLocation +case object HEADER extends ApiKeyLocation } /** - * Case class used to unapply numeric values only in pattern matching - * @param value the string representation of the numeric value - */ +* Case class used to unapply numeric values only in pattern matching +* @param value the string representation of the numeric value +*/ sealed case class NumericValue(value: String) { - override def toString = value +override def toString = value } object NumericValue { - def unapply(n: Any): Option[NumericValue] = n match { - case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) - case _ => None - } +def unapply(n: Any): Option[NumericValue] = n match { +case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) +case _ => None +} } /** - * Used for params being arrays - */ +* Used for params being arrays +*/ sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) object ArrayValues { - def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = - ArrayValues(values.getOrElse(Seq.empty), format) +def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = +ArrayValues(values.getOrElse(Seq.empty), format) - def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) } /** - * Defines how arrays should be rendered in query strings. - */ +* Defines how arrays should be rendered in query strings. +*/ sealed trait CollectionFormat trait MergedArrayFormat extends CollectionFormat { - def separator: String +def separator: String } object CollectionFormats { - case object CSV extends MergedArrayFormat { - override val separator = "," - } +case object CSV extends MergedArrayFormat { +override val separator = "," +} - case object TSV extends MergedArrayFormat { - override val separator = "\t" - } +case object TSV extends MergedArrayFormat { +override val separator = "\t" +} - case object SSV extends MergedArrayFormat { - override val separator = " " - } +case object SSV extends MergedArrayFormat { +override val separator = " " +} - case object PIPES extends MergedArrayFormat { - override val separator = "|" - } +case object PIPES extends MergedArrayFormat { +override val separator = "|" +} - case object MULTI extends CollectionFormat +case object MULTI extends CollectionFormat } object ParametersMap { - /** - * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, - * with valid url-encoding, arrays handling, files preservation, ... - */ - implicit class ParametersMapImprovements(val m: Map[String, Any]) { +/** +* Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, +* with valid url-encoding, arrays handling, files preservation, ... +*/ +implicit class ParametersMapImprovements(val m: Map[String, Any]) { - def asFormattedParamsList = m.toList.flatMap(formattedParams) +def asFormattedParamsList = m.toList.flatMap(formattedParams) - def asFormattedParams = m.flatMap(formattedParams) +def asFormattedParams = m.flatMap(formattedParams) - private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") +private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") - private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) +private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) - private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { - case arr: ArrayValues => - arr.format match { - case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) - case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) - } - case None => Seq.empty - case Some(opt) => - formattedParams(name, opt) - case s: Seq[Any] => - formattedParams(name, ArrayValues(s)) - case v: String => Seq((name, urlEncode(v))) - case NumericValue(v) => Seq((name, urlEncode(v))) - case f: File => Seq((name, f)) - case m: ApiModel => Seq((name, m)) - } - - } +private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { +case arr: ArrayValues => +arr.format match { +case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) +case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) +} +case None => Seq.empty +case Some(opt) => +formattedParams(name, opt) +case s: Seq[Any] => +formattedParams(name, ArrayValues(s)) +case v: String => Seq((name, urlEncode(v))) +case NumericValue(v) => Seq((name, urlEncode(v))) +case f: File => Seq((name, f)) +case m: ApiModel => Seq((name, m)) +} + +} } diff --git a/modules/swagger-codegen/src/main/resources/android-java/api.mustache b/modules/swagger-codegen/src/main/resources/android-java/api.mustache index ed9538c1594..22fe28f32f3 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -18,97 +18,103 @@ import java.util.HashMap; import java.io.File; {{#operations}} -public class {{classname}} { - String basePath = "{{basePath}}"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); + public class {{classname}} { + String basePath = "{{basePath}}"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); - public void addHeader(String key, String value) { + public void addHeader(String key, String value) { getInvoker().addDefaultHeader(key, value); - } + } - public ApiInvoker getInvoker() { + public ApiInvoker getInvoker() { return apiInvoker; - } + } - public void setBasePath(String basePath) { + public void setBasePath(String basePath) { this.basePath = basePath; - } + } - public String getBasePath() { + public String getBasePath() { return basePath; - } - - {{#operation}} - /** - * {{summary}} - * {{notes}} -{{#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}}; - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); - } - {{/required}}{{/allParams}} - - // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - // query params - Map queryParams = new HashMap(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); - - {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); - {{/queryParams}} - - {{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); - {{/headerParams}} - - String[] contentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { - // file uploading - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - {{#formParams}}{{#notFile}} - if ({{paramName}} != null) { - builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); - } - {{/notFile}}{{#isFile}} - if ({{paramName}} != null) { - builder.addBinaryBody("{{baseName}}", {{paramName}}); - } - {{/isFile}}{{/formParams}} - - HttpEntity httpEntity = builder.build(); - postBody = httpEntity; - } else { - // normal form params - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} - {{/formParams}} } - try { - String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#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}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} + + // create path and map variables + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + // query params + Map + queryParams = new HashMap + (); + // header params + Map + headerParams = new HashMap + (); + // form params + Map + formParams = new HashMap + (); + + {{#queryParams}}if ({{paramName}} != null) + queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{/queryParams}} + + {{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{/headerParams}} + + String[] contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if (contentType.startsWith("multipart/form-data")) { + // file uploading + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + {{#formParams}}{{#notFile}} + if ({{paramName}} != null) { + builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); + } + {{/notFile}}{{#isFile}} + if ({{paramName}} != null) { + builder.addBinaryBody("{{baseName}}", {{paramName}}); + } + {{/isFile}}{{/formParams}} + + HttpEntity httpEntity = builder.build(); + postBody = httpEntity; + } else { + // normal form params + {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{/formParams}} + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; - } - else { + } + else { return {{#returnType}}null{{/returnType}}; - } - } catch (ApiException ex) { - throw ex; + } + } catch (ApiException ex) { + throw ex; + } + } + {{/operation}} } - } - {{/operation}} -} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiException.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiException.mustache index a6bcba75b7c..7510bb078c5 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiException.mustache @@ -1,29 +1,29 @@ package {{invokerPackage}}; public class ApiException extends Exception { - int code = 0; - String message = null; +int code = 0; +String message = null; - public ApiException() {} +public ApiException() {} - public ApiException(int code, String message) { - this.code = code; - this.message = message; - } +public ApiException(int code, String message) { +this.code = code; +this.message = message; +} - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } +public int getCode() { +return code; +} + +public void setCode(int code) { +this.code = code; +} + +public String getMessage() { +return message; +} + +public void setMessage(String message) { +this.message = message; +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index e759f8264a4..7250f3463df 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -52,338 +52,345 @@ import javax.net.ssl.X509TrustManager; import com.google.gson.JsonParseException; public class ApiInvoker { - private static ApiInvoker INSTANCE = new ApiInvoker(); - private Map defaultHeaderMap = new HashMap(); +private static ApiInvoker INSTANCE = new ApiInvoker(); +private Map + defaultHeaderMap = new HashMap +(); - private HttpClient client = null; +private HttpClient client = null; - private boolean ignoreSSLCertificates = false; +private boolean ignoreSSLCertificates = false; - private ClientConnectionManager ignoreSSLConnectionManager; +private ClientConnectionManager ignoreSSLConnectionManager; - /** Content type "text/plain" with UTF-8 encoding. */ - public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); +/** Content type "text/plain" with UTF-8 encoding. */ +public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); - /** - * ISO 8601 date time format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); +/** +* ISO 8601 date time format. +* @see https://en.wikipedia.org/wiki/ISO_8601 +*/ +public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - /** - * ISO 8601 date format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); +/** +* ISO 8601 date format. +* @see https://en.wikipedia.org/wiki/ISO_8601 +*/ +public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - static { - // Use UTC as the default time zone. - DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); - DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); +static { +// Use UTC as the default time zone. +DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); +DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); - // Set default User-Agent. - setUserAgent("Android-Java-Swagger"); - } - - public static void setUserAgent(String userAgent) { - INSTANCE.addDefaultHeader("User-Agent", userAgent); - } - - public static Date parseDateTime(String str) { - try { - return DATE_TIME_FORMAT.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - public static Date parseDate(String str) { - try { - return DATE_FORMAT.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - public static String formatDateTime(Date datetime) { - return DATE_TIME_FORMAT.format(datetime); - } - - public static String formatDate(Date date) { - return DATE_FORMAT.format(date); - } - - public static String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDateTime((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); - } - } - - public ApiInvoker() { - initConnectionManager(); - } - - public static ApiInvoker getInstance() { - return INSTANCE; - } - - public void ignoreSSLCertificates(boolean ignoreSSLCertificates) { - this.ignoreSSLCertificates = ignoreSSLCertificates; - } - - public void addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - } - - public String escapeString(String str) { - return str; - } - - public static Object deserialize(String json, String containerType, Class cls) throws ApiException { - try{ - if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) { - return JsonUtil.deserializeToList(json, cls); - } - 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.deserializeToObject(json, cls); - } - } - catch (JsonParseException e) { - throw new ApiException(500, e.getMessage()); - } - } - - public static String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return JsonUtil.serialize(obj); - else - return null; - } - catch (Exception e) { - throw new ApiException(500, e.getMessage()); - } - } - - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { - HttpClient client = getClient(host); - - 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 url = host + path + b.toString(); - - HashMap headers = new HashMap(); - - for(String key : headerParams.keySet()) { - headers.put(key, headerParams.get(key)); - } - - for(String key : defaultHeaderMap.keySet()) { - if(!headerParams.containsKey(key)) { - headers.put(key, defaultHeaderMap.get(key)); - } - } - headers.put("Accept", "application/json"); - - // URL encoded string from form parameters - String formParamStr = null; - - // for form data - if ("application/x-www-form-urlencoded".equals(contentType)) { - StringBuilder formParamBuilder = new StringBuilder(); - - // encode the form params - for (String key : formParams.keySet()) { - String value = formParams.get(key); - if (value != null && !"".equals(value.trim())) { - if (formParamBuilder.length() > 0) { - formParamBuilder.append("&"); - } - try { - formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); - } - catch (Exception e) { - // move on to next - } - } - } - formParamStr = formParamBuilder.toString(); - } - - HttpResponse response = null; - try { - if ("GET".equals(method)) { - HttpGet get = new HttpGet(url); - get.addHeader("Accept", "application/json"); - for(String key : headers.keySet()) { - get.setHeader(key, headers.get(key)); - } - response = client.execute(get); - } - else if ("POST".equals(method)) { - HttpPost post = new HttpPost(url); - if (formParamStr != null) { - post.setHeader("Content-Type", contentType); - post.setEntity(new StringEntity(formParamStr, "UTF-8")); - } else if (body != null) { - if (body instanceof HttpEntity) { - // this is for file uploading - post.setEntity((HttpEntity) body); - } else { - post.setHeader("Content-Type", contentType); - post.setEntity(new StringEntity(serialize(body), "UTF-8")); - } - } - for(String key : headers.keySet()) { - post.setHeader(key, headers.get(key)); - } - response = client.execute(post); - } - else if ("PUT".equals(method)) { - HttpPut put = new HttpPut(url); - if (formParamStr != null) { - put.setHeader("Content-Type", contentType); - put.setEntity(new StringEntity(formParamStr, "UTF-8")); - } else if (body != null) { - put.setHeader("Content-Type", contentType); - put.setEntity(new StringEntity(serialize(body), "UTF-8")); - } - for(String key : headers.keySet()) { - put.setHeader(key, headers.get(key)); - } - response = client.execute(put); - } - else if ("DELETE".equals(method)) { - HttpDelete delete = new HttpDelete(url); - for(String key : headers.keySet()) { - delete.setHeader(key, headers.get(key)); - } - response = client.execute(delete); - } - else if ("PATCH".equals(method)) { - HttpPatch patch = new HttpPatch(url); - if (formParamStr != null) { - patch.setHeader("Content-Type", contentType); - patch.setEntity(new StringEntity(formParamStr, "UTF-8")); - } else if (body != null) { - patch.setHeader("Content-Type", contentType); - patch.setEntity(new StringEntity(serialize(body), "UTF-8")); - } - for(String key : headers.keySet()) { - patch.setHeader(key, headers.get(key)); - } - response = client.execute(patch); - } - - int code = response.getStatusLine().getStatusCode(); - String responseString = null; - if(code == 204) - responseString = ""; - else if(code >= 200 && code < 300) { - if(response.getEntity() != null) { - HttpEntity resEntity = response.getEntity(); - responseString = EntityUtils.toString(resEntity); - } - return responseString; - } - else { - if(response.getEntity() != null) { - HttpEntity resEntity = response.getEntity(); - responseString = EntityUtils.toString(resEntity); - } - else - responseString = "no data"; - } - throw new ApiException(code, responseString); - } - catch(IOException e) { - throw new ApiException(500, e.getMessage()); - } - } - - private HttpClient getClient(String host) { - if (client == null) { - if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) { - // Trust self signed certificates - client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams()); - } else { - client = new DefaultHttpClient(); - } - } - return client; - } - - private void initConnectionManager() { - try { - final SSLContext sslContext = SSLContext.getInstance("SSL"); - - // set up a TrustManager that trusts everything - TrustManager[] trustManagers = new TrustManager[] { - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted(X509Certificate[] certs, String authType) {} - public void checkServerTrusted(X509Certificate[] certs, String authType) {} - }}; - - sslContext.init(null, trustManagers, new SecureRandom()); - - SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) { - private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory(); - - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) - throws IOException, UnknownHostException { - return sslFactory.createSocket(socket, host, port, autoClose); - } - - public Socket createSocket() throws IOException { - return sslFactory.createSocket(); - } - }; - - sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - Scheme httpsScheme = new Scheme("https", sf, 443); - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(httpsScheme); - schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - - ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry); - } catch (NoSuchAlgorithmException e) { - // This will only be thrown if SSL isn't available for some reason. - } catch (KeyManagementException e) { - // This might be thrown when passing a key into init(), but no key is being passed. - } catch (GeneralSecurityException e) { - // This catches anything else that might go wrong. - // If anything goes wrong we default to the standard connection manager. - } - } +// Set default User-Agent. +setUserAgent("Android-Java-Swagger"); +} + +public static void setUserAgent(String userAgent) { +INSTANCE.addDefaultHeader("User-Agent", userAgent); +} + +public static Date parseDateTime(String str) { +try { +return DATE_TIME_FORMAT.parse(str); +} catch (java.text.ParseException e) { +throw new RuntimeException(e); +} +} + +public static Date parseDate(String str) { +try { +return DATE_FORMAT.parse(str); +} catch (java.text.ParseException e) { +throw new RuntimeException(e); +} +} + +public static String formatDateTime(Date datetime) { +return DATE_TIME_FORMAT.format(datetime); +} + +public static String formatDate(Date date) { +return DATE_FORMAT.format(date); +} + +public static String parameterToString(Object param) { +if (param == null) { +return ""; +} else if (param instanceof Date) { +return formatDateTime((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); +} +} + +public ApiInvoker() { +initConnectionManager(); +} + +public static ApiInvoker getInstance() { +return INSTANCE; +} + +public void ignoreSSLCertificates(boolean ignoreSSLCertificates) { +this.ignoreSSLCertificates = ignoreSSLCertificates; +} + +public void addDefaultHeader(String key, String value) { +defaultHeaderMap.put(key, value); +} + +public String escapeString(String str) { +return str; +} + +public static Object deserialize(String json, String containerType, Class cls) throws ApiException { +try{ +if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) { +return JsonUtil.deserializeToList(json, cls); +} +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.deserializeToObject(json, cls); +} +} +catch (JsonParseException e) { +throw new ApiException(500, e.getMessage()); +} +} + +public static String serialize(Object obj) throws ApiException { +try { +if (obj != null) +return JsonUtil.serialize(obj); +else +return null; +} +catch (Exception e) { +throw new ApiException(500, e.getMessage()); +} +} + +public String invokeAPI(String host, String path, String method, Map + queryParams, Object body, Map + headerParams, Map + formParams, String contentType) throws ApiException { +HttpClient client = getClient(host); + +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 url = host + path + b.toString(); + +HashMap + headers = new HashMap +(); + +for(String key : headerParams.keySet()) { +headers.put(key, headerParams.get(key)); +} + +for(String key : defaultHeaderMap.keySet()) { +if(!headerParams.containsKey(key)) { +headers.put(key, defaultHeaderMap.get(key)); +} +} +headers.put("Accept", "application/json"); + +// URL encoded string from form parameters +String formParamStr = null; + +// for form data +if ("application/x-www-form-urlencoded".equals(contentType)) { +StringBuilder formParamBuilder = new StringBuilder(); + +// encode the form params +for (String key : formParams.keySet()) { +String value = formParams.get(key); +if (value != null && !"".equals(value.trim())) { +if (formParamBuilder.length() > 0) { +formParamBuilder.append("&"); +} +try { +formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); +} +catch (Exception e) { +// move on to next +} +} +} +formParamStr = formParamBuilder.toString(); +} + +HttpResponse response = null; +try { +if ("GET".equals(method)) { +HttpGet get = new HttpGet(url); +get.addHeader("Accept", "application/json"); +for(String key : headers.keySet()) { +get.setHeader(key, headers.get(key)); +} +response = client.execute(get); +} +else if ("POST".equals(method)) { +HttpPost post = new HttpPost(url); +if (formParamStr != null) { +post.setHeader("Content-Type", contentType); +post.setEntity(new StringEntity(formParamStr, "UTF-8")); +} else if (body != null) { +if (body instanceof HttpEntity) { +// this is for file uploading +post.setEntity((HttpEntity) body); +} else { +post.setHeader("Content-Type", contentType); +post.setEntity(new StringEntity(serialize(body), "UTF-8")); +} +} +for(String key : headers.keySet()) { +post.setHeader(key, headers.get(key)); +} +response = client.execute(post); +} +else if ("PUT".equals(method)) { +HttpPut put = new HttpPut(url); +if (formParamStr != null) { +put.setHeader("Content-Type", contentType); +put.setEntity(new StringEntity(formParamStr, "UTF-8")); +} else if (body != null) { +put.setHeader("Content-Type", contentType); +put.setEntity(new StringEntity(serialize(body), "UTF-8")); +} +for(String key : headers.keySet()) { +put.setHeader(key, headers.get(key)); +} +response = client.execute(put); +} +else if ("DELETE".equals(method)) { +HttpDelete delete = new HttpDelete(url); +for(String key : headers.keySet()) { +delete.setHeader(key, headers.get(key)); +} +response = client.execute(delete); +} +else if ("PATCH".equals(method)) { +HttpPatch patch = new HttpPatch(url); +if (formParamStr != null) { +patch.setHeader("Content-Type", contentType); +patch.setEntity(new StringEntity(formParamStr, "UTF-8")); +} else if (body != null) { +patch.setHeader("Content-Type", contentType); +patch.setEntity(new StringEntity(serialize(body), "UTF-8")); +} +for(String key : headers.keySet()) { +patch.setHeader(key, headers.get(key)); +} +response = client.execute(patch); +} + +int code = response.getStatusLine().getStatusCode(); +String responseString = null; +if(code == 204) +responseString = ""; +else if(code >= 200 && code < 300) { +if(response.getEntity() != null) { +HttpEntity resEntity = response.getEntity(); +responseString = EntityUtils.toString(resEntity); +} +return responseString; +} +else { +if(response.getEntity() != null) { +HttpEntity resEntity = response.getEntity(); +responseString = EntityUtils.toString(resEntity); +} +else +responseString = "no data"; +} +throw new ApiException(code, responseString); +} +catch(IOException e) { +throw new ApiException(500, e.getMessage()); +} +} + +private HttpClient getClient(String host) { +if (client == null) { +if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) { +// Trust self signed certificates +client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams()); +} else { +client = new DefaultHttpClient(); +} +} +return client; +} + +private void initConnectionManager() { +try { +final SSLContext sslContext = SSLContext.getInstance("SSL"); + +// set up a TrustManager that trusts everything +TrustManager[] trustManagers = new TrustManager[] { +new X509TrustManager() { +public X509Certificate[] getAcceptedIssuers() { +return null; +} +public void checkClientTrusted(X509Certificate[] certs, String authType) {} +public void checkServerTrusted(X509Certificate[] certs, String authType) {} +}}; + +sslContext.init(null, trustManagers, new SecureRandom()); + +SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) { +private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory(); + +public Socket createSocket(Socket socket, String host, int port, boolean autoClose) +throws IOException, UnknownHostException { +return sslFactory.createSocket(socket, host, port, autoClose); +} + +public Socket createSocket() throws IOException { +return sslFactory.createSocket(); +} +}; + +sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); +Scheme httpsScheme = new Scheme("https", sf, 443); +SchemeRegistry schemeRegistry = new SchemeRegistry(); +schemeRegistry.register(httpsScheme); +schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + +ignoreSSLConnectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry); +} catch (NoSuchAlgorithmException e) { +// This will only be thrown if SSL isn't available for some reason. +} catch (KeyManagementException e) { +// This might be thrown when passing a key into init(), but no key is being passed. +} catch (GeneralSecurityException e) { +// This catches anything else that might go wrong. +// If anything goes wrong we default to the standard connection manager. +} +} } diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index 367890f3298..ec30a79812c 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -1,93 +1,93 @@ {{#useAndroidMavenGradlePlugin}} -group = '{{groupId}}' -project.version = '{{artifactVersion}}' + group = '{{groupId}}' + project.version = '{{artifactVersion}}' {{/useAndroidMavenGradlePlugin}} buildscript { - repositories { - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:1.2.2' - {{#useAndroidMavenGradlePlugin}} - classpath 'com.github.dcendents:android-maven-plugin:1.2' - {{/useAndroidMavenGradlePlugin}} - } +repositories { +jcenter() +} +dependencies { +classpath 'com.android.tools.build:gradle:1.2.2' +{{#useAndroidMavenGradlePlugin}} + classpath 'com.github.dcendents:android-maven-plugin:1.2' +{{/useAndroidMavenGradlePlugin}} +} } allprojects { - repositories { - jcenter() - } +repositories { +jcenter() +} } apply plugin: 'com.android.library' {{#useAndroidMavenGradlePlugin}} -apply plugin: 'com.github.dcendents.android-maven' + apply plugin: 'com.github.dcendents.android-maven' {{/useAndroidMavenGradlePlugin}} android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } +compileSdkVersion 22 +buildToolsVersion '22.0.0' +defaultConfig { +minSdkVersion 14 +targetSdkVersion 22 +} - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } +// Rename the aar correctly +libraryVariants.all { variant -> +variant.outputs.each { output -> +def outputFile = output.outputFile +if (outputFile != null && outputFile.name.endsWith('.aar')) { +def fileName = "${project.name}-${variant.baseName}-${version}.aar" +output.outputFile = new File(outputFile.parent, fileName) +} +} +} } ext { - swagger_annotations_version = "1.5.0" - gson_version = "2.3.1" - httpclient_version = "4.3.3" - junit_version = "4.8.1" +swagger_annotations_version = "1.5.0" +gson_version = "2.3.1" +httpclient_version = "4.3.3" +junit_version = "4.8.1" } dependencies { - compile "io.swagger:swagger-annotations:$swagger_annotations_version" - compile "com.google.code.gson:gson:$gson_version" - compile "org.apache.httpcomponents:httpcore:$httpclient_version" - compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { - exclude(group: 'org.apache.httpcomponents', module: 'httpclient') - } - compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { - exclude(group: 'org.apache.httpcomponents', module: 'httpclient') - } - testCompile "junit:junit:$junit_version" +compile "io.swagger:swagger-annotations:$swagger_annotations_version" +compile "com.google.code.gson:gson:$gson_version" +compile "org.apache.httpcomponents:httpcore:$httpclient_version" +compile "org.apache.httpcomponents:httpclient:$httpclient_version" +compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { +exclude(group: 'org.apache.httpcomponents', module: 'httpclient') +} +compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { +exclude(group: 'org.apache.httpcomponents', module: 'httpclient') +} +testCompile "junit:junit:$junit_version" } afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } +android.libraryVariants.all { variant -> +def task = project.tasks.create "jar${variant.name.capitalize()}", Jar +task.description = "Create jar artifact for ${variant.name}" +task.dependsOn variant.javaCompile +task.from variant.javaCompile.destinationDir +task.destinationDir = project.file("${project.buildDir}/outputs/jar") +task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" +artifacts.add('archives', task); +} } {{#useAndroidMavenGradlePlugin}} -task sourcesJar(type: Jar) { + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' -} + } -artifacts { + artifacts { archives sourcesJar -} + } {{/useAndroidMavenGradlePlugin}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache b/modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache index 55cec2f1279..72b9ec2e42b 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache @@ -3,14 +3,14 @@ package {{invokerPackage}}; import org.apache.http.client.methods.*; public class HttpPatch extends HttpPost { - public static final String METHOD_PATCH = "PATCH"; +public static final String METHOD_PATCH = "PATCH"; - public HttpPatch(final String url) { - super(url); - } +public HttpPatch(final String url) { +super(url); +} - @Override - public String getMethod() { - return METHOD_PATCH; - } +@Override +public String getMethod() { +return METHOD_PATCH; +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache b/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache index ae8d18d3731..fb88b7f701c 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache @@ -8,48 +8,55 @@ import java.util.List; import {{modelPackage}}.*; public class JsonUtil { - public static GsonBuilder gsonBuilder; +public static GsonBuilder gsonBuilder; - static { - gsonBuilder = new GsonBuilder(); - gsonBuilder.serializeNulls(); - gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - } +static { +gsonBuilder = new GsonBuilder(); +gsonBuilder.serializeNulls(); +gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); +} - public static Gson getGson() { - return gsonBuilder.create(); - } +public static Gson getGson() { +return gsonBuilder.create(); +} - public static String serialize(Object obj){ - return getGson().toJson(obj); - } +public static String serialize(Object obj){ +return getGson().toJson(obj); +} - public static T deserializeToList(String jsonString, Class cls){ +public static + T deserializeToList(String jsonString, Class cls){ return getGson().fromJson(jsonString, getListTypeForDeserialization(cls)); - } - - public static T deserializeToObject(String jsonString, Class cls){ - return getGson().fromJson(jsonString, getTypeForDeserialization(cls)); - } - - public static Type getListTypeForDeserialization(Class cls) { - String className = cls.getSimpleName(); - {{#models}}{{#model}} - if ("{{classname}}".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); } - {{/model}}{{/models}} - return new TypeToken>(){}.getType(); - } - public static Type getTypeForDeserialization(Class cls) { - String className = cls.getSimpleName(); - {{#models}}{{#model}} - if ("{{classname}}".equalsIgnoreCase(className)) { - return new TypeToken<{{classname}}>(){}.getType(); - } - {{/model}}{{/models}} - return new TypeToken(){}.getType(); - } + public static + T deserializeToObject(String jsonString, Class cls){ + return getGson().fromJson(jsonString, getTypeForDeserialization(cls)); + } -}; + public static Type getListTypeForDeserialization(Class cls) { + String className = cls.getSimpleName(); + {{#models}}{{#model}} + if ("{{classname}}".equalsIgnoreCase(className)) { + return new TypeToken + >(){}.getType(); + } + {{/model}}{{/models}} + return new TypeToken + >(){}.getType(); + } + + public static Type getTypeForDeserialization(Class cls) { + String className = cls.getSimpleName(); + {{#models}}{{#model}} + if ("{{classname}}".equalsIgnoreCase(className)) { + return new TypeToken<{{classname}}>(){}.getType(); + } + {{/model}}{{/models}} + return new TypeToken + (){}.getType(); + } + + }; diff --git a/modules/swagger-codegen/src/main/resources/android-java/manifest.mustache b/modules/swagger-codegen/src/main/resources/android-java/manifest.mustache index 165749c3cc4..b36579739f9 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/manifest.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/manifest.mustache @@ -1,3 +1,3 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/android-java/model.mustache b/modules/swagger-codegen/src/main/resources/android-java/model.mustache index 6c805a832e4..411cd69f71a 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/model.mustache @@ -7,46 +7,46 @@ import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - }; - @SerializedName("{{baseName}}") - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - @SerializedName("{{baseName}}") - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + {{#model}}{{#description}} + /** + * {{description}} + **/{{/description}} + @ApiModel(description = "{{{description}}}") + public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + @SerializedName("{{baseName}}") + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } - {{/vars}} + {{/vars}} - @Override - public String toString() { + @Override + public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); {{/vars}}sb.append("}\n"); return sb.toString(); - } -} -{{/model}} + } + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache index 05388db4e11..b78ae08991b 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache @@ -1,155 +1,158 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen - - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - - com.google.code.gson - gson - ${gson-version} - - - org.apache.httpcomponents - httpclient - ${httpclient-version} - compile - - - org.apache.httpcomponents - httpmime - ${httpclient-version} - compile - + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.google.code.gson + gson + ${gson-version} + + + org.apache.httpcomponents + httpclient + ${httpclient-version} + compile + + + org.apache.httpcomponents + httpmime + ${httpclient-version} + compile + - - - junit - junit - ${junit-version} - test - - - - - sonatype-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - - - 1.5.0 - 2.3.1 - 4.8.1 - 1.0.0 - 4.8.1 - 4.3.6 - + + + junit + junit + ${junit-version} + test + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + + 1.5.0 + 2.3.1 + 4.8.1 + 1.0.0 + 4.8.1 + 4.3.6 + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index cd12ae18806..bb0d9694aaf 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -8,37 +8,37 @@ import scala.concurrent.duration._ import collection.mutable {{#operations}} -class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - {{#operation}} - def {{nickname}}({{#allParams}}{{#optional}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, - {{/hasMore}} - {{/optional}}{{^optional}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, - {{/hasMore}}{{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { - // create path and map variables - val path = (addFmt("{{path}}"){{#pathParams}} - replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString){{/pathParams}}) + {{#operation}} + def {{nickname}}({{#allParams}}{{#optional}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, + {{/hasMore}} + {{/optional}}{{^optional}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, + {{/hasMore}}{{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { + // create path and map variables + val path = (addFmt("{{path}}"){{#pathParams}} + replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString){{/pathParams}}) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] - {{#requiredParamCount}}// verify required params are set - val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size - if (paramCount != {{requiredParamCount}}) sys.error("missing required params"){{/requiredParamCount}} + {{#requiredParamCount}}// verify required params are set + val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size + if (paramCount != {{requiredParamCount}}) sys.error("missing required params"){{/requiredParamCount}} - {{#queryParams}}{{#optional}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/optional}}{{^optional}} - if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/optional}}{{/queryParams}} + {{#queryParams}}{{#optional}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/optional}}{{^optional}} + if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/optional}}{{/queryParams}} - {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString{{/headerParams}} + {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString{{/headerParams}} + + val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{paramName}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}}) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + {{/operation}} - val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{paramName}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}}) - resFuture flatMap { resp => - process(reader.read(resp)) } - } - - {{/operation}} - -} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache index 7d2093f8609..a4fcee3c988 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache @@ -9,17 +9,17 @@ import io.swagger.client._ import java.io.Closeable class {{clientName}}(config: SwaggerConfig) extends Closeable { - val locator = config.locator - val name = config.name +val locator = config.locator +val name = config.name - private[this] val client = transportClient +private[this] val client = transportClient - protected def transportClient: TransportClient = new RestClient(config) - {{#apiInfo}}{{#apis}} - val {{classVarName}} = new {{classname}}(client, config) - {{/apis}}{{/apiInfo}} +protected def transportClient: TransportClient = new RestClient(config) +{{#apiInfo}}{{#apis}} + val {{classVarName}} = new {{classname}}(client, config) +{{/apis}}{{/apiInfo}} - def close() { - client.close() - } +def close() { +client.close() +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache index b0da2825b32..c69f1d0bd36 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache @@ -4,10 +4,10 @@ import org.joda.time.DateTime {{#models}} -{{#model}} -case class {{classname}} ( - {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}}{{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}} - {{/vars}} -) -{{/model}} + {{#model}} + case class {{classname}} ( + {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}}{{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}} + {{/vars}} + ) + {{/model}} {{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache index aef5e1f389a..7de6c56badf 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache @@ -3,10 +3,10 @@ organization := "{{package}}" name := "{{projectName}}-client" libraryDependencies ++= Seq( - "io.swagger" %% "swagger-async-httpclient" % "0.3.5", - "joda-time" % "joda-time" % "2.3", - "org.joda" % "joda-convert" % "1.3.1", - "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "junit" % "junit" % "4.11" % "test" +"io.swagger" %% "swagger-async-httpclient" % "0.3.5", +"joda-time" % "joda-time" % "2.3", +"org.joda" % "joda-convert" % "1.3.1", +"ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", +"org.scalatest" %% "scalatest" % "2.2.1" % "test", +"junit" % "junit" % "4.11" % "test" ) diff --git a/modules/swagger-codegen/src/main/resources/codegen/README.mustache b/modules/swagger-codegen/src/main/resources/codegen/README.mustache index a434038ec41..df9b28758eb 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/README.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/README.mustache @@ -9,7 +9,7 @@ your changes applied. The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. -Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. +Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. ## How do I use this? At this point, you've likely generated a client setup. It will include something along these lines: diff --git a/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache index 788ef78834b..025c1bd82eb 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache @@ -8,184 +8,186 @@ import java.io.File; public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig { - // source folder where to write the files - protected String sourceFolder = "src"; - protected String apiVersion = "1.0.0"; +// source folder where to write the files +protected String sourceFolder = "src"; +protected String apiVersion = "1.0.0"; - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } +/** +* 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 "{{name}}"; - } +/** +* 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 "{{name}}"; +} - /** - * 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 {{name}} client library."; - } +/** +* 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 {{name}} client library."; +} - public {{generatorClass}}() { - super(); +public {{generatorClass}}() { +super(); - // set the output folder here - outputFolder = "generated-code/{{name}}"; +// set the output folder here +outputFolder = "generated-code/{{name}}"; - /** - * Models. You can write model files using the modelTemplateFiles map. - * if you want to create one template for file, you can do so here. - * for multiple files for model, just put another entry in the `modelTemplateFiles` with - * a different extension - */ - modelTemplateFiles.put( - "model.mustache", // the template to use - ".sample"); // the extension for each file to write +/** +* Models. You can write model files using the modelTemplateFiles map. +* if you want to create one template for file, you can do so here. +* for multiple files for model, just put another entry in the `modelTemplateFiles` with +* a different extension +*/ +modelTemplateFiles.put( +"model.mustache", // the template to use +".sample"); // the extension for each file to write - /** - * Api classes. You can write classes for each Api file with the apiTemplateFiles map. - * as with models, add multiple entries with different extensions for multiple files per - * class - */ - apiTemplateFiles.put( - "api.mustache", // the template to use - ".sample"); // the extension for each file to write +/** +* Api classes. You can write classes for each Api file with the apiTemplateFiles map. +* as with models, add multiple entries with different extensions for multiple files per +* class +*/ +apiTemplateFiles.put( +"api.mustache", // the template to use +".sample"); // the extension for each file to write - /** - * Template Location. This is the location which templates will be read from. The generator - * will use the resource stream to attempt to read the templates. - */ - templateDir = "{{name}}"; +/** +* Template Location. This is the location which templates will be read from. The generator +* will use the resource stream to attempt to read the templates. +*/ +templateDir = "{{name}}"; - /** - * Api Package. Optional, if needed, this can be used in templates - */ - apiPackage = "io.swagger.client.api"; +/** +* Api Package. Optional, if needed, this can be used in templates +*/ +apiPackage = "io.swagger.client.api"; - /** - * Model Package. Optional, if needed, this can be used in templates - */ - modelPackage = "io.swagger.client.model"; +/** +* Model Package. Optional, if needed, this can be used in templates +*/ +modelPackage = "io.swagger.client.model"; - /** - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") +/** +* Reserved words. Override this with reserved words specific to your language +*/ +reservedWords = new HashSet + ( + Arrays.asList( + "sample1", // replace with static values + "sample2") ); /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files - */ + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ additionalProperties.put("apiVersion", apiVersion); /** - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied - */ - supportingFiles.add(new SupportingFile("myFile.mustache", // the input template or file - "", // the destination folder, relative `outputFolder` - "myFile.sample") // the output file + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("myFile.mustache", // the input template or file + "", // the destination folder, relative `outputFolder` + "myFile.sample") // the output file ); /** - * Language Specific Primitives. These types will not trigger imports by - * the client generator - */ - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Type1", // replace these with your types + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet + ( + Arrays.asList( + "Type1", // replace these with your types "Type2") - ); - } + ); + } - /** - * 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 - * - * @return the escaped term - */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the 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 + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } - /** - * Location to write model files. You can use the modelPackage() as defined when the class is - * instantiated - */ - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } - /** - * Location to write api files. You can use the apiPackage() as defined when the class is - * instantiated - */ - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } - /** - * Optional - type declaration. This is a String which is used by the templates to instantiate your - * types. There is typically special handling for different property types - * - * @return a string value used as the `dataType` field for model templates, `returnType` for api templates - */ - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } - /** - * Optional - swagger type conversion. This is used to map swagger types in a `Property` into - * either language specific types via `typeMapping` or into complex models if there is not a mapping. - * - * @return a string value of the type or complex model for this property - * @see io.swagger.models.properties.Property - */ - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if(languageSpecificPrimitives.contains(type)) + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) return toModelName(type); - } - else - type = swaggerType; - return toModelName(type); - } -} \ No newline at end of file + } + else + type = swaggerType; + return toModelName(type); + } + } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache index ad480b9b331..b1daf970a0d 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache @@ -1,102 +1,105 @@ - 4.0.0 - io.swagger - {{name}}-swagger-codegen - jar - {{name}}-swagger-codegen - 1.0.0 - - 2.2.0 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + io.swagger + {{name}}-swagger-codegen + jar + {{name}}-swagger-codegen + 1.0.0 + + 2.2.0 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - - - io.swagger - swagger-codegen - ${swagger-codegen-version} - provided - - - - 2.1.2-M1 - 1.0.0 - 4.8.1 - + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-codegen + ${swagger-codegen-version} + provided + + + + 2.1.2-M1 + 1.0.0 + 4.8.1 + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index ad57cffdf34..466e628d23a 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -9,209 +9,308 @@ using Newtonsoft.Json; using RestSharp; namespace {{invokerPackage}} { - /// - /// API client is mainly responible for making the HTTP call to the API backend - /// - public class ApiClient { +/// + + /// API client is mainly responible for making the HTTP call to the API backend + /// + +public class ApiClient { - /// - /// Initializes a new instance of the class. - /// - /// The base path. - public ApiClient(String basePath="{{basePath}}") { - this.basePath = basePath; - this.restClient = new RestClient(this.basePath); - } +/// + + /// Initializes a new instance of the + + class. + /// + +/// +The base path. +public ApiClient(String basePath="{{basePath}}") { +this.basePath = basePath; +this.restClient = new RestClient(this.basePath); +} - /// +/// + /// Gets or sets the base path. - /// - /// The base path. - public string basePath { get; set; } + /// + +/// +The base path. +public string basePath { get; set; } - /// +/// + /// Gets or sets the RestClient - /// - /// The RestClient. - public RestClient restClient { get; set; } + /// + +/// +The RestClient. +public RestClient restClient { get; set; } - private Dictionary defaultHeaderMap = new Dictionary(); +private Dictionary + defaultHeaderMap = new Dictionary +(); - public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, - Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { - var response = Task.Run(async () => { - var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings); - return resp; - }); - return response.Result; +public Object CallApi(String Path, RestSharp.Method Method, Dictionary + QueryParams, String PostBody, +Dictionary + HeaderParams, Dictionary + FormParams, Dictionary + FileParams, String[] AuthSettings) { +var response = Task.Run(async () => { +var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings); +return resp; +}); +return response.Result; +} + +public async Task + CallApiAsync(String Path, RestSharp.Method Method, Dictionary + QueryParams, String PostBody, + Dictionary + HeaderParams, Dictionary + FormParams, Dictionary + FileParams, String[] AuthSettings) { + + var request = new RestRequest(Path, Method); + + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + + // add default header, if any + foreach(KeyValuePair + defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(KeyValuePair + param in HeaderParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(KeyValuePair + param in QueryParams) + request.AddQueryParameter(param.Key, param.Value); + + // add form parameter, if any + foreach(KeyValuePair + param in FormParams) + request.AddParameter(param.Key, param.Value); + + // add file parameter, if any + foreach(KeyValuePair + param in FileParams) + request.AddFile(param.Key, param.Value); + + if (PostBody != null) { + request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter } - public async Task CallApiAsync(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, - Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { - - var request = new RestRequest(Path, Method); - - UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); - - // add default header, if any - foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) - request.AddHeader(defaultHeader.Key, defaultHeader.Value); - - // add header parameter, if any - foreach(KeyValuePair param in HeaderParams) - request.AddHeader(param.Key, param.Value); - - // add query parameter, if any - foreach(KeyValuePair param in QueryParams) - request.AddQueryParameter(param.Key, param.Value); - - // add form parameter, if any - foreach(KeyValuePair param in FormParams) - request.AddParameter(param.Key, param.Value); - - // add file parameter, if any - foreach(KeyValuePair param in FileParams) - request.AddFile(param.Key, param.Value); - - if (PostBody != null) { - request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter - } - - return (Object) await restClient.ExecuteTaskAsync(request); + return (Object) await restClient.ExecuteTaskAsync(request); } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// + /// + + /// Add default header + /// + + /// + + Header field name + /// + + Header field value + /// + public void AddDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); + defaultHeaderMap.Add(key, value); } - /// - /// Get default header - /// - /// Dictionary of default header - public Dictionary GetDefaultHeader() { - return defaultHeaderMap; + /// + + /// Get default header + /// + + /// + Dictionary of default header + public Dictionary + GetDefaultHeader() { + return defaultHeaderMap; } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string + /// + + /// escape string (url-encoded) + /// + + /// + + String to be escaped + /// + Escaped string public string EscapeString(string str) { - return str; + return str; } - /// - /// if parameter is DateTime, output in ISO8601 format - /// if parameter is a list of string, join the list with "," - /// otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string + /// + + /// if parameter is DateTime, output in ISO8601 format + /// if parameter is a list of string, join the list with "," + /// otherwise just return the string + /// + + /// + + The parameter (header, path, query, form) + /// + Formatted string public string ParameterToString(object obj) { - if (obj is DateTime) { - return ((DateTime)obj).ToString ("u"); - } else if (obj is List) { - return String.Join(",", obj as List); - } else { - return Convert.ToString (obj); - } - } + if (obj is DateTime) { + return ((DateTime)obj).ToString ("u"); + } else if (obj is List + ) { + return String.Join(",", obj as List + ); + } else { + return Convert.ToString (obj); + } + } - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public object Deserialize(string content, Type type) { - if (type.GetType() == typeof(Object)) - return (Object)content; + /// + + /// Deserialize the JSON string into a proper object + /// + + /// + + JSON string + /// + + Object type + /// + Object representation of the JSON string + public object Deserialize(string content, Type type) { + if (type.GetType() == typeof(Object)) + return (Object)content; - try - { - return JsonConvert.DeserializeObject(content, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - } + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException e) { + throw new ApiException(500, e.Message); + } + } - /// - /// Serialize an object into JSON string - /// - /// Object - /// JSON string - public string Serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } + /// + + /// Serialize an object into JSON string + /// + + /// + + Object + /// + JSON string + public string Serialize(object obj) { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) { + throw new ApiException(500, e.Message); + } + } - /// - /// Get the API key with prefix - /// - /// Object - /// API key with prefix - public string GetApiKeyWithPrefix (string apiKey) - { - var apiKeyValue = ""; - Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); - var apiKeyPrefix = ""; - if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { - return apiKeyPrefix + " " + apiKeyValue; - } else { - return apiKeyValue; - } - } + /// + + /// Get the API key with prefix + /// + + /// + + Object + /// + API key with prefix + public string GetApiKeyWithPrefix (string apiKey) + { + var apiKeyValue = ""; + Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { + return apiKeyPrefix + " " + apiKeyValue; + } else { + return apiKeyValue; + } + } - /// - /// Update parameters based on authentication - /// - /// Query parameters - /// Header parameters - /// Authentication settings - public void UpdateParamsForAuth(Dictionary QueryParams, Dictionary HeaderParams, string[] AuthSettings) { - if (AuthSettings == null || AuthSettings.Length == 0) - return; - - foreach (string auth in AuthSettings) { - // determine which one to use - switch(auth) { - {{#authMethods}} - case "{{name}}": - {{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + Configuration.password);{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - break; - {{/authMethods}} - default: + /// + + /// Update parameters based on authentication + /// + + /// + + Query parameters + /// + + Header parameters + /// + + Authentication settings + public void UpdateParamsForAuth(Dictionary + QueryParams, Dictionary + HeaderParams, string[] AuthSettings) { + if (AuthSettings == null || AuthSettings.Length == 0) + return; + + foreach (string auth in AuthSettings) { + // determine which one to use + switch(auth) { + {{#authMethods}} + case "{{name}}": + {{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}} + ");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = + GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} + HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + + Configuration.password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: //TODO show warning about security definition not found - break; - } - } + break; + } + } - } + } - /// - /// Encode string in base64 format - /// - /// String to be encoded - public static string Base64Encode(string text) { - var textByte = System.Text.Encoding.UTF8.GetBytes(text); - return System.Convert.ToBase64String(textByte); - } + /// + + /// Encode string in base64 format + /// + + /// + + String to be encoded + public static string Base64Encode(string text) { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } - } -} + } + } diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index 38a340be249..d21aca8814f 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -1,42 +1,61 @@ using System; namespace {{invokerPackage}} { - /// - /// API Exception - /// - public class ApiException : Exception { - /// +/// + + /// API Exception + /// + +public class ApiException : Exception { +/// + /// Gets or sets the error code (HTTP status code) - /// - /// The error code (HTTP status code). - public int ErrorCode { get; set; } + /// + +/// +The error code (HTTP status code). +public int ErrorCode { get; set; } - /// +/// + /// Gets or sets the error content (body json object) - /// - /// The error content (Http response body). - public dynamic ErrorContent { get; private set; } + /// + +/// +The error content (Http response body). +public dynamic ErrorContent { get; private set; } - /// - /// Initializes a new instance of the class. - /// - /// The base path. - public ApiException() {} +/// + + /// Initializes a new instance of the + + class. + /// + +/// +The base path. +public ApiException() {} - /// - /// Initializes a new instance of the class. - /// - /// HTTP status code. - /// Error message. - public ApiException(int errorCode, string message) : base(message) { - this.ErrorCode = errorCode; - } +/// + + /// Initializes a new instance of the + + class. + /// + +/// +HTTP status code. +/// +Error message. +public ApiException(int errorCode, string message) : base(message) { +this.ErrorCode = errorCode; +} - public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { - this.ErrorCode = errorCode; - this.ErrorContent = errorContent; - } - - } +public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { +this.ErrorCode = errorCode; +this.ErrorContent = errorContent; +} + +} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 1f5c00a356d..71f4bb07f14 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -7,41 +7,62 @@ using System.Text; using {{invokerPackage}}; namespace {{invokerPackage}} { - /// - /// Represents a set of configuration settings - /// - public class Configuration{ +/// + + /// Represents a set of configuration settings + /// + +public class Configuration{ - /// +/// + /// Gets or sets the API client. This is the default API client for making HTTP calls. - /// - /// The API client. - public static ApiClient apiClient = new ApiClient(); + /// + +/// +The API client. +public static ApiClient apiClient = new ApiClient(); - /// +/// + /// Gets or sets the username (HTTP basic authentication) - /// - /// The username. - public static String username { get; set; } + /// + +/// +The username. +public static String username { get; set; } - /// +/// + /// Gets or sets the password (HTTP basic authentication) - /// - /// The password. - public static String password { get; set; } + /// + +/// +The password. +public static String password { get; set; } - /// - /// Gets or sets the API key based on the authentication name - /// - /// The API key. - public static Dictionary apiKey = new Dictionary(); +/// + + /// Gets or sets the API key based on the authentication name + /// + +/// +The API key. +public static Dictionary + apiKey = new Dictionary +(); - /// - /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name - /// - /// The prefix of the API key. - public static Dictionary apiKeyPrefix = new Dictionary(); +/// + + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name + /// + +/// +The prefix of the API key. +public static Dictionary + apiKeyPrefix = new Dictionary +(); - } +} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 117446441fa..67dff4c8222 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -8,166 +8,212 @@ using {{modelPackage}}; {{/imports}} namespace {{package}} { - {{#operations}} +{{#operations}} - public interface I{{classname}} { + public interface I{{classname}} { {{#operation}} - /// - /// {{summary}} {{notes}} - /// - {{#allParams}}/// {{description}}{{/allParams}} - /// {{#returnType}}{{{returnType}}}{{/returnType}} - {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + /// + + /// {{summary}} {{notes}} + /// + + {{#allParams}}/// + {{description}}{{/allParams}} + /// + {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - /// - /// {{summary}} {{notes}} - /// - {{#allParams}}/// {{description}}{{/allParams}} - /// {{#returnType}}{{{returnType}}}{{/returnType}} - {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + /// + + /// {{summary}} {{notes}} + /// + + {{#allParams}}/// + {{description}}{{/allParams}} + /// + {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} - } - - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class {{classname}} : I{{classname}} { - - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public {{classname}}(ApiClient apiClient = null) { - if (apiClient == null) { // use the default one in Configuration - this.apiClient = Configuration.apiClient; - } else { - this.apiClient = apiClient; - } } - /// - /// Initializes a new instance of the class. - /// - /// + /// + + /// Represents a collection of functions to interact with the API endpoints + /// + + public class {{classname}} : I{{classname}} { + + /// + + /// Initializes a new instance of the + + class. + /// + + /// + an instance of ApiClient (optional) + /// + + public {{classname}}(ApiClient apiClient = null) { + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } + } + + /// + + /// Initializes a new instance of the + + class. + /// + + /// + public {{classname}}(String basePath) { - this.apiClient = new ApiClient(basePath); + this.apiClient = new ApiClient(basePath); } - /// - /// Sets the base path of the API client. - /// - /// The base path + /// + + /// Sets the base path of the API client. + /// + + /// + The base path public void SetBasePath(String basePath) { - this.apiClient.basePath = basePath; + this.apiClient.basePath = basePath; } - /// - /// Gets the base path of the API client. - /// - /// The base path + /// + + /// Gets the base path of the API client. + /// + + /// + The base path public String GetBasePath(String basePath) { - return this.apiClient.basePath; + return this.apiClient.basePath; } - /// - /// Gets or sets the API client. - /// - /// The API client + /// + + /// Gets or sets the API client. + /// + + /// + The API client public ApiClient apiClient {get; set;} {{#operation}} - /// - /// {{summary}} {{notes}} - /// - {{#allParams}}/// {{description}}{{/allParams}} - /// {{#returnType}}{{{returnType}}}{{/returnType}} - public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + /// + + /// {{summary}} {{notes}} + /// + + {{#allParams}}/// + {{description}}{{/allParams}} + /// + {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); - {{/required}}{{/allParams}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} - var path = "{{path}}"; - path = path.Replace("{format}", "json"); - {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); - {{/pathParams}} + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); + {{/pathParams}} - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - String postBody = null; + var queryParams = new Dictionary + (); + var headerParams = new Dictionary + (); + var formParams = new Dictionary + (); + var fileParams = new Dictionary + (); + String postBody = null; - {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter - {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter - {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} - {{/formParams}} - {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter - {{/bodyParam}} + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}} + {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter + {{/bodyParam}} - // authentication setting, if any - String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - // make the HTTP request - IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + // make the HTTP request + IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); - if (((int)response.StatusCode) >= 400) { + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); - } - {{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} - return;{{/returnType}} - } - - /// - /// {{summary}} {{notes}} - /// - {{#allParams}}/// {{description}}{{/allParams}} - /// {{#returnType}}{{{returnType}}}{{/returnType}} - public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + } + {{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} + } - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); - {{/required}}{{/allParams}} + /// + + /// {{summary}} {{notes}} + /// + + {{#allParams}}/// + {{description}}{{/allParams}} + /// + {{#returnType}}{{{returnType}}}{{/returnType}} + public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - var path = "{{path}}"; - path = path.Replace("{format}", "json"); - {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); - {{/pathParams}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - String postBody = null; + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); + {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter - {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter - {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} - {{/formParams}} - {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter - {{/bodyParam}} + var queryParams = new Dictionary + (); + var headerParams = new Dictionary + (); + var formParams = new Dictionary + (); + var fileParams = new Dictionary + (); + String postBody = null; - // authentication setting, if any - String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}} + {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter + {{/bodyParam}} - // make the HTTP request - IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); - if (((int)response.StatusCode) >= 400) { + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); - } - {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} - return;{{/returnType}} - } + } + {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} + } {{/operation}} - } - {{/operations}} + } +{{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index ce0e62de192..4f1b56a47de 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -6,44 +6,52 @@ using System.Runtime.Serialization; using Newtonsoft.Json; {{#models}} -{{#model}} -namespace {{package}} { + {{#model}} + namespace {{package}} { - /// - /// {{description}} - /// - [DataContract] - public class {{classname}} { - {{#vars}} - {{#description}}/* {{{description}}} */{{/description}} - [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] - public {{{datatype}}} {{name}} { get; set; } + /// + + /// {{description}} + /// + + [DataContract] + public class {{classname}} { + {{#vars}} + {{#description}}/* {{{description}}} */{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] + public {{{datatype}}} {{name}} { get; set; } - {{/vars}} + {{/vars}} - /// - /// Get the string presentation of the object - /// - /// String presentation of the object - public override string ToString() { - var sb = new StringBuilder(); - sb.Append("class {{classname}} {\n"); - {{#vars}} - sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); - {{/vars}} - sb.Append("}\n"); - return sb.ToString(); - } + /// + + /// Get the string presentation of the object + /// + + /// + String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + sb.Append("}\n"); + return sb.ToString(); + } - /// - /// Get the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } + /// + + /// Get the JSON string presentation of the object + /// + + /// + JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } -} - {{/model}} - {{/models}} + } + {{/model}} +{{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml b/modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml index 1dbaf98e644..1eb5e43c7d7 100644 --- a/modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml +++ b/modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml @@ -1,87 +1,87 @@ - + xmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/2.0 + The last segment of the namespace specifies the version + of the AIR runtime required for this application to run. - - AirExecutorApp + minimumPatchLevel - The minimum patch level of the AIR runtime required to run + the application. Optional. + --> - - AirExecutorApp + + AirExecutorApp - - AirExecutorApp + + AirExecutorApp - - v1 + + AirExecutorApp - - + + v1 - - + + - - + + - - - - - AirExecutorApp.swf - - - + + - - + + + + + AirExecutorApp.swf - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - + + + + + + + + + @@ -90,57 +90,57 @@ - - + + - - + + - - + + - - - - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as b/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as index d64cd304d49..f25f4563c07 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as @@ -1,14 +1,10 @@ package io.swagger.event { -import io.swagger.event.Response; - -import flash.events.Event; - /** * Event dispatched by the SDK to communicate success events and failure events. * If a custom dispatcher has been assigned by the consumer on the generated client then the dispatcher dispatches * the ApiClientEvent to indicate success or failure of the invocation using the Response */ -public class ApiClientEvent extends Event{ +public class ApiClientEvent extends Event { /** * Event type to indicate a unsuccessful invocation @@ -19,18 +15,17 @@ public class ApiClientEvent extends Event{ * Event type to indicate a successful invocation */ public static const SUCCESS_EVENT:String = "successfulInvocation"; - + + public function ApiClientEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) { + super(type, bubbles, cancelable); + } /** * The Response object which contains response info */ - public var response: Response; + public var response:Response; /** * Any additional info */ public var message:String; - - public function ApiClientEvent(type:String,bubbles:Boolean = false,cancelable:Boolean = false) { - super(type, bubbles, cancelable); - } } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiError.as b/modules/swagger-codegen/src/main/resources/flash/ApiError.as index c8ac95a5c59..7734d7f9979 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiError.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiError.as @@ -1,10 +1,7 @@ -package io.swagger.exception -{ - public class ApiError extends Error - { - public function ApiError(id:*=0, message:*="") - { - super(message,id); - } - } +package io.swagger.exception { +public class ApiError extends Error { + public function ApiError(id:* = 0, message:* = "") { + super(message, id); + } +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as b/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as index e5ea46480aa..9236e40acbc 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as @@ -1,34 +1,32 @@ -package io.swagger.exception -{ - public class ApiErrorCodes - { - /** - * System exception. - */ - public static const SYSTEM_EXCEPTION: Number = 0; - - /** - * With Arguments as current key. - */ - public static const API_KEY_NOT_VALID: Number = 1000; - /** - * With arguments as current token value - */ - public static const AUTH_TOKEN_NOT_VALID: Number = 1001; - /** - * With arguments as input JSON and output class anme - */ - public static const ERROR_CONVERTING_JSON_TO_JAVA: Number = 1002; - /** - * With arguments as JAVA class name - */ - public static const ERROR_CONVERTING_JAVA_TO_JSON: Number = 1003; - - public static const ERROR_FROM_WEBSERVICE_CALL: Number = 1004; - /** - * With arguments as current API server name - */ - public static const API_SERVER_NOT_VALID: Number = 1005; - - } +package io.swagger.exception { +public class ApiErrorCodes { + /** + * System exception. + */ + public static const SYSTEM_EXCEPTION:Number = 0; + + /** + * With Arguments as current key. + */ + public static const API_KEY_NOT_VALID:Number = 1000; + /** + * With arguments as current token value + */ + public static const AUTH_TOKEN_NOT_VALID:Number = 1001; + /** + * With arguments as input JSON and output class anme + */ + public static const ERROR_CONVERTING_JSON_TO_JAVA:Number = 1002; + /** + * With arguments as JAVA class name + */ + public static const ERROR_CONVERTING_JAVA_TO_JSON:Number = 1003; + + public static const ERROR_FROM_WEBSERVICE_CALL:Number = 1004; + /** + * With arguments as current API server name + */ + public static const API_SERVER_NOT_VALID:Number = 1005; + +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as b/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as deleted file mode 100644 index 897b95a4f6e..00000000000 --- a/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as +++ /dev/null @@ -1,289 +0,0 @@ -package io.swagger.common -{ -import asaxb.xml.bind.ASAXBContext; -import asaxb.xml.bind.Unmarshaller; - -import io.swagger.event.ApiClientEvent; -import io.swagger.event.Response; -import io.swagger.common.ApiUserCredentials; - -import flash.events.EventDispatcher; -import flash.utils.Dictionary; -import flash.utils.describeType; -import flash.xml.XMLDocument; -import flash.xml.XMLNode; - -import mx.messaging.ChannelSet; -import mx.messaging.channels.HTTPChannel; -import mx.messaging.messages.HTTPRequestMessage; -import mx.rpc.AsyncToken; -import mx.rpc.events.FaultEvent; -import mx.rpc.events.ResultEvent; -import mx.rpc.http.HTTPService; -import mx.rpc.xml.SimpleXMLEncoder; -import mx.utils.ObjectUtil; - - -public class ApiInvoker extends EventDispatcher -{ - - private var _apiUsageCredentials:ApiUserCredentials; - internal var _apiProxyServerUrl:String = ""; - private var _baseUrl: String = ""; - internal var _useProxyServer: Boolean = true; - private var _proxyHostName:String = ""; - private var _apiPath: String = ""; - private var _proxyPath: String = ""; - - public var _apiEventNotifier:EventDispatcher; - - private static const DELETE_DATA_DUMMY:String = "dummyDataRequiredForDeleteOverride"; - private static const X_HTTP_OVERRIDE_KEY:String = "X-HTTP-Method-Override"; - private static const CONTENT_TYPE_HEADER_KEY:String = "Content-Type"; - - public function ApiInvoker(apiUsageCredentials: ApiUserCredentials, eventNotifier: EventDispatcher, useProxy: Boolean = true) { - _apiUsageCredentials = apiUsageCredentials; - _useProxyServer = useProxy; - if(_apiUsageCredentials.hostName != null){ - _proxyHostName = _apiUsageCredentials.hostName; - } - _apiPath = _apiUsageCredentials.apiPath; - _proxyPath = _apiUsageCredentials.proxyPath; - _apiProxyServerUrl = _apiUsageCredentials.apiProxyServerUrl; - _apiEventNotifier = eventNotifier; - } - - public function invokeAPI(resourceURL: String, method: String, queryParams: Dictionary, postObject: Object, headerParams: Dictionary): AsyncToken { - //make the communication - if(_useProxyServer) { - resourceURL = _apiProxyServerUrl + resourceURL; - } - else{ - resourceURL = "http://"+ _proxyHostName + _apiPath + resourceURL; - } - - var counter: int = 0; - var symbol: String = "&"; - var paramValue: Object; - for (var paramName:String in queryParams) { - paramValue = queryParams[paramName]; - //var key:String = paramName; - // do stuff - symbol = "&"; - if(counter == 0){ - symbol = "?"; - } - resourceURL = resourceURL + symbol + paramName + "=" + paramValue.toString(); - counter++; - - } -// trace(resourceURL); - //create a httpservice and invoke the rest url waiting for response - var requestHeader:Object = new Object(); - if(headerParams != null) { - for(var key: String in headerParams) { - requestHeader[key] = headerParams[key]; - } - } - - resourceURL = ApiUrlHelper.appendTokenInfo(resourceURL, requestHeader, _apiUsageCredentials); - - var bodyData:String = marshal(postObject).toString();//restRequest.postData; - - return doRestCall(resourceURL, onApiRequestResult, onApiRequestFault, method, bodyData, requestHeader, "application/xml"); - - - } - - private function doRestCall( url : String, resultFunction : Function, faultFunction : Function = null, - restMethod : String = "GET", - bodyData : Object = null, headers: Object = null, contentType:String = "application/xml" ) : AsyncToken - { - var httpService : HTTPService = new HTTPService( ); - - if(headers == null){ - headers = new Object(); - } - httpService.method = restMethod; - - if ( restMethod.toUpperCase() != HTTPRequestMessage.GET_METHOD ) - { - //httpService.method = HTTPRequestMessage.POST_METHOD; - not required as we're using the proxy - if( bodyData == null ) - { - bodyData = new Object(); - } - - if(restMethod == HTTPRequestMessage.DELETE_METHOD){ - headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.DELETE_METHOD; - bodyData = DELETE_DATA_DUMMY; - } - else if(restMethod == HTTPRequestMessage.PUT_METHOD){ - headers[X_HTTP_OVERRIDE_KEY]= HTTPRequestMessage.PUT_METHOD; - } - else{ - headers[CONTENT_TYPE_HEADER_KEY]= contentType; - } - } - else - { - //if the request type is GET and content type is xml then the Flex HTTPService converts it to a POST ... yeah - contentType = null; - } - - httpService.url = url; - httpService.contentType = contentType; - httpService.resultFormat = "e4x"; - httpService.headers = headers; - httpService.addEventListener( ResultEvent.RESULT, resultFunction ); - if( faultFunction != null ) - { - httpService.addEventListener( FaultEvent.FAULT, faultFunction ); - } - if(_useProxyServer){ - httpService.useProxy = true; - - var channelSet: ChannelSet = new ChannelSet(); - var httpChannel: HTTPChannel = new HTTPChannel(); - httpChannel.uri = ApiUrlHelper.getProxyUrl(_proxyHostName, _proxyPath); - channelSet.addChannel(httpChannel); - httpService.channelSet = channelSet; - } - - return httpService.send( bodyData ); - } - - private function onApiRequestResult(event:ResultEvent):void - { - var completionListener: Function = event.token.completionListener; - var result: Object = event.result; - var resultType: Class = event.token.returnType; - var resultObject:Object; - if(resultType != null) { - var context:ASAXBContext = ASAXBContext.newInstance(resultType); - var unmarshaller:Unmarshaller = context.createUnmarshaller(); - var resultXML: XML = new XML(event.result); - try{ - resultObject = unmarshaller.unmarshal(resultXML); - } - catch(error: TypeError){ - var errorResponse: Response = new Response(false, null, "Could not unmarshall response"); - if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher - var failureEvent: ApiClientEvent = new ApiClientEvent(event.token.completionEventType); - failureEvent.response = errorResponse; - _apiEventNotifier.dispatchEvent(failureEvent); - } - } - - if(resultObject is ListWrapper){ - resultObject = ListWrapper(resultObject).getList(); - } - } - - var response : Response = new Response(true, resultObject); - response.requestId = event.token.requestId; - var successEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.SUCCESS_EVENT; - - if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher - var successEvent: ApiClientEvent = new ApiClientEvent(successEventType); - successEvent.response = response; - _apiEventNotifier.dispatchEvent(successEvent); - } - } - - private function onApiRequestFault(event:FaultEvent):void - { - var completionListener: Function = event.token.completionListener; - if(completionListener != null){ - completionListener.call( null, new Response( false, null, event.fault.faultString) ); - } - - var failureEventType: String = event.token.completionEventType != null ? event.token.completionEventType : ApiClientEvent.FAILURE_EVENT; - - if (_apiEventNotifier != null) { //dispatch event via assigned dispatcher - var failureEvent: ApiClientEvent = new ApiClientEvent(failureEventType); - failureEvent.response = new Response( false, null, event.fault.faultString); - _apiEventNotifier.dispatchEvent(failureEvent); - } - } - - - public function marshal(source:Object):Object { -// trace("marshal got - " + source) - if(source is String) { - return source; - } else if(source is Array && source.length > 0) { - var writer:XMLWriter=new XMLWriter(); - var sourceArray: Array = source as Array; - var arrayEnclosure: String = getArrayEnclosure(sourceArray); - writer.xml.setName(arrayEnclosure); - - for (var i:int = 0; i < sourceArray.length; i++) { - var o: Object = sourceArray[i]; - writer.xml.appendChild(marshal(o)); - } - return writer.xml; - } else - return marshalObject(source); - } - - public function marshalObject(source:Object):XML - { - var writer:XMLWriter=new XMLWriter(); - var objDescriptor:XML=describeType(source); - var property:XML; - var propertyType:String; - var propertyValue:Object; - - var qualifiedClassName:String=objDescriptor.@name; - qualifiedClassName=qualifiedClassName.replace("::","."); - var className: String = qualifiedClassName.substring(qualifiedClassName.lastIndexOf(".") + 1); - className = className().toLowerCase() + className.substring(1); - writer.xml.setName(className); - - for each(property in objDescriptor.elements("variable")){ - propertyValue=source[property.@name]; - if (propertyValue!=null){ - if (ObjectUtil.isSimple(propertyValue)){ - writer.addProperty(property.@name, propertyValue.toString()); - } - else { - writer.addProperty(property.@name, marshal(propertyValue).toXMLString()); - } - } - } - for each(property in objDescriptor.elements("accessor")){ - if (property.@access=="readonly"){ - continue; - } - propertyValue=source[property.@name]; - if (source[property.@name]!=null){ - if (ObjectUtil.isSimple(propertyValue)){ - writer.addProperty(property.@name, propertyValue.toString()); - } - else { - writer.addProperty(property.@name, marshal(propertyValue).toXMLString()); - } - } - } - return writer.xml; - } - - public function escapeString(str: String): String { - return str; - } - - private function getArrayEnclosure(arr: Array) : String { - if(arr != null && arr.length > 0) { - var className: String = flash.utils.getQualifiedClassName(arr[0]) - if(className.indexOf("::") > 0) - className = className.substr(className.indexOf("::") + 2, className.length) - - return className.substring(0, 1).toLowerCase() + className.substring(1, className.length) + "s"; - } else - return ""; - } - - -} -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as b/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as index 4333c6c7e4c..57c5bc00819 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as @@ -1,6 +1,4 @@ package io.swagger.common { -import io.swagger.common.ApiUserCredentials; - /** * @private * Internal class for the Rest client @@ -12,17 +10,17 @@ internal class ApiUrlHelper { private static const HTTP_URL_PREFIX:String = "http://"; - internal static function appendTokenInfo(restUrl:String, requestHeader: Object, credentials: ApiUserCredentials): String { + internal static function appendTokenInfo(restUrl:String, requestHeader:Object, credentials:ApiUserCredentials):String { //checks for the presence api credentials on client initialization and not repeated here - if(restUrl.indexOf("?") == -1){ + if (restUrl.indexOf("?") == -1) { restUrl += ( "?" + API_URL_KEY + "=" + credentials.apiToken ); } - else{ + else { restUrl += ( "&" + API_URL_KEY + "=" + credentials.apiToken ); } requestHeader.api_key = credentials.apiToken; - if(credentials.authToken != null && credentials.authToken != ""){ + if (credentials.authToken != null && credentials.authToken != "") { restUrl += ( "&" + AUTH_TOKEN_URL_KEY + "=" + credentials.authToken ); requestHeader.auth_token = credentials.authToken; } @@ -30,7 +28,7 @@ internal class ApiUrlHelper { return restUrl; } - internal static function getProxyUrl(hostName: String, proxyPath: String): String{ + internal static function getProxyUrl(hostName:String, proxyPath:String):String { if (hostName(hostName.length - 1) == "/") //remove trailing slash { hostName = hostName.substring(0, hostName.length - 1); diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as b/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as index 118d917a247..8e03c99a17f 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as @@ -5,6 +5,24 @@ package io.swagger.common { * */ public class ApiUserCredentials { + /** + * Constructor of ApiUserCredentials + * @param apiToken An apitoken that is passed along with the requests + * @param authToken A valid auth_token which could necessary for certain operations + * @param hostName The host name for the Rest API eg. api.companyName.com + * @param userId The userId which is required for certain operations - currently, get user lists + */ + public function ApiUserCredentials(hostName:String, apiPath:String, apiToken:String, + authToken:String = null, userId:Number = -1, apiProxyServerUrl:String = "", + proxyPath:String = null) { + this.hostName = hostName; + this.apiToken = apiToken; + this.authToken = authToken; + this.userId = userId; + this.apiPath = apiPath; + this.apiProxyServerUrl = apiProxyServerUrl; + this.proxyPath = proxyPath; + } /** * An apitoken that is passed along with the requests */ @@ -21,43 +39,21 @@ public class ApiUserCredentials { * The host name for the Rest API eg. api.companyName.com */ public var hostName:String; - - /** - * The base path to the api resources - used along with the hostname - * eg. /v4 - */ - public var apiPath: String; - - /** - * The base path to the blazeds proxy - * eg. /v4/messagebroker/restproxy - */ - public var proxyPath: String; - - /** - * If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with - * the value useProxy as true - */ - public var apiProxyServerUrl: String; - /** - * Constructor of ApiUserCredentials - * @param apiToken An apitoken that is passed along with the requests - * @param authToken A valid auth_token which could necessary for certain operations - * @param hostName The host name for the Rest API eg. api.companyName.com - * @param userId The userId which is required for certain operations - currently, get user lists + * The base path to the api resources - used along with the hostname + * eg. /v4 */ - public function ApiUserCredentials(hostName: String, apiPath: String, apiToken: String, - authToken: String = null, userId: Number = -1, apiProxyServerUrl: String="", - proxyPath: String = null) { - this.hostName = hostName; - this.apiToken = apiToken; - this.authToken = authToken; - this.userId = userId; - this.apiPath = apiPath; - this.apiProxyServerUrl = apiProxyServerUrl; - this.proxyPath = proxyPath; - } + public var apiPath:String; + /** + * The base path to the blazeds proxy + * eg. /v4/messagebroker/restproxy + */ + public var proxyPath:String; + /** + * If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with + * the value useProxy as true + */ + public var apiProxyServerUrl:String; } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as b/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as index b22890ad1d1..20ac7cb555f 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as +++ b/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as @@ -1,9 +1,7 @@ -package io.swagger.common -{ - public interface ListWrapper - { - - function getList(): Array; - - } +package io.swagger.common { +public interface ListWrapper { + + function getList():Array; + +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/Response.as b/modules/swagger-codegen/src/main/resources/flash/Response.as index a43b7980a38..b225ab9b6ce 100644 --- a/modules/swagger-codegen/src/main/resources/flash/Response.as +++ b/modules/swagger-codegen/src/main/resources/flash/Response.as @@ -6,50 +6,47 @@ package io.swagger.event { */ public class Response { - /** - * Indicates whether the invoked operation failed or succeeded - */ - public var isSuccess:Boolean; - - /** - * The payload of the succesful operation eg. a Word in a WordRequest - */ - public var payload:Object; - - /** - * Error message in case of failure - */ - public var errorMessage:String; - - /** - * A request Id that was passed in by the user as a param when invoking the operation - */ - public var requestId:String; private static const API_ERROR_MSG:String = "Api error response: "; - public function Response(isSuccessful: Boolean, payload: Object = null, errorMessage: String = null, requestId: String = null) { - this.isSuccess = isSuccessful; - this.payload = payload; - this.errorMessage = getFriendlyMessage(errorMessage); - } - - private static function getFriendlyMessage(errorMessage: String): String{ - var result: String = errorMessage; - if(errorMessage == null) + private static function getFriendlyMessage(errorMessage:String):String { + var result:String = errorMessage; + if (errorMessage == null) return null; - var errorCode: String; - var errorCodeArray: Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/); - if(errorCodeArray != null && errorCodeArray.length == 1){ + var errorCode:String; + var errorCodeArray:Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/); + if (errorCodeArray != null && errorCodeArray.length == 1) { errorCode = String(errorCodeArray[0]); } - var msgArray: Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/); - if(msgArray != null && msgArray.length == 1){ + var msgArray:Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/); + if (msgArray != null && msgArray.length == 1) { result = API_ERROR_MSG + String(msgArray[0]); } return result; } - public function toString(): String { + public function Response(isSuccessful:Boolean, payload:Object = null, errorMessage:String = null, requestId:String = null) { + this.isSuccess = isSuccessful; + this.payload = payload; + this.errorMessage = getFriendlyMessage(errorMessage); + } + /** + * Indicates whether the invoked operation failed or succeeded + */ + public var isSuccess:Boolean; + /** + * The payload of the succesful operation eg. a Word in a WordRequest + */ + public var payload:Object; + /** + * Error message in case of failure + */ + public var errorMessage:String; + /** + * A request Id that was passed in by the user as a param when invoking the operation + */ + public var requestId:String; + + public function toString():String { return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")"; } } diff --git a/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as b/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as index 059de642a74..23b96ec17f2 100644 --- a/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as +++ b/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as @@ -1,75 +1,63 @@ -package io.swagger.common -{ - import io.swagger.common.ApiUserCredentials; - - import flash.events.EventDispatcher; - import flash.events.IEventDispatcher; - - import mx.utils.UIDUtil; - - public class SwaggerApi extends EventDispatcher - { - - protected var _apiUsageCredentials:ApiUserCredentials; - protected var _apiEventNotifier:EventDispatcher; - protected var _apiInvoker: ApiInvoker; - - protected var _useProxyServer: Boolean = false; +package io.swagger.common { +public class SwaggerApi extends EventDispatcher { - - /** - * Constructor for the api client - * @param apiCredentials Wrapper object for tokens and hostName required towards authentication - * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response - */ - public function SwaggerApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { - super(); - _apiUsageCredentials = apiCredentials; - _apiEventNotifier = eventDispatcher; - } - - public function useProxyServer(value:Boolean, proxyServerUrl: String = null):void { - _useProxyServer = value; - } - - protected function getApiInvoker():ApiInvoker { - if(_apiInvoker == null){ - if(_apiEventNotifier == null){ - _apiEventNotifier = this; - } - _apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer); - } - return _apiInvoker; - } - - protected function getUniqueId():String { - return UIDUtil.createUID(); - } - - /** - * Method for returning the path value - * For a string value an empty value is returned if the value is null - * @param value - * @return - */ - protected static function toPathValue(value: Object): String { - if(value is Array){ - return arrayToPathValue(value as Array); - } - return value == null ? "" : value.toString(); - } - - /** - * Method for returning a path value - * For a list of objects a comma separated string is returned - * @param objects - * @return - */ - protected static function arrayToPathValue(objects: Array): String { - var out: String = ""; - - return objects.join(","); - } - - } + /** + * Method for returning the path value + * For a string value an empty value is returned if the value is null + * @param value + * @return + */ + protected static function toPathValue(value:Object):String { + if (value is Array) { + return arrayToPathValue(value as Array); + } + return value == null ? "" : value.toString(); + } + + /** + * Method for returning a path value + * For a list of objects a comma separated string is returned + * @param objects + * @return + */ + protected static function arrayToPathValue(objects:Array):String { + var out:String = ""; + + return objects.join(","); + } + + /** + * Constructor for the api client + * @param apiCredentials Wrapper object for tokens and hostName required towards authentication + * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response + */ + public function SwaggerApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) { + super(); + _apiUsageCredentials = apiCredentials; + _apiEventNotifier = eventDispatcher; + } + protected var _apiUsageCredentials:ApiUserCredentials; + protected var _apiEventNotifier:EventDispatcher; + protected var _apiInvoker:ApiInvoker; + protected var _useProxyServer:Boolean = false; + + public function useProxyServer(value:Boolean, proxyServerUrl:String = null):void { + _useProxyServer = value; + } + + protected function getApiInvoker():ApiInvoker { + if (_apiInvoker == null) { + if (_apiEventNotifier == null) { + _apiEventNotifier = this; + } + _apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer); + } + return _apiInvoker; + } + + protected function getUniqueId():String { + return UIDUtil.createUID(); + } + +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as b/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as index 0b08066775b..ec4ab73455b 100644 --- a/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as +++ b/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as @@ -1,28 +1,24 @@ -package io.swagger.common -{ - public class XMLWriter - { - public var xml:XML; - - public function XMLWriter() - { - xml=; - } - - public function reset():void { - xml=new XML(); - } - - public function addProperty(propertyName:String, propertyValue:String):XML { - var xmlProperty:XML= - xmlProperty.setName(propertyName); - xmlProperty.appendChild(propertyValue); - xml.appendChild(xmlProperty); - return xmlProperty; - } - - public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void { - xml.elements(propertyName)[0].@[attribute]=attributeValue; - } - } +package io.swagger.common { +public class XMLWriter { + public function XMLWriter() { + xml = ; + } + public var xml:XML; + + public function reset():void { + xml = new XML(); + } + + public function addProperty(propertyName:String, propertyValue:String):XML { + var xmlProperty:XML = + xmlProperty.setName(propertyName); + xmlProperty.appendChild(propertyValue); + xml.appendChild(xmlProperty); + return xmlProperty; + } + + public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void { + xml.elements(propertyName)[0].@[attribute] = attributeValue; + } +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/api.mustache b/modules/swagger-codegen/src/main/resources/flash/api.mustache index b1f11e92438..b00f2ee2c8a 100644 --- a/modules/swagger-codegen/src/main/resources/flash/api.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/api.mustache @@ -15,26 +15,26 @@ import flash.utils.Dictionary; import flash.events.EventDispatcher; {{#operations}} -public class {{classname}} extends SwaggerApi { + public class {{classname}} extends SwaggerApi { /** * Constructor for the {{classname}} api client * @param apiCredentials Wrapper object for tokens and hostName required towards authentication * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response */ public function {{classname}}(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { - super(apiCredentials, eventDispatcher); + super(apiCredentials, eventDispatcher); } -{{#operation}} + {{#operation}} public static const event_{{nickname}}: String = "{{nickname}}"; -{{/operation}} + {{/operation}} -{{#operation}} + {{#operation}} - /* - * Returns {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} - */ - public function {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): String { + /* + * Returns {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} + */ + public function {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): String { // create path and map variables var path: String = "{{path}}".replace(/{format}/g,"xml"){{#pathParams}}.replace("{" + "{{paramName}}" + "}", getApiInvoker().escapeString({{{paramName}}})){{/pathParams}}; @@ -43,14 +43,14 @@ public class {{classname}} extends SwaggerApi { var headerParams: Dictionary = new Dictionary(); {{#requiredParamCount}} - // verify required params are set - if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiError(400, "missing required params"); + // verify required params are set + if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { + throw new ApiError(400, "missing required params"); } {{/requiredParamCount}} {{#queryParams}}if("null" != String({{paramName}})) - queryParams["{{paramName}}"] = toPathValue({{paramName}}); + queryParams["{{paramName}}"] = toPathValue({{paramName}}); {{/queryParams}} {{#headerParams}}headerParams["{{paramName}}"] = toPathValue({{paramName}}); @@ -66,8 +66,8 @@ public class {{classname}} extends SwaggerApi { token.returnType = {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null {{/returnType}}; return requestId; - } + } {{/operation}} -} - {{/operations}} + } +{{/operations}} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/facetValue.as b/modules/swagger-codegen/src/main/resources/flash/facetValue.as index c6bfa1f27d1..e421c0498dc 100644 --- a/modules/swagger-codegen/src/main/resources/flash/facetValue.as +++ b/modules/swagger-codegen/src/main/resources/flash/facetValue.as @@ -1,8 +1,8 @@ package com.wordnik.client.model { - public class FacetValue { - public var value: String = null; - public var count: Number = 0; - } +public class FacetValue { + public var value:String = null; + public var count:Number = 0; +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flash/model.mustache b/modules/swagger-codegen/src/main/resources/flash/model.mustache index c3369514e80..8f81853fb6d 100644 --- a/modules/swagger-codegen/src/main/resources/flash/model.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/model.mustache @@ -4,37 +4,37 @@ package {{package}} { {{/imports}} {{#models}} -{{#model}} - [XmlRootNode(name="{{classname}}")] - public class {{classname}} { - {{#vars}} + {{#model}} + [XmlRootNode(name="{{classname}}")] + public class {{classname}} { + {{#vars}} - {{#description}}/* {{description}} */ - {{/description}} + {{#description}}/* {{description}} */ + {{/description}} - {{#isList}} - // This declaration below of _{{name}}_obj_class is to force flash compiler to include this class - private var _{{name}}_obj_class: {{baseType}} = null; - [XmlElementWrapper(name="{{name}}")] - [XmlElements(name="{{nameSingular}}", type="{{baseType}}")] - {{/isList}} - {{#isNotContainer}}[XmlElement(name="{{name}}")] - {{/isNotContainer}} - public var {{name}}: {{{datatype}}} = {{{defaultValue}}}; + {{#isList}} + // This declaration below of _{{name}}_obj_class is to force flash compiler to include this class + private var _{{name}}_obj_class: {{baseType}} = null; + [XmlElementWrapper(name="{{name}}")] + [XmlElements(name="{{nameSingular}}", type="{{baseType}}")] + {{/isList}} + {{#isNotContainer}}[XmlElement(name="{{name}}")] + {{/isNotContainer}} + public var {{name}}: {{{datatype}}} = {{{defaultValue}}}; - {{/vars}} + {{/vars}} public function toString(): String { - var str: String = "{{classname}}: "; - {{#vars}} + var str: String = "{{classname}}: "; + {{#vars}} str += " ({{name}}: " + {{name}} + ")"; - {{/vars}} - return str; + {{/vars}} + return str; } -} -{{/model}} - {{/models}} + } + {{/model}} +{{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/flash/modelList.mustache b/modules/swagger-codegen/src/main/resources/flash/modelList.mustache index 7741902bcaa..423aaf8d961 100644 --- a/modules/swagger-codegen/src/main/resources/flash/modelList.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/modelList.mustache @@ -5,19 +5,19 @@ import io.swagger.common.ListWrapper; {{/imports}} {{#models}} -{{#model}} - public class {{classname}}List implements ListWrapper { + {{#model}} + public class {{classname}}List implements ListWrapper { // This declaration below of _{{name}}_obj_class is to force flash compiler to include this class private var _{{classVarName}}_obj_class: {{package}}.{{classname}} = null; [XmlElements(name="{{classVarName}}", type="{{package}}.{{classname}}")] public var {{classVarName}}: Array = new Array(); public function getList(): Array{ - return {{classVarName}}; + return {{classVarName}}; } -} -{{/model}} - {{/models}} + } + {{/model}} +{{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache index 2fd81183a5b..b9adf4d8d92 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache @@ -1,3 +1,5 @@ -{{#isBodyParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isBodyParam}} +
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} \ No newline at end of file +
Body Parameter — {{description}} {{#defaultValue}} + default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache index 97f342e60d7..66770da842e 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache @@ -1,3 +1,5 @@ -{{#isFormParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isFormParam}} +
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Form Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isFormParam}} \ No newline at end of file +
Form Parameter — {{description}} {{#defaultValue}} + default: {{{defaultValue}}}{{/defaultValue}}
{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache index 903713493be..709b79e3738 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache @@ -1,3 +1,5 @@ -{{#isHeaderParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isHeaderParam}} +
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Header Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isHeaderParam}} \ No newline at end of file +
Header Parameter — {{description}} {{#defaultValue}} + default: {{{defaultValue}}}{{/defaultValue}}
{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index ce881084bc2..09248273010 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -1,61 +1,76 @@ - - + + API Reference - - -

{{{appName}}}

-
{{{appDescription}}} for {{partner}}
- {{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} - {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} - {{#version}}
Version: {{{version}}}
{{/version}} -
{{{licenseInfo}}}
-
{{{licenseUrl}}}
-

Access

-
Customize this message as you see fit!
-

Methods

- {{#apiInfo}} - {{#apis}} - {{#operations}}{{#operation}} -
-
{{httpMethod}}: {{path}}
-
{{#tags}}{{this}}{{/tags}}
-
{{nickname}} {{summary}}
-
{{notes}}
+ + +

{{{appName}}}

-

Parameters

-
- {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} - {{/allParams}} -
-

Return type

+
{{{appDescription}}} for {{partner}}
+{{#infoUrl}} +
More information: {{{infoUrl}}}
{{/infoUrl}} +{{#infoEmail}} +
Contact Info: {{{infoEmail}}}
{{/infoEmail}} +{{#version}} +
Version: {{{version}}}
{{/version}} +
{{{licenseInfo}}}
+
{{{licenseUrl}}}
+

Access

- +
Customize this message as you see fit!
+

Methods

+{{#apiInfo}} + {{#apis}} + {{#operations}}{{#operation}} +
+
+
{{httpMethod}}: {{path}}
+
+
{{#tags}}{{this}}{{/tags}}
+
{{nickname}} {{summary}}
+
{{notes}}
- {{#examples}} -

Example data

-
Content-Type: {{{contentType}}}
-
{{example}}
- {{/examples}} -
-
- {{/operation}}{{/operations}} - {{/apis}}{{/apiInfo}} +

Parameters

-

Models

- {{#models}} - {{#model}} -
-

{{classname}}

-
- {{#vars}}
{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}
{{datatype}} {{description}}
- {{/vars}} -
-
- {{/model}} - {{/models}} - - +
+ {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} + {{/allParams}} +
+ +

Return type

+ + + + {{#examples}} +

Example data

+ +
Content-Type: {{{contentType}}}
+
{{example}}
+ {{/examples}} +
+ +
+ {{/operation}}{{/operations}} + {{/apis}}{{/apiInfo}} + +

Models

+{{#models}} + {{#model}} +
+

{{classname}}

+ +
+ {{#vars}} +
{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}
+
{{datatype}} {{description}}
+ {{/vars}} +
+ +
+ {{/model}} +{{/models}} + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache index b47805a4f04..6270f601c8a 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache @@ -1,3 +1,5 @@ -{{#isPathParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isPathParam}} +
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Path Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isPathParam}} \ No newline at end of file +
Path Parameter — {{description}} {{#defaultValue}} + default: {{{defaultValue}}}{{/defaultValue}}
{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache index 52147fbd718..323ace6a27e 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache @@ -1,3 +1,5 @@ -{{#isQueryParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+{{#isQueryParam}} +
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Query Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isQueryParam}} \ No newline at end of file +
Query Parameter — {{description}} {{#defaultValue}} + default: {{{defaultValue}}}{{/defaultValue}}
{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index 14ab06a7f7e..d628ff11ff8 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -1,151 +1,151 @@ -body { - font-family: Trebuchet MS, sans-serif; - font-size: 15px; - color: #444; - margin-right: 24px; +body { +font-family: Trebuchet MS, sans-serif; +font-size: 15px; +color: #444; +margin-right: 24px; } -h1 { - font-size: 25px; +h1 { +font-size: 25px; } -h2 { - font-size: 20px; +h2 { +font-size: 20px; } -h3 { - font-size: 16px; - font-weight: bold; +h3 { +font-size: 16px; +font-weight: bold; } -hr { - height: 1px; - border: 0; - color: #ddd; - background-color: #ddd; - display: none; +hr { +height: 1px; +border: 0; +color: #ddd; +background-color: #ddd; +display: none; } .app-desc { - clear: both; - margin-left: 20px; +clear: both; +margin-left: 20px; } .param-name { - width: 100%; +width: 100%; } .license-info { - margin-left: 20px; +margin-left: 20px; } .license-url { - margin-left: 20px; +margin-left: 20px; } .model { - margin: 0 0 0px 20px; +margin: 0 0 0px 20px; } .method { - margin-left: 20px; +margin-left: 20px; } -.method-notes { - margin: 10px 0 20px 0; - font-size: 90%; - color: #555; +.method-notes { +margin: 10px 0 20px 0; +font-size: 90%; +color: #555; } pre { - padding: 10px; - margin-bottom: 2px; +padding: 10px; +margin-bottom: 2px; } pre.get { - background-color: #0f6ab4; +background-color: #0f6ab4; } pre.post { - background-color: #10a54a; +background-color: #10a54a; } pre.put { - background-color: #c5862b; +background-color: #c5862b; } pre.delete { - background-color: #a41e22; +background-color: #a41e22; } -.huge { - color: #fff; +.huge { +color: #fff; } pre.example { - background-color: #f3f3f3; - padding: 10px; - border: 1px solid #ddd; +background-color: #f3f3f3; +padding: 10px; +border: 1px solid #ddd; } code { - white-space: pre; +white-space: pre; } .nickname { - font-weight: bold; +font-weight: bold; } .method-path { - font-size: 1.5em; - background-color: #0f6ab4; +font-size: 1.5em; +background-color: #0f6ab4; } .parameter { - width: 500px; +width: 500px; } .param { - width: 500px; - padding: 10px 0 0 20px; - font-weight: bold; +width: 500px; +padding: 10px 0 0 20px; +font-weight: bold; } .param-desc { - width: 700px; - padding: 0 0 0 20px; - color: #777; +width: 700px; +padding: 0 0 0 20px; +color: #777; } .param-type { - font-style: italic; +font-style: italic; } .field-label { - padding: 0; - margin: 0; - clear: both; +padding: 0; +margin: 0; +clear: both; } -.field-items { - padding: 0 0 15px 0; - margin-bottom: 15px; +.field-items { +padding: 0 0 15px 0; +margin-bottom: 15px; } .return-type { - clear: both; - padding-bottom: 10px; +clear: both; +padding-bottom: 10px; } .param-header { - font-weight: bold; +font-weight: bold; } .method-tags { - text-align: right; +text-align: right; } .method-tag { - background: none repeat scroll 0% 0% #24A600; - border-radius: 3px; - padding: 2px 10px; - margin: 2px; - color: #FFF; - display: inline-block; - text-decoration: none; +background: none repeat scroll 0% 0% #24A600; +border-radius: 3px; +padding: 2px 10px; +margin: 2px; +color: #FFF; +display: inline-block; +text-decoration: none; } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/logback.xml b/modules/swagger-codegen/src/main/resources/logback.xml index bcfc95e538d..010fdca0cfe 100644 --- a/modules/swagger-codegen/src/main/resources/logback.xml +++ b/modules/swagger-codegen/src/main/resources/logback.xml @@ -1,12 +1,12 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache index 85d1f3211a1..f0300e95656 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache @@ -4,22 +4,22 @@ var url = require('url'); {{#operations}} -var {{classname}} = require('./{{classname}}Service'); + var {{classname}} = require('./{{classname}}Service'); -{{#operation}} + {{#operation}} -module.exports.{{nickname}} = function {{nickname}} (req, res, next) { - {{#allParams}}var {{paramName}} = req.swagger.params['{{baseName}}'].value; - {{/allParams}} + module.exports.{{nickname}} = function {{nickname}} (req, res, next) { + {{#allParams}}var {{paramName}} = req.swagger.params['{{baseName}}'].value; + {{/allParams}} - var result = {{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + var result = {{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); -}; -{{/operation}} + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); + }; + {{/operation}} {{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache index 0562c2f0c37..57d0ff040c9 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache @@ -8,9 +8,9 @@ var serverPort = {{serverPort}}; // swaggerRouter configuration var options = { - swaggerUi: '/swagger.json', - controllers: './controllers', - useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode) +swaggerUi: '/swagger.json', +controllers: './controllers', +useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode) }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) @@ -18,21 +18,21 @@ var swaggerDoc = require('./api/swagger.json'); // Initialize the Swagger middleware swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { - // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain - app.use(middleware.swaggerMetadata()); +// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain +app.use(middleware.swaggerMetadata()); - // Validate Swagger requests - app.use(middleware.swaggerValidator()); +// Validate Swagger requests +app.use(middleware.swaggerValidator()); - // Route validated requests to appropriate controller - app.use(middleware.swaggerRouter(options)); +// Route validated requests to appropriate controller +app.use(middleware.swaggerRouter(options)); - // Serve the Swagger documents and Swagger UI - app.use(middleware.swaggerUi()); +// Serve the Swagger documents and Swagger UI +app.use(middleware.swaggerUi()); - // Start the server - http.createServer(app).listen({{serverPort}}, function () { - console.log('Your server is listening on port %d (http://localhost:%d)', {{serverPort}}, {{serverPort}}); - console.log('Swagger-ui is available on http://localhost:%d/docs', {{serverPort}}); - }); +// Start the server +http.createServer(app).listen({{serverPort}}, function () { +console.log('Your server is listening on port %d (http://localhost:%d)', {{serverPort}}, {{serverPort}}); +console.log('Swagger-ui is available on http://localhost:%d/docs', {{serverPort}}); +}); }); \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 7add6e813fe..ace5125d47a 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -1,15 +1,15 @@ { - "name": "{{projectName}}", - "version": "{{appVersion}}", - "description": "{{appDescription}}", - "main": "index.js", - "keywords": [ - "swagger" - ], - "license": "MIT", - "private": true, - "dependencies": { - "connect": "^3.2.0", - "swagger-tools": "0.8.*" - } +"name": "{{projectName}}", +"version": "{{appVersion}}", +"description": "{{appDescription}}", +"main": "index.js", +"keywords": [ +"swagger" +], +"license": "MIT", +"private": true, +"dependencies": { +"connect": "^3.2.0", +"swagger-tools": "0.8.*" +} } diff --git a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache index d7c2ade5079..76d582a0356 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache @@ -1,18 +1,18 @@ 'use strict'; {{#operations}} -{{#operation}} -exports.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#operation}} + exports.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - var examples = {}; - {{#examples}} - examples['{{contentType}}'] = {{{example}}}; - {{/examples}} + var examples = {}; + {{#examples}} + examples['{{contentType}}'] = {{{example}}}; + {{/examples}} - {{#returnType}} - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; - {{/returnType}} -} -{{/operation}} + {{#returnType}} + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + {{/returnType}} + } + {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache index 8b4c8d33bdc..ed6a91567ad 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -1,42 +1,42 @@ { - "swagger": "2.0", - "info": { - "title": "{{appName}}", - "description": "{{appDescription}}", - "version": "{{apiVersion}}" - }, +"swagger": "2.0", +"info": { +"title": "{{appName}}", +"description": "{{appDescription}}", +"version": "{{apiVersion}}" +}, {{#apiInfo}} - "produces": ["application/json"], - "host": "localhost:{{serverPort}}", - "basePath": "{{contextPath}}", - "paths": { -{{#apis}} -{{#operations}} - {{#operation}} - "{{{path}}}": { - "{{httpMethod}}": { - "x-swagger-router-controller": "{{classname}}", - "tags": ["{{baseName}}"], - "operationId": "{{operationId}}",{{#hasParams}} - "parameters": [ - {{#allParams}} - {{{jsonSchema}}}{{#hasMore}},{{/hasMore}} - {{/allParams}} - ],{{/hasParams}} - "responses": { - {{#responses}} - "{{code}}": {{{jsonSchema}}} - {{#hasMore}},{{/hasMore}} - {{/responses}} - } - } - } {{#hasMore}},{{/hasMore}} - {{/operation}} - {{#hasMore}},{{/hasMore}} -{{/operations}} -{{/apis}} + "produces": ["application/json"], + "host": "localhost:{{serverPort}}", + "basePath": "{{contextPath}}", + "paths": { + {{#apis}} + {{#operations}} + {{#operation}} + "{{{path}}}": { + "{{httpMethod}}": { + "x-swagger-router-controller": "{{classname}}", + "tags": ["{{baseName}}"], + "operationId": "{{operationId}}",{{#hasParams}} + "parameters": [ + {{#allParams}} + {{{jsonSchema}}}{{#hasMore}},{{/hasMore}} + {{/allParams}} + ],{{/hasParams}} + "responses": { + {{#responses}} + "{{code}}": {{{jsonSchema}}} + {{#hasMore}},{{/hasMore}} + {{/responses}} + } + } + } {{#hasMore}},{{/hasMore}} + {{/operation}} + {{#hasMore}},{{/hasMore}} + {{/operations}} + {{/apis}} {{/apiInfo}} - }, "definitions": { - {{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} - } +}, "definitions": { +{{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} +} } diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache index 1e5e7135574..86ef0c702af 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache @@ -12,88 +12,88 @@ #pragma mark - Singletion Methods + (instancetype) sharedConfig { - static SWGConfiguration *shardConfig = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - shardConfig = [[self alloc] init]; - }); - return shardConfig; +static SWGConfiguration *shardConfig = nil; +static dispatch_once_t onceToken; +dispatch_once(&onceToken, ^{ +shardConfig = [[self alloc] init]; +}); +return shardConfig; } #pragma mark - Initialize Methods - (instancetype) init { - self = [super init]; - if (self) { - self.username = @""; - self.password = @""; - self.mutableApiKey = [NSMutableDictionary dictionary]; - self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - } - return self; +self = [super init]; +if (self) { +self.username = @""; +self.password = @""; +self.mutableApiKey = [NSMutableDictionary dictionary]; +self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; +} +return self; } #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; - } - else if ([self.apiKey objectForKey:key]) { - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; - } - else { - return @""; - } +if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { +return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; +} +else if ([self.apiKey objectForKey:key]) { +return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; +} +else { +return @""; +} } - (NSString *) getBasicAuthToken { - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; +NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; +NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; +basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + +return basicAuthCredentials; } #pragma mark - Setter Methods - (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +[self.mutableApiKey setValue:value forKey:field]; } - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +[self.mutableApiKeyPrefix setValue:value forKey:field]; } #pragma mark - Getter Methods - (NSDictionary *) apiKey { - return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; +return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; } - (NSDictionary *) apiKeyPrefix { - return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; +return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; } #pragma mark - - (NSDictionary *) authSettings { - return @{ {{#authMethods}}{{#isApiKey}} - @"{{name}}": @{ - @"type": @"api_key", - @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, - @"key": @"{{keyParamName}}", - @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] - }, - {{/isApiKey}}{{#isBasic}} - @"{{name}}": @{ - @"type": @"basic", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getBasicAuthToken] - }, - {{/isBasic}}{{/authMethods}} - }; +return @{ {{#authMethods}}{{#isApiKey}} + @"{{name}}": @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}}{{#isBasic}} + @"{{name}}": @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}}{{/authMethods}} +}; } @end diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache index 33023ca3c6f..529e07aa81c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache @@ -1,56 +1,57 @@ -#import +#import + @interface SWGConfiguration : NSObject /** - * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setValue:forApiKeyField:`. - */ +* Api key values for Api Key type Authentication +* +* To add or remove api key, use `setValue:forApiKeyField:`. +*/ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** - * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. - */ +* Api key prefix values to be prepend to the respective api key +* +* To add or remove prefix, use `setValue:forApiKeyPrefixField:`. +*/ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication - */ +* Usename and Password for Basic type Authentication +*/ @property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** - * Get configuration singleton instance - */ +* Get configuration singleton instance +*/ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` - */ +* Sets field in `apiKey` +*/ - (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; /** - * Sets field in `apiKeyPrefix` - */ +* Sets field in `apiKeyPrefix` +*/ - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; /** - * Get API key (with prefix if set) - */ +* Get API key (with prefix if set) +*/ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token - */ +* Get Basic Auth token +*/ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings - */ +* Get Authentication Setings +*/ - (NSDictionary *) authSettings; @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 40d75bd806b..b01f59a6857 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -1,226 +1,226 @@ {{#operations}} -#import "{{classname}}.h" -#import "SWGFile.h" -#import "SWGQueryParamCollection.h" -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} + #import "{{classname}}.h" + #import "SWGFile.h" + #import "SWGQueryParamCollection.h" + {{#imports}}#import "{{import}}.h" + {{/imports}} + {{newline}} -@interface {{classname}} () + @interface {{classname}} () @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; -@end + @end -@implementation {{classname}} + @implementation {{classname}} -static NSString * basePath = @"{{basePath}}"; + static NSString * basePath = @"{{basePath}}"; -#pragma mark - Initialize methods + #pragma mark - Initialize methods -- (id) init { + - (id) init { self = [super init]; if (self) { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; - self.defaultHeaders = [NSMutableDictionary dictionary]; + self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; + self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; -} + } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; - } - self.defaultHeaders = [NSMutableDictionary dictionary]; + if (apiClient) { + self.apiClient = apiClient; + } + else { + self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; + } + self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; -} + } -#pragma mark - + #pragma mark - -+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { + +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static {{classname}}* singletonAPI = nil; if (singletonAPI == nil) { - singletonAPI = [[{{classname}} alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; + singletonAPI = [[{{classname}} alloc] init]; + [singletonAPI addHeader:headerValue forKey:key]; } return singletonAPI; -} + } -+(void) setBasePath:(NSString*)path { + +(void) setBasePath:(NSString*)path { basePath = path; -} + } -+(NSString*) getBasePath { + +(NSString*) getBasePath { return basePath; -} + } --(void) addHeader:(NSString*)value forKey:(NSString*)key { + -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; -} + } --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { + -(void) setHeaderValue:(NSString*) value + forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; -} + } --(unsigned long) requestQueueSize { + -(unsigned long) requestQueueSize { return [SWGApiClient requestQueueSize]; -} + } -{{#operation}} -/*! - * {{{summary}}} - * {{{notes}}} -{{#allParams}} * \param {{paramName}} {{{description}}} -{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ --(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} + {{#operation}} + /*! + * {{{summary}}} + * {{{notes}}} + {{#allParams}} * \param {{paramName}} {{{description}}} + {{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + -(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} {{/allParams}} {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - NSAssert({{paramName}} != nil, @"Missing the required parameter `{{paramName}}` when calling {{nickname}}"); - {{/required}}{{/allParams}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + NSAssert({{paramName}} != nil, @"Missing the required parameter `{{paramName}}` when calling {{nickname}}"); + {{/required}}{{/allParams}} - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; - {{/pathParams}} + {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; + {{/pathParams}} - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if({{paramName}} != nil) { + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + {{#queryParams}}if({{paramName}} != nil) { {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; + queryParams[@"{{baseName}}"] = [[SWGQueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} - } - {{/queryParams}} - NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + } + {{/queryParams}} + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - {{#headerParams}}if({{paramName}} != nil) + {{#headerParams}}if({{paramName}} != nil) headerParams[@"{{baseName}}"] = {{paramName}}; - {{/headerParams}} - - // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if ([headerParams[@"Accept"] length] == 0) { + {{/headerParams}} + + // HTTP header `Accept` + headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if ([headerParams[@"Accept"] length] == 0) { [headerParams removeObjectForKey:@"Accept"]; - } + } - // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { + // response content type + NSString *responseContentType; + if ([headerParams objectForKey:@"Accept"]) { responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { + } + else { responseContentType = @""; - } + } - // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + // request content type + NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; - // Authentication setting - NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - id bodyDictionary = nil; - {{#bodyParam}} - id __body = {{paramName}}; + // Authentication setting + NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - if(__body != nil && [__body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)__body) { + id bodyDictionary = nil; + {{#bodyParam}} + id __body = {{paramName}}; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; + [objs addObject:[(SWGObject*)dict toDictionary]]; } else{ - [objs addObject:dict]; + [objs addObject:dict]; } - } - bodyDictionary = objs; - } - else if([__body respondsToSelector:@selector(toDictionary)]) { - bodyDictionary = [(SWGObject*)__body toDictionary]; - } - else if([__body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)__body; - NSDictionary *JSON = + } + bodyDictionary = objs; + } + else if([__body respondsToSelector:@selector(toDictionary)]) { + bodyDictionary = [(SWGObject*)__body toDictionary]; + } + else if([__body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)__body; + NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] - options: NSJSONReadingMutableContainers - error: &error]; - bodyDictionary = JSON; - } - {{/bodyParam}} - {{^bodyParam}} + options: NSJSONReadingMutableContainers + error: &error]; + bodyDictionary = JSON; + } + {{/bodyParam}} + {{^bodyParam}} - NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - {{#formParams}} - {{#notFile}} - formParams[@"{{paramName}}"] = {{paramName}}; - {{/notFile}}{{#isFile}} - requestContentType = @"multipart/form-data"; - if(bodyDictionary == nil) { - bodyDictionary = [[NSMutableArray alloc] init]; - } - if({{paramName}} != nil) { - [bodyDictionary addObject:{{paramName}}]; - {{paramName}}.paramName = @"{{baseName}}"; - } - {{/isFile}} - if(bodyDictionary == nil) { - bodyDictionary = [[NSMutableArray alloc] init]; - } - [bodyDictionary addObject:formParams]; - {{/formParams}} - {{/bodyParam}} + {{#formParams}} + {{#notFile}} + formParams[@"{{paramName}}"] = {{paramName}}; + {{/notFile}}{{#isFile}} + requestContentType = @"multipart/form-data"; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } + if({{paramName}} != nil) { + [bodyDictionary addObject:{{paramName}}]; + {{paramName}}.paramName = @"{{baseName}}"; + } + {{/isFile}} + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } + [bodyDictionary addObject:formParams]; + {{/formParams}} + {{/bodyParam}} - {{#requiredParamCount}} - {{#requiredParams}} - if({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} + {{#requiredParamCount}} + {{#requiredParams}} + if({{paramName}} == nil) { + // error + } + {{/requiredParams}} + {{/requiredParamCount}} - {{#returnContainer}} - // response is in a container - {{>apiBodyResponseWithContainer}}{{/returnContainer}} + {{#returnContainer}} + // response is in a container + {{>apiBodyResponseWithContainer}}{{/returnContainer}} - {{#returnSimpleType}} - // non container response + {{#returnSimpleType}} + // non container response - {{#returnTypeIsPrimitive}} - // primitive response - {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} + {{#returnTypeIsPrimitive}} + // primitive response + {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} - {{#returnBaseType}} - // complex response - {{>apiNonPrimitiveResponse}}{{/returnBaseType}} - {{/returnSimpleType}} + {{#returnBaseType}} + // complex response + {{>apiNonPrimitiveResponse}}{{/returnBaseType}} + {{/returnSimpleType}} - {{^returnSimpleType}}{{^returnContainer}} - // it's void - {{>voidResponse}} - {{/returnContainer}}{{/returnSimpleType}} -} + {{^returnSimpleType}}{{^returnContainer}} + // it's void + {{>voidResponse}} + {{/returnContainer}}{{/returnSimpleType}} + } -{{/operation}} + {{/operation}} -{{newline}} + {{newline}} {{/operations}} @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 65f4c39e0b3..74c55d3ffa4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -1,4 +1,5 @@ -#import +#import + {{#imports}}#import "{{import}}.h" {{/imports}} #import "SWGObject.h" @@ -6,36 +7,36 @@ {{newline}} {{#operations}} -@interface {{classname}}: NSObject + @interface {{classname}}: NSObject -@property(nonatomic, assign)SWGApiClient *apiClient; + @property(nonatomic, assign)SWGApiClient *apiClient; --(instancetype) initWithApiClient:(SWGApiClient *)apiClient; --(void) addHeader:(NSString*)value forKey:(NSString*)key; --(unsigned long) requestQueueSize; -+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; -{{#operation}} -/** + -(instancetype) initWithApiClient:(SWGApiClient *)apiClient; + -(void) addHeader:(NSString*)value forKey:(NSString*)key; + -(unsigned long) requestQueueSize; + +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; + +(void) setBasePath:(NSString*)basePath; + +(NSString*) getBasePath; + {{#operation}} + /** - {{{summary}}} - {{#notes}}{{{notes}}}{{/notes}} + {{{summary}}} + {{#notes}}{{{notes}}}{{/notes}} - {{#allParams}}@param {{paramName}} {{description}} - {{/allParams}} + {{#allParams}}@param {{paramName}} {{description}} + {{/allParams}} - return type: {{{returnType}}} - */ --(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} -{{/hasMore}}{{/allParams}} - {{#returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} + return type: {{{returnType}}} + */ + -(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} + {{/hasMore}}{{/allParams}} + {{#returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} -{{newline}} -{{/operation}} + {{newline}} + {{/operation}} {{/operations}} @end diff --git a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache index acaeaf2ddf5..48d49a2f1ca 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache @@ -1,38 +1,38 @@ - // {{returnContainer}} container response type - return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - {{#isMapContainer}} - NSDictionary *result = nil; - if (data) { - result = [[NSDictionary alloc]initWithDictionary: data]; - } - completionBlock(data, nil); - {{/isMapContainer}}{{#isListContainer}} - {{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - {{#returnTypeIsPrimitive}} - {{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict]; - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil]; - {{/returnTypeIsPrimitive}} - [objs addObject:d]; - } - completionBlock(({{{returnType}}})objs, nil); - } - {{/returnBaseType}} - {{/isListContainer}} - }]; +// {{returnContainer}} container response type +return [self.apiClient dictionary: requestUrl +method: @"{{httpMethod}}" +queryParams: queryParams +body: bodyDictionary +headerParams: headerParams +authSettings: authSettings +requestContentType: requestContentType +responseContentType: responseContentType +completionBlock: ^(NSDictionary *data, NSError *error) { +if (error) { +{{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}} +return; +} +{{#isMapContainer}} + NSDictionary *result = nil; + if (data) { + result = [[NSDictionary alloc]initWithDictionary: data]; + } + completionBlock(data, nil); +{{/isMapContainer}}{{#isListContainer}} + {{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + {{#returnTypeIsPrimitive}} + {{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict]; + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}} + {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil]; + {{/returnTypeIsPrimitive}} + [objs addObject:d]; + } + completionBlock(({{{returnType}}})objs, nil); + } + {{/returnBaseType}} +{{/isListContainer}} +}]; diff --git a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache index da8ea063bfb..d240c9f2f30 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache @@ -1,24 +1,24 @@ - {{^returnTypeIsPrimitive}} +{{^returnTypeIsPrimitive}} // comples response type return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - {{#returnType}}{{returnType}} result = nil; - if (data) { - result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil]; - } - {{#returnType}}completionBlock(result , nil);{{/returnType}} - {{/returnType}} - }]; - {{/returnTypeIsPrimitive}} + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} + {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} + return; + } + {{#returnType}}{{returnType}} result = nil; + if (data) { + result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil]; + } + {{#returnType}}completionBlock(result , nil);{{/returnType}} + {{/returnType}} + }]; +{{/returnTypeIsPrimitive}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache index d44d356526d..b60b4b54bbc 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache @@ -1,36 +1,36 @@ - // primitive response type - {{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; - completionBlock(result, nil); - }]; - {{/returnBaseType}} - {{^returnBaseType}} +// primitive response type +{{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl +method: @"{{httpMethod}}" +queryParams: queryParams +body: bodyDictionary +headerParams: headerParams +authSettings: authSettings +requestContentType: requestContentType +responseContentType: responseContentType +completionBlock: ^(NSString *data, NSError *error) { +if (error) { +completionBlock(nil, error); +return; +} +{{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; +completionBlock(result, nil); +}]; +{{/returnBaseType}} +{{^returnBaseType}} // no return base type - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - {{/returnBaseType}} + return [self.apiClient stringWithCompletionBlock: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; +{{/returnBaseType}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index b728e6bb06c..00c6297b71a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -1,26 +1,26 @@ {{#models}} -{{#model}} -#import "{{classname}}.h" + {{#model}} + #import "{{classname}}.h" -@implementation {{classname}} - -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; -} + @implementation {{classname}} -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; + + (JSONKeyMapper *)keyMapper + { + return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; + } - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} + + (BOOL)propertyIsOptional:(NSString *)propertyName + { + NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; -{{/model}} -@end + if ([optionalProperties containsObject:propertyName]) { + return YES; + } + else { + return NO; + } + } + + {{/model}} + @end {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index 81ac19a0b73..12cb782a731 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -1,22 +1,23 @@ -#import +#import + #import "SWGObject.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} {{#models}} -{{#model}} + {{#model}} -@protocol {{classname}} -@end - -@interface {{classname}} : SWGObject + @protocol {{classname}} + @end -{{#vars}} -{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} - */{{/description}} -@property(nonatomic) {{{ datatype }}} {{name}}; -{{/vars}} + @interface {{classname}} : SWGObject -@end -{{/model}} + {{#vars}} + {{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} + */{{/description}} + @property(nonatomic) {{{ datatype }}} {{name}}; + {{/vars}} + + @end + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache index 7bbbc14c066..602bbcb807f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache @@ -1,15 +1,15 @@ - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; +return [self.apiClient stringWithCompletionBlock: requestUrl +method: @"{{httpMethod}}" +queryParams: queryParams +body: bodyDictionary +headerParams: headerParams +authSettings: authSettings +requestContentType: requestContentType +responseContentType: responseContentType +completionBlock: ^(NSString *data, NSError *error) { +if (error) { +completionBlock(error); +return; +} +completionBlock(nil); +}]; diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 2bcdd6da690..f216d6bc3bc 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -22,14 +22,14 @@ use WWW::{{invokerPackage}}::Configuration; sub new { - my $class = shift; - my (%args) = ( - 'ua' => LWP::UserAgent->new, - 'base_url' => '{{basePath}}', - @_ - ); +my $class = shift; +my (%args) = ( +'ua' => LWP::UserAgent->new, +'base_url' => '{{basePath}}', +@_ +); - return bless \%args, $class; +return bless \%args, $class; } # Set the user agent of the API client @@ -37,20 +37,20 @@ sub new # @param string $user_agent The user agent of the API client # sub set_user_agent { - my ($self, $user_agent) = @_; - $self->{http_user_agent}= $user_agent; +my ($self, $user_agent) = @_; +$self->{http_user_agent}= $user_agent; } # Set timeout # # @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] -# +# sub set_timeout { - my ($self, $seconds) = @_; - if (!looks_like_number($seconds)) { - croak('Timeout variable must be numeric.'); - } - $self->{http_timeout} = $seconds; +my ($self, $seconds) = @_; +if (!looks_like_number($seconds)) { +croak('Timeout variable must be numeric.'); +} +$self->{http_timeout} = $seconds; } # make the HTTP request @@ -61,70 +61,70 @@ sub set_timeout { # @param array $headerParams parameters to be place in request header # @return mixed sub call_api { - my $self = shift; - my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; +my $self = shift; +my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; - # update parameters based on authentication settings - $self->update_params_for_auth($header_params, $query_params, $auth_settings); +# update parameters based on authentication settings +$self->update_params_for_auth($header_params, $query_params, $auth_settings); - my $_url = $self->{base_url} . $resource_path; +my $_url = $self->{base_url} . $resource_path; - # build query - if (%$query_params) { - $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); - } +# build query +if (%$query_params) { +$_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); +} - # body data - $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string - my $_body_data = %$post_params ? $post_params : $body_data; +# body data +$body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string +my $_body_data = %$post_params ? $post_params : $body_data; - # Make the HTTP request - my $_request; - if ($method eq 'POST') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = POST($_url, %$header_params, Content => $_body_data); +# Make the HTTP request +my $_request; +if ($method eq 'POST') { +# multipart +$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? +'form-data' : $header_params->{'Content-Type'}; - } - elsif ($method eq 'PUT') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; +$_request = POST($_url, %$header_params, Content => $_body_data); - $_request = PUT($_url, %$header_params, Content => $_body_data); +} +elsif ($method eq 'PUT') { +# multipart +$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? +'form-data' : $header_params->{'Content-Type'}; - } - elsif ($method eq 'GET') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = GET($_url, %$header_params); - } - elsif ($method eq 'HEAD') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = HEAD($_url,%$header_params); - } - elsif ($method eq 'DELETE') { #TODO support form data - my $headers = HTTP::Headers->new(%$header_params); - $_request = DELETE($_url, %$headers); - } - elsif ($method eq 'PATCH') { #TODO - } - else { - } - - $self->{ua}->timeout($self->{http_timeout} || $WWW::{{invokerPackage}}::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::{{invokerPackage}}::Configuration::http_user_agent); - - my $_response = $self->{ua}->request($_request); +$_request = PUT($_url, %$header_params, Content => $_body_data); - unless ($_response->is_success) { - croak("API Exception(".$_response->code."): ".$_response->message); - } - - return $_response->content; +} +elsif ($method eq 'GET') { +my $headers = HTTP::Headers->new(%$header_params); +$_request = GET($_url, %$header_params); +} +elsif ($method eq 'HEAD') { +my $headers = HTTP::Headers->new(%$header_params); +$_request = HEAD($_url,%$header_params); +} +elsif ($method eq 'DELETE') { #TODO support form data +my $headers = HTTP::Headers->new(%$header_params); +$_request = DELETE($_url, %$headers); +} +elsif ($method eq 'PATCH') { #TODO +} +else { +} + +$self->{ua}->timeout($self->{http_timeout} || $WWW::{{invokerPackage}}::Configuration::http_timeout); +$self->{ua}->agent($self->{http_user_agent} || $WWW::{{invokerPackage}}::Configuration::http_user_agent); + +my $_response = $self->{ua}->request($_request); + +unless ($_response->is_success) { +croak("API Exception(".$_response->code."): ".$_response->message); +} + +return $_response->content; } @@ -133,8 +133,8 @@ sub call_api { # @param string $value a string which will be part of the path # @return string the serialized object sub to_path_value { - my ($self, $value) = @_; - return uri_escape($self->to_string($value)); +my ($self, $value) = @_; +return uri_escape($self->to_string($value)); } @@ -145,12 +145,12 @@ sub to_path_value { # @param object $object an object to be serialized to a string # @return string the serialized object sub to_query_value { - my ($self, $object) = @_; - if (is_array($object)) { - return implode(',', $object); - } else { - return $self->to_string($object); - } +my ($self, $object) = @_; +if (is_array($object)) { +return implode(',', $object); +} else { +return $self->to_string($object); +} } @@ -160,8 +160,8 @@ sub to_query_value { # @param string $value a string which will be part of the header # @return string the header string sub to_header_value { - my ($self, $value) = @_; - return $self->to_string($value); +my ($self, $value) = @_; +return $self->to_string($value); } # Take value and turn it into a string suitable for inclusion in @@ -170,8 +170,8 @@ sub to_header_value { # @param string $value the value of the form parameter # @return string the form string sub to_form_value { - my ($self, $value) = @_; - return $self->to_string($value); +my ($self, $value) = @_; +return $self->to_string($value); } # Take value and turn it into a string suitable for inclusion in @@ -180,50 +180,50 @@ sub to_form_value { # @param string $value the value of the parameter # @return string the header string sub to_string { - my ($self, $value) = @_; - if (ref($value) eq "DateTime") { # datetime in ISO8601 format - return $value->datetime(); - } - else { - return $value; - } +my ($self, $value) = @_; +if (ref($value) eq "DateTime") { # datetime in ISO8601 format +return $value->datetime(); +} +else { +return $value; +} } # Deserialize a JSON string into an object -# +# # @param string $class class name is passed as a string # @param string $data data of the body # @return object an instance of $class sub deserialize { - my ($self, $class, $data) = @_; - $log->debugf("deserializing %s for %s", $data, $class); - my $_result; +my ($self, $class, $data) = @_; +$log->debugf("deserializing %s for %s", $data, $class); +my $_result; - if (not defined $data) { - return undef; - } elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash - $_result = \(json_decode $data); - } elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data - return $data if $data eq '[]'; # return if empty array +if (not defined $data) { +return undef; +} elsif ( lc(substr($class, 0, 4)) eq 'map[') { #hash +$_result = \(json_decode $data); +} elsif ( lc(substr($class, 0, 6)) eq 'array[' ) { # array of data +return $data if $data eq '[]'; # return if empty array - my $_sub_class = substr($class, 6, -1); - my @_json_data = json_decode $data; - my @_values = (); - foreach my $_value (@_json_data) { - push @_values, $self->deserialize($_sub_class, $_value); - } - $_result = \@_values; - } elsif ($class eq 'DateTime') { - $_result = DateTime->from_epoch(epoch => str2time($data)); - } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { #TODO revise the primitive type - $_result= $data; - } else { # model - my $_instance = use_module("WWW::{{invokerPackage}}::Object::$class")->new; - $_result = $_instance->from_hash(decode_json $data); - } +my $_sub_class = substr($class, 6, -1); +my @_json_data = json_decode $data; +my @_values = (); +foreach my $_value (@_json_data) { +push @_values, $self->deserialize($_sub_class, $_value); +} +$_result = \@_values; +} elsif ($class eq 'DateTime') { +$_result = DateTime->from_epoch(epoch => str2time($data)); +} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { #TODO revise the primitive type +$_result= $data; +} else { # model +my $_instance = use_module("WWW::{{invokerPackage}}::Object::$class")->new; +$_result = $_instance->from_hash(decode_json $data); +} - return $_result; +return $_result; } @@ -232,15 +232,15 @@ sub deserialize # @return String Accept (e.g. application/json) sub select_header_accept { - my ($self, @header) = @_; +my ($self, @header) = @_; - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return undef; - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } +if (@header == 0 || (@header == 1 && $header[0] eq '')) { +return undef; +} elsif (grep(/^application\/json$/i, @header)) { +return 'application/json'; +} else { +return join(',', @header); +} } @@ -249,15 +249,15 @@ sub select_header_accept # @return String Content-Type (e.g. application/json) sub select_header_content_type { - my ($self, @header) = @_; +my ($self, @header) = @_; - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return 'application/json'; # default to application/json - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } +if (@header == 0 || (@header == 1 && $header[0] eq '')) { +return 'application/json'; # default to application/json +} elsif (grep(/^application\/json$/i, @header)) { +return 'application/json'; +} else { +return join(',', @header); +} } @@ -266,38 +266,38 @@ sub select_header_content_type # @return string API key with the prefix sub get_api_key_with_prefix { - my ($self, $api_key) = @_; - if ($WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}) { - return $WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; - } else { - return $WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; - } +my ($self, $api_key) = @_; +if ($WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}) { +return $WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; +} else { +return $WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; +} } # update hearder and query param based on authentication setting -# +# # @param array $headerParams header parameters (by ref) # @param array $queryParams query parameters (by ref) # @param array $authSettings array of authentication scheme (e.g ['api_key']) sub update_params_for_auth { - my ($self, $header_params, $query_params, $auth_settings) = @_; +my ($self, $header_params, $query_params, $auth_settings) = @_; - return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); +return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); - # one endpoint can have more than 1 auth settings - foreach my $auth (@$auth_settings) { - # determine which one to use - if (!defined($auth)) { - } - {{#authMethods}}elsif ($auth eq '{{name}}') { - {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{invokerPackage}}::Configuration::username.":".$WWW::{{invokerPackage}}::Configuration::password);{{/isBasic}} - {{#isOAuth}}# TODO support oauth{{/isOAuth}} - } - {{/authMethods}} - else { - # TODO show warning about security definition not found - } - } +# one endpoint can have more than 1 auth settings +foreach my $auth (@$auth_settings) { +# determine which one to use +if (!defined($auth)) { +} +{{#authMethods}}elsif ($auth eq '{{name}}') { +{{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{invokerPackage}}::Configuration::username.":".$WWW::{{invokerPackage}}::Configuration::password);{{/isBasic}} +{{#isOAuth}}# TODO support oauth{{/isOAuth}} +} +{{/authMethods}} +else { +# TODO show warning about security definition not found +} +} } diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index b4a7885a798..47c8052d033 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -21,56 +21,56 @@ use DateTime; # return json string sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); +return decode_json(JSON->new->convert_blessed->encode( shift )); } # used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $self->get_attribute_map) { - if (defined $self->{$_key}) { - $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; - } - } - return $_data; +sub TO_JSON { +my $self = shift; +my $_data = {}; +foreach my $_key (keys $self->get_attribute_map) { +if (defined $self->{$_key}) { +$_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; +} +} +return $_data; } # from json string sub from_hash { - my ($self, $hash) = @_; - # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->get_swagger_types ) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { - push @_array, $self->_deserialize($_subclass, $_element); - } - $self->{$_key} = \@_array; - } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); - } else { - $log->debugf("warning: %s not defined\n", $_key); - } - } - - return $self; +my ($self, $hash) = @_; +# loop through attributes and use swagger_types to deserialize the data +while ( my ($_key, $_type) = each $self->get_swagger_types ) { +if ($_type =~ /^array\[/i) { # array +my $_subclass = substr($_type, 6, -1); +my @_array = (); +foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { +push @_array, $self->_deserialize($_subclass, $_element); } - +$self->{$_key} = \@_array; +} elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime +$self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); +} else { +$log->debugf("warning: %s not defined\n", $_key); +} +} + +return $self; +} + # deserialize non-array data sub _deserialize { - my ($self, $type, $data) = @_; - $log->debugf("deserializing %s with %s",Dumper($data), $type); - - if ($type eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { - return $data; - } else { # hash(model) - my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; - return $_instance->from_hash($data); - } +my ($self, $type, $data) = @_; +$log->debugf("deserializing %s with %s",Dumper($data), $type); + +if ($type eq 'DateTime') { +return DateTime->from_epoch(epoch => str2time($data)); +} elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { +return $data; +} else { # hash(model) +my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; +return $_instance->from_hash($data); +} } 1; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index c67139ee33d..c92aea5d4a6 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -14,7 +14,7 @@ # limitations under the License. # # -# NOTE: This class is auto generated by the swagger code generator program. +# NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # package WWW::{{invokerPackage}}::{{classname}}; @@ -22,7 +22,7 @@ package WWW::{{invokerPackage}}::{{classname}}; require 5.6.0; use strict; use warnings; -use utf8; +use utf8; use Exporter; use Carp qw( croak ); use Log::Any qw($log); @@ -31,111 +31,111 @@ use WWW::{{invokerPackage}}::ApiClient; use WWW::{{invokerPackage}}::Configuration; {{#operations}} -our @EXPORT_OK = qw( - {{#operation}}{{{nickname}}} - {{/operation}} -); + our @EXPORT_OK = qw( + {{#operation}}{{{nickname}}} + {{/operation}} + ); -sub new { + sub new { my $class = shift; my $default_api_client = $WWW::{{invokerPackage}}::Configuration::api_client ? $WWW::{{invokerPackage}}::Configuration::api_client : WWW::{{invokerPackage}}::ApiClient->new; my (%self) = ( - 'api_client' => $default_api_client, - @_ + 'api_client' => $default_api_client, + @_ ); #my $self = { # #api_client => $options->{api_client} # api_client => $default_api_client - #}; + #}; bless \%self, $class; -} + } {{#operation}} - # - # {{{nickname}}} - # - # {{{summary}}} - # - {{#allParams}} # @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} - {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - # - sub {{nickname}} { - my ($self, %args) = @_; + # + # {{{nickname}}} + # + # {{{summary}}} + # + {{#allParams}} # @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + # + sub {{nickname}} { + my ($self, %args) = @_; - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - unless (exists $args{'{{paramName}}'}) { - croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); - } - {{/required}}{{/allParams}} + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + unless (exists $args{'{{paramName}}'}) { + croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} - # parse inputs - my $_resource_path = '{{path}}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '{{path}}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = '{{httpMethod}}'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = '{{httpMethod}}'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); - {{#queryParams}}# query params - if ( exists $args{'{{paramName}}'}) { + {{#queryParams}}# query params + if ( exists $args{'{{paramName}}'}) { $query_params->{'{{baseName}}'} = $self->{api_client}->to_query_value($args{'{{paramName}}'}); - }{{/queryParams}} - {{#headerParams}}# header params - if ( exists $args{'{{paramName}}'}) { + }{{/queryParams}} + {{#headerParams}}# header params + if ( exists $args{'{{paramName}}'}) { $header_params->{'{{baseName}}'} = $self->{api_client}->to_header_value($args{'{{paramName}}'}); - }{{/headerParams}} - {{#pathParams}}# path params - if ( exists $args{'{{paramName}}'}) { + }{{/headerParams}} + {{#pathParams}}# path params + if ( exists $args{'{{paramName}}'}) { my $_base_variable = "{" . "{{baseName}}" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'{{paramName}}'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - }{{/pathParams}} - {{#formParams}}# form params - if ( exists $args{'{{paramName}}'} ) { + }{{/pathParams}} + {{#formParams}}# form params + if ( exists $args{'{{paramName}}'} ) { {{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'}; push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'}; {{/isFile}} {{^isFile}}$form_params->{'{{baseName}}'} = $self->{api_client}->to_form_value($args{'{{paramName}}'}); {{/isFile}} - }{{/formParams}} - my $_body_data; - {{#bodyParams}}# body params - if ( exists $args{'{{paramName}}'}) { + }{{/formParams}} + my $_body_data; + {{#bodyParams}}# body params + if ( exists $args{'{{paramName}}'}) { $_body_data = $args{'{{paramName}}'}; - }{{/bodyParams}} + }{{/bodyParams}} - # authentication setting, if any - my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + # authentication setting, if any + my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - # make the API Call - {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response); - return $_response_object;{{/returnType}} - {{^returnType}}$self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - {{/returnType}} - } - {{/operation}} -{{newline}} + } + my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response); + return $_response_object;{{/returnType}} + {{^returnType}}$self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + {{/returnType}} + } + {{/operation}} + {{newline}} {{/operations}} 1; diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index c527957a9b1..2e76edc87b4 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -1,58 +1,58 @@ {{#models}} -{{#model}} -package WWW::{{invokerPackage}}::Object::{{classname}}; + {{#model}} + package WWW::{{invokerPackage}}::Object::{{classname}}; -require 5.6.0; -use strict; -use warnings; -use utf8; -use JSON qw(decode_json); -use Data::Dumper; -use Module::Runtime qw(use_module); -use Log::Any qw($log); -use Date::Parse; -use DateTime; + require 5.6.0; + use strict; + use warnings; + use utf8; + use JSON qw(decode_json); + use Data::Dumper; + use Module::Runtime qw(use_module); + use Log::Any qw($log); + use Date::Parse; + use DateTime; -use base "WWW::{{invokerPackage}}::Object::BaseObject"; + use base "WWW::{{invokerPackage}}::Object::BaseObject"; -# -#{{description}} -# -#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -# + # + #{{description}} + # + #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. + # -my $swagger_types = { - {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} -}; - -my $attribute_map = { - {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} -}; - -# new object -sub new { - my ($class, %args) = @_; - my $self = { - {{#vars}}#{{#description}}{{{description}}}{{/description}} - '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, + my $swagger_types = { + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - }; + }; - return bless $self, $class; -} + my $attribute_map = { + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + }; -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} + # new object + sub new { + my ($class, %args) = @_; + my $self = { + {{#vars}}#{{#description}}{{{description}}}{{/description}} + '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, + {{/hasMore}}{{/vars}} + }; -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} + return bless $self, $class; + } -1; -{{/model}} + # get swagger type of the attribute + sub get_swagger_types { + return $swagger_types; + } + + # get attribute mappping + sub get_attribute_map { + return $attribute_map; + } + + 1; + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 6356143f914..f9a80ca07ca 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -43,407 +43,407 @@ class ApiClient { function __construct($host = null) { if ($host === null) { $this->host = '{{basePath}}'; - } else { - $this->host = $host; - } - } +} else { +$this->host = $host; +} +} - /** - * add default header - * - * @param string $header_name header name (e.g. Token) - * @param string $header_value header value (e.g. 1z8wp3) - */ - public function addDefaultHeader($header_name, $header_value) { - if (!is_string($header_name)) - throw new \InvalidArgumentException('Header name must be a string.'); +/** +* add default header +* +* @param string $header_name header name (e.g. Token) +* @param string $header_value header value (e.g. 1z8wp3) +*/ +public function addDefaultHeader($header_name, $header_value) { +if (!is_string($header_name)) +throw new \InvalidArgumentException('Header name must be a string.'); - self::$default_header[$header_name] = $header_value; - } +self::$default_header[$header_name] = $header_value; +} - /** - * get the default header - * - * @return array default header - */ - public function getDefaultHeader() { - return self::$default_header; - } +/** +* get the default header +* +* @return array default header +*/ +public function getDefaultHeader() { +return self::$default_header; +} - /** - * delete the default header based on header name - * - * @param string $header_name header name (e.g. Token) - */ - public function deleteDefaultHeader($header_name) { - unset(self::$default_header[$header_name]); - } +/** +* delete the default header based on header name +* +* @param string $header_name header name (e.g. Token) +*/ +public function deleteDefaultHeader($header_name) { +unset(self::$default_header[$header_name]); +} - /** - * set the user agent of the api client - * - * @param string $user_agent the user agent of the api client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) - throw new \InvalidArgumentException('User-agent must be a string.'); +/** +* set the user agent of the api client +* +* @param string $user_agent the user agent of the api client +*/ +public function setUserAgent($user_agent) { +if (!is_string($user_agent)) +throw new \InvalidArgumentException('User-agent must be a string.'); - $this->user_agent= $user_agent; - } +$this->user_agent= $user_agent; +} - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } +/** +* get the user agent of the api client +* +* @return string user agent +*/ +public function getUserAgent($user_agent) { +return $this->user_agent; +} - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); +/** +* set the HTTP timeout value +* +* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] +*/ +public function setTimeout($seconds) { +if (!is_numeric($seconds) || $seconds < 0) +throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - $this->curl_timeout = $seconds; - } +$this->curl_timeout = $seconds; +} - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } +/** +* get the HTTP timeout value +* +* @return string HTTP timeout value +*/ +public function getTimeout() { +return $this->curl_timeout; +} - /** - * Get API key (with prefix if set) - * @param string key name - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; - } else { - return; - } - } +/** +* Get API key (with prefix if set) +* @param string key name +* @return string API key with the prefix +*/ +public function getApiKeyWithPrefix($apiKey) { +if (isset(Configuration::$apiKeyPrefix[$apiKey])) { +return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; +} else if (isset(Configuration::$apiKey[$apiKey])) { +return Configuration::$apiKey[$apiKey]; +} else { +return; +} +} - /** - * update hearder and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; +/** +* update hearder and query param based on authentication setting +* +* @param array $headerParams header parameters (by ref) +* @param array $queryParams query parameters (by ref) +* @param array $authSettings array of authentication scheme (e.g ['api_key']) +*/ +public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) +{ +if (count($authSettings) == 0) +return; - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - {{#authMethods}} - case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - break; - {{/authMethods}} - default: - //TODO show warning about security definition not found - } - } - } - - /** - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { +// one endpoint can have more than 1 auth settings +foreach($authSettings as $auth) { +// determine which one to use +switch($auth) { +{{#authMethods}} + case '{{name}}': + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; +{{/authMethods}} +default: +//TODO show warning about security definition not found +} +} +} - $headers = array(); +/** +* @param string $resourcePath path to method endpoint +* @param string $method method to call +* @param array $queryParams parameters to be place in query URL +* @param array $postData parameters to be placed in POST body +* @param array $headerParams parameters to be place in request header +* @return mixed +*/ +public function callApi($resourcePath, $method, $queryParams, $postData, +$headerParams, $authSettings) { - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); +$headers = array(); - # construct the http header - $headerParams = array_merge((array)self::$default_header, (array)$headerParams); +# determine authentication setting +$this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } +# construct the http header +$headerParams = array_merge((array)self::$default_header, (array)$headerParams); - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { - $postData = http_build_query($postData); - } - else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); - } +foreach ($headerParams as $key => $val) { +$headers[] = "$key: $val"; +} - $url = $this->host . $resourcePath; +// form data +if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { +$postData = http_build_query($postData); +} +else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model +$postData = json_encode($this->sanitizeForSerialization($postData)); +} - $curl = curl_init(); - // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); - } - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); +$url = $this->host . $resourcePath; - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); +$curl = curl_init(); +// set timeout, if needed +if ($this->curl_timeout != 0) { +curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); +} +// return the result on success, rather than just TRUE +curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } +curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new ApiException('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); +if (! empty($queryParams)) { +$url = ($url . '?' . http_build_query($queryParams)); +} - // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); +if ($method == self::$POST) { +curl_setopt($curl, CURLOPT_POST, true); +curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); +} else if ($method == self::$PATCH) { +curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); +curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); +} else if ($method == self::$PUT) { +curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); +curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); +} else if ($method == self::$DELETE) { +curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); +curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); +} else if ($method != self::$GET) { +throw new ApiException('Method ' . $method . ' is not recognized.'); +} +curl_setopt($curl, CURLOPT_URL, $url); - // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); +// Set user agent +curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); - } else { - curl_setopt($curl, CURLOPT_VERBOSE, 0); - } +// debugging for curl +if (Configuration::$debug) { +error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); - // obtain the HTTP response headers - curl_setopt($curl, CURLOPT_HEADER, 1); +curl_setopt($curl, CURLOPT_VERBOSE, 1); +curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); +} else { +curl_setopt($curl, CURLOPT_VERBOSE, 0); +} - // Make the request - $response = curl_exec($curl); - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); +// obtain the HTTP response headers +curl_setopt($curl, CURLOPT_HEADER, 1); - // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); - } +// Make the request +$response = curl_exec($curl); +$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); +$http_header = substr($response, 0, $http_header_size); +$http_body = substr($response, $http_header_size); +$response_info = curl_getinfo($curl); - // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); - } - return $data; - } +// debug HTTP response body +if (Configuration::$debug) { +error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); +} - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } +// Handle the response +if ($response_info['http_code'] == 0) { +throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); +} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { +$data = json_decode($http_body); +if (json_last_error() > 0) { // if response is a string +$data = $http_body; +} +} else { +throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", +$response_info['http_code'], $http_header, $http_body); +} +return $data; +} - return $sanitized; - } +/** +* Build a JSON POST object +*/ +protected function sanitizeForSerialization($data) +{ +if (is_scalar($data) || null === $data) { +$sanitized = $data; +} else if ($data instanceof \DateTime) { +$sanitized = $data->format(\DateTime::ISO8601); +} else if (is_array($data)) { +foreach ($data as $property => $value) { +$data[$property] = $this->sanitizeForSerialization($value); +} +$sanitized = $data; +} else if (is_object($data)) { +$values = array(); +foreach (array_keys($data::$swaggerTypes) as $property) { +if ($data->$property !== null) { +$values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); +} +} +$sanitized = $values; +} else { +$sanitized = (string)$data; +} - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode(self::toString($value)); - } +return $sanitized; +} - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return self::toString($object); - } - } +/** +* Take value and turn it into a string suitable for inclusion in +* the path, by url-encoding. +* @param string $value a string which will be part of the path +* @return string the serialized object +*/ +public static function toPathValue($value) { +return rawurlencode(self::toString($value)); +} - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return self::toString($value); - } +/** +* Take value and turn it into a string suitable for inclusion in +* the query, by imploding comma-separated if it's an object. +* If it's a string, pass through unchanged. It will be url-encoded +* later. +* @param object $object an object to be serialized to a string +* @return string the serialized object +*/ +public static function toQueryValue($object) { +if (is_array($object)) { +return implode(',', $object); +} else { +return self::toString($object); +} +} - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public static function toFormValue($value) { - return self::toString($value); - } +/** +* Take value and turn it into a string suitable for inclusion in +* the header. If it's a string, pass through unchanged +* If it's a datetime object, format it in ISO8601 +* @param string $value a string which will be part of the header +* @return string the header string +*/ +public static function toHeaderValue($value) { +return self::toString($value); +} - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public static function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } +/** +* Take value and turn it into a string suitable for inclusion in +* the http body (form parameter). If it's a string, pass through unchanged +* If it's a datetime object, format it in ISO8601 +* @param string $value the value of the form parameter +* @return string the form string +*/ +public static function toFormValue($value) { +return self::toString($value); +} - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass); - } - } - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } else { - $class = "{{invokerPackage}}\\models\\".$class; - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = self::deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } +/** +* Take value and turn it into a string suitable for inclusion in +* the parameter. If it's a string, pass through unchanged +* If it's a datetime object, format it in ISO8601 +* @param string $value the value of the parameter +* @return string the header string +*/ +public static function toString($value) { +if ($value instanceof \DateTime) { // datetime in ISO8601 format +return $value->format(\DateTime::ISO8601); +} +else { +return $value; +} +} - return $deserialized; - } +/** +* Deserialize a JSON string into an object +* +* @param object $object object or primitive to be deserialized +* @param string $class class name is passed as a string +* @return object an instance of $class +*/ +public static function deserialize($data, $class) +{ +if (null === $data) { +$deserialized = null; +} elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] +$inner = substr($class, 4, -1); +$deserialized = array(); +if(strrpos($inner, ",") !== false) { +$subClass_array = explode(',', $inner, 2); +$subClass = $subClass_array[1]; +foreach ($data as $key => $value) { +$deserialized[$key] = self::deserialize($value, $subClass); +} +} +} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { +$subClass = substr($class, 6, -1); +$values = array(); +foreach ($data as $key => $value) { +$values[] = self::deserialize($value, $subClass); +} +$deserialized = $values; +} elseif ($class == 'DateTime') { +$deserialized = new \DateTime($data); +} elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { +settype($data, $class); +$deserialized = $data; +} else { +$class = "{{invokerPackage}}\\models\\".$class; +$instance = new $class(); +foreach ($instance::$swaggerTypes as $property => $type) { +$original_property_name = $instance::$attributeMap[$property]; +if (isset($original_property_name) && isset($data->$original_property_name)) { +$instance->$property = self::deserialize($data->$original_property_name, $type); +} +} +$deserialized = $instance; +} - /* - * return the header 'Accept' based on an array of Accept provided - * - * @param array[string] $accept Array of header - * @return string Accept (e.g. application/json) - */ - public static function selectHeaderAccept($accept) { - if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { - return NULL; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; - } else { - return implode(',', $accept); - } - } +return $deserialized; +} - /* - * return the content type based on an array of content-type provided - * - * @param array[string] content_type_array Array fo content-type - * @return string Content-Type (e.g. application/json) - */ - public static function selectHeaderContentType($content_type) { - if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { - return 'application/json'; - } elseif (preg_grep("/application\/json/i", $content_type)) { - return 'application/json'; - } else { - return implode(',', $content_type); - } - } +/* +* return the header 'Accept' based on an array of Accept provided +* +* @param array[string] $accept Array of header +* @return string Accept (e.g. application/json) +*/ +public static function selectHeaderAccept($accept) { +if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { +return NULL; +} elseif (preg_grep("/application\/json/i", $accept)) { +return 'application/json'; +} else { +return implode(',', $accept); +} +} + +/* +* return the content type based on an array of content-type provided +* +* @param array[string] content_type_array Array fo content-type +* @return string Content-Type (e.g. application/json) +*/ +public static function selectHeaderContentType($content_type) { +if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { +return 'application/json'; +} elseif (preg_grep("/application\/json/i", $content_type)) { +return 'application/json'; +} else { +return implode(',', $content_type); +} +} } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index b66c3a51eb7..6ee6efc0805 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -34,25 +34,25 @@ class ApiException extends Exception { public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); $this->response_headers = $responseHeaders; - $this->response_body = $responseBody; - } +$this->response_body = $responseBody; +} - /** - * Get the HTTP response header - * - * @return string HTTP response header - */ - public function getResponseHeaders() { - return $this->response_headers; - } +/** +* Get the HTTP response header +* +* @return string HTTP response header +*/ +public function getResponseHeaders() { +return $this->response_headers; +} - /** - * Get the HTTP response body - * - * @return string HTTP response body - */ - public function getResponseBody() { - return $this->response_body; - } +/** +* Get the HTTP response body +* +* @return string HTTP response body +*/ +public function getResponseBody() { +return $this->response_body; +} } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 12d2eb80744..ced857098d9 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -30,108 +30,108 @@ class {{classname}} { if (Configuration::$apiClient === null) { Configuration::$apiClient = new ApiClient(); // create a new API client if not present $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } +} +else +$this->apiClient = Configuration::$apiClient; // use the default one +} else { +$this->apiClient = $apiClient; // use the one provided by the user +} +} - private $apiClient; // instance of the ApiClient +private $apiClient; // instance of the ApiClient - /** - * get the API client - */ - public function getApiClient() { - return $this->apiClient; - } +/** +* get the API client +*/ +public function getApiClient() { +return $this->apiClient; +} - /** - * set the API client - */ - public function setApiClient($apiClient) { - $this->apiClient = $apiClient; - } +/** +* set the API client +*/ +public function setApiClient($apiClient) { +$this->apiClient = $apiClient; +} - {{#operation}} - /** - * {{{nickname}}} - * - * {{{summary}}} - * -{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ - public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if (${{paramName}} === null) { +{{#operation}} + /** + * {{{nickname}}} + * + * {{{summary}}} + * + {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if (${{paramName}} === null) { throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); - } - {{/required}}{{/allParams}} + } + {{/required}}{{/allParams}} - // parse inputs - $resourcePath = "{{path}}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "{{httpMethod}}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + // parse inputs + $resourcePath = "{{path}}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "{{httpMethod}}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); - {{#queryParams}}// query params - if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->toQueryValue(${{paramName}}); - }{{/queryParams}} - {{#headerParams}}// header params - if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); - }{{/headerParams}} - {{#pathParams}}// path params - if(${{paramName}} !== null) { - $resourcePath = str_replace("{" . "{{baseName}}" . "}", - $this->apiClient->toPathValue(${{paramName}}), $resourcePath); - }{{/pathParams}} - {{#formParams}}// form params - if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}}); - }{{/formParams}} - {{#bodyParams}}// body params - $_tempBody = null; - if (isset(${{paramName}})) { - $_tempBody = ${{paramName}}; - }{{/bodyParams}} + {{#queryParams}}// query params + if(${{paramName}} !== null) { + $queryParams['{{baseName}}'] = $this->apiClient->toQueryValue(${{paramName}}); + }{{/queryParams}} + {{#headerParams}}// header params + if(${{paramName}} !== null) { + $headerParams['{{baseName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); + }{{/headerParams}} + {{#pathParams}}// path params + if(${{paramName}} !== null) { + $resourcePath = str_replace("{" . "{{baseName}}" . "}", + $this->apiClient->toPathValue(${{paramName}}), $resourcePath); + }{{/pathParams}} + {{#formParams}}// form params + if (${{paramName}} !== null) { + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}}); + }{{/formParams}} + {{#bodyParams}}// body params + $_tempBody = null; + if (isset(${{paramName}})) { + $_tempBody = ${{paramName}}; + }{{/bodyParams}} - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } - // authentication setting, if any - $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); + // authentication setting, if any + $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, $authSettings); - {{#returnType}}if(! $response) { - return null; - } + {{#returnType}}if(! $response) { + return null; + } - $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); - return $responseObject;{{/returnType}} - } - {{/operation}} + $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); + return $responseObject;{{/returnType}} + } +{{/operation}} {{newline}} {{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index fb47a865834..07d94b86106 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -1,32 +1,32 @@ { - "name": "{{invokerPackage}}/{{invokerPackage}}-php", - "description": "{{description}}", - "keywords": [ - "swagger", - "php", - "sdk", - "api" - ], - "homepage": "http://swagger.io", - "license": "Apache v2", - "authors": [ - { - "name": "Swagger and contributors", - "homepage": "https://github.com/swagger-api/swagger-codegen" - } - ], - "require": { - "php": ">=5.3.3", - "ext-curl": "*", - "ext-json": "*", - "ext-mbstring": "*" - }, - "require-dev": { - "phpunit/phpunit": "~4.0", - "satooshi/php-coveralls": "~0.6.1", - "squizlabs/php_codesniffer": "~2.0" - }, - "autoload": { - "psr-4": { "{{invokerPackage}}\\" : "lib/" } - } +"name": "{{invokerPackage}}/{{invokerPackage}}-php", +"description": "{{description}}", +"keywords": [ +"swagger", +"php", +"sdk", +"api" +], +"homepage": "http://swagger.io", +"license": "Apache v2", +"authors": [ +{ +"name": "Swagger and contributors", +"homepage": "https://github.com/swagger-api/swagger-codegen" +} +], +"require": { +"php": ">=5.3.3", +"ext-curl": "*", +"ext-json": "*", +"ext-mbstring": "*" +}, +"require-dev": { +"phpunit/phpunit": "~4.0", +"satooshi/php-coveralls": "~0.6.1", +"squizlabs/php_codesniffer": "~2.0" +}, +"autoload": { +"psr-4": { "{{invokerPackage}}\\" : "lib/" } +} } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 9ce348ad131..f93bc3c5016 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -16,7 +16,7 @@ */ {{#models}} -{{#model}} + {{#model}} /** * {{description}} * @@ -31,40 +31,40 @@ use \ArrayAccess; class {{classname}} implements ArrayAccess { static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); + {{/hasMore}}{{/vars}} + ); - static $attributeMap = array( - {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); + static $attributeMap = array( + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); - {{#vars}}{{#description}} - /** - * {{{description}}} - */{{/description}} - public ${{name}}; /* {{{datatype}}} */{{/vars}} + {{#vars}}{{#description}} + /** + * {{{description}}} + */{{/description}} + public ${{name}}; /* {{{datatype}}} */{{/vars}} - public function __construct(array $data = null) { + public function __construct(array $data = null) { {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} {{/hasMore}}{{/vars}} - } + } - public function offsetExists($offset) { + public function offsetExists($offset) { return isset($this->$offset); - } + } - public function offsetGet($offset) { + public function offsetGet($offset) { return $this->$offset; - } + } - public function offsetSet($offset, $value) { + public function offsetSet($offset, $value) { $this->$offset = $value; - } + } - public function offsetUnset($offset) { + public function offsetUnset($offset) { unset($this->$offset); - } -} -{{/model}} + } + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 9c590a9a508..f4e99c9fbc9 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -67,8 +67,8 @@ If you want to run the tests in all the python platforms: ```sh $ make test-all [... tox creates a virtualenv for every platform and runs tests inside of each] - py27: commands succeeded - py34: commands succeeded - congratulations :) +py27: commands succeeded +py34: commands succeeded +congratulations :) ``` diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 867014d5e12..fa5e539a280 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -5,17 +5,17 @@ {{classname}}.py Copyright 2015 SmartBear Software - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ @@ -31,18 +31,18 @@ from .. import configuration from ..api_client import ApiClient {{#operations}} -class {{classname}}(object): + class {{classname}}(object): def __init__(self, api_client=None): - if api_client: - self.api_client = api_client - else: - if not configuration.api_client: - configuration.api_client = ApiClient('{{basePath}}') - self.api_client = configuration.api_client - + if api_client: + self.api_client = api_client + else: + if not configuration.api_client: + configuration.api_client = ApiClient('{{basePath}}') + self.api_client = configuration.api_client + {{#operation}} - def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): + def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ {{{summary}}} {{{notes}}} @@ -52,17 +52,17 @@ class {{classname}}(object): :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - if {{paramName}} is None: + # verify the required parameter '{{paramName}}' is set + if {{paramName}} is None: raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") {{/required}}{{/allParams}} all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] params = locals() for key, val in iteritems(params['kwargs']): - if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) - params[key] = val + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) + params[key] = val del params['kwargs'] resource_path = '{{path}}'.replace('{format}', 'json') @@ -70,34 +70,34 @@ class {{classname}}(object): path_params = {} {{#pathParams}} - if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}'] + if '{{paramName}}' in params: + path_params['{{baseName}}'] = params['{{paramName}}'] {{/pathParams}} query_params = {} {{#queryParams}} - if '{{paramName}}' in params: + if '{{paramName}}' in params: query_params['{{baseName}}'] = params['{{paramName}}'] {{/queryParams}} header_params = {} {{#headerParams}} - if '{{paramName}}' in params: + if '{{paramName}}' in params: header_params['{{baseName}}'] = params['{{paramName}}'] {{/headerParams}} form_params = {} files = {} {{#formParams}} - if '{{paramName}}' in params: + if '{{paramName}}' in params: {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} {{/formParams}} body_params = None {{#bodyParam}} - if '{{paramName}}' in params: + if '{{paramName}}' in params: body_params = params['{{paramName}}'] {{/bodyParam}} # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: - del header_params['Accept'] + del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) @@ -106,10 +106,10 @@ class {{classname}}(object): auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings) + body=body_params, post_params=form_params, files=files, + response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings) {{#returnType}} - return response + return response {{/returnType}}{{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index b8cc4cc2a84..fc0e7c60549 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -22,282 +22,282 @@ import random from six import iteritems try: - # for python3 - from urllib.parse import quote +# for python3 +from urllib.parse import quote except ImportError: - # for python2 - from urllib import quote +# for python2 +from urllib import quote from . import configuration class ApiClient(object): - """ - Generic API client for Swagger client library builds +""" +Generic API client for Swagger client library builds - :param host: The base path for the server to call - :param header_name: a header to pass when making calls to the API - :param header_value: a header value to pass when making calls to the API - """ - def __init__(self, host=configuration.host, header_name=None, header_value=None): - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.host = host - self.cookie = None - # Set default User-Agent. - self.user_agent = 'Python-Swagger' +:param host: The base path for the server to call +:param header_name: a header to pass when making calls to the API +:param header_value: a header value to pass when making calls to the API +""" +def __init__(self, host=configuration.host, header_name=None, header_value=None): +self.default_headers = {} +if header_name is not None: +self.default_headers[header_name] = header_value +self.host = host +self.cookie = None +# Set default User-Agent. +self.user_agent = 'Python-Swagger' - @property - def user_agent(self): - return self.default_headers['User-Agent'] +@property +def user_agent(self): +return self.default_headers['User-Agent'] - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value +@user_agent.setter +def user_agent(self, value): +self.default_headers['User-Agent'] = value - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value +def set_default_header(self, header_name, header_value): +self.default_headers[header_name] = header_value - def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response=None, auth_settings=None): +def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, +body=None, post_params=None, files=None, response=None, auth_settings=None): - # headers parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) +# headers parameters +header_params = header_params or {} +header_params.update(self.default_headers) +if self.cookie: +header_params['Cookie'] = self.cookie +if header_params: +header_params = self.sanitize_for_serialization(header_params) - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.replace('{' + k + '}', replacement) +# path parameters +if path_params: +path_params = self.sanitize_for_serialization(path_params) +for k, v in iteritems(path_params): +replacement = quote(str(self.to_path_value(v))) +resource_path = resource_path.replace('{' + k + '}', replacement) - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} +# query parameters +if query_params: +query_params = self.sanitize_for_serialization(query_params) +query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - # post parameters - if post_params: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) +# post parameters +if post_params: +post_params = self.prepare_post_parameters(post_params, files) +post_params = self.sanitize_for_serialization(post_params) - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) +# auth setting +self.update_params_for_auth(header_params, query_params, auth_settings) - # body - if body: - body = self.sanitize_for_serialization(body) +# body +if body: +body = self.sanitize_for_serialization(body) - # request url - url = self.host + resource_path +# request url +url = self.host + resource_path - # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) +# perform request and return response +response_data = self.request(method, url, query_params=query_params, headers=header_params, +post_params=post_params, body=body) - # deserialize response data - if response: - return self.deserialize(response_data, response) - else: - return None +# deserialize response data +if response: +return self.deserialize(response_data, response) +else: +return None - def to_path_value(self, obj): - """ - Convert a string or object to a path-friendly value +def to_path_value(self, obj): +""" +Convert a string or object to a path-friendly value - :param obj: object or string value +:param obj: object or string value - :return string: quoted value - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) +:return string: quoted value +""" +if type(obj) == list: +return ','.join(obj) +else: +return str(obj) - def sanitize_for_serialization(self, obj): - """ - Sanitize an object for Request. +def sanitize_for_serialization(self, obj): +""" +Sanitize an object for Request. - If obj is None, return None. - If obj is str, int, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - """ - if isinstance(obj, type(None)): - return None - elif isinstance(obj, (str, int, float, bool, tuple)): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' and key != 'attribute_map' and val is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} +If obj is None, return None. +If obj is str, int, float, bool, return directly. +If obj is datetime.datetime, datetime.date convert to string in iso8601 format. +If obj is list, santize each element in the list. +If obj is dict, return the dict. +If obj is swagger model, return the properties dict. +""" +if isinstance(obj, type(None)): +return None +elif isinstance(obj, (str, int, float, bool, tuple)): +return obj +elif isinstance(obj, list): +return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] +elif isinstance(obj, (datetime.datetime, datetime.date)): +return obj.isoformat() +else: +if isinstance(obj, dict): +obj_dict = obj +else: +# Convert model obj to dict except attributes `swagger_types`, `attribute_map` +# and attributes which value is not None. +# Convert attribute name to json key in model definition for request. +obj_dict = {obj.attribute_map[key]: val +for key, val in iteritems(obj.__dict__) +if key != 'swagger_types' and key != 'attribute_map' and val is not None} +return {key: self.sanitize_for_serialization(val) +for key, val in iteritems(obj_dict)} - def deserialize(self, obj, obj_class): - """ - Derialize a JSON string into an object. +def deserialize(self, obj, obj_class): +""" +Derialize a JSON string into an object. - :param obj: string or object to be deserialized - :param obj_class: class literal for deserialzied object, or string of class name +:param obj: string or object to be deserialized +:param obj_class: class literal for deserialzied object, or string of class name - :return object: deserialized object - """ - # Have to accept obj_class as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(obj_class) == str: - if 'list[' in obj_class: - match = re.match('list\[(.*)\]', obj_class) - sub_class = match.group(1) - return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] +:return object: deserialized object +""" +# Have to accept obj_class as string or actual type. Type could be a +# native Python type, or one of the model classes. +if type(obj_class) == str: +if 'list[' in obj_class: +match = re.match('list\[(.*)\]', obj_class) +sub_class = match.group(1) +return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] - if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: - obj_class = eval(obj_class) - else: # not a native type, must be model class - obj_class = eval('models.' + obj_class) +if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: +obj_class = eval(obj_class) +else: # not a native type, must be model class +obj_class = eval('models.' + obj_class) - if obj_class in [int, float, dict, list, str, bool]: - return obj_class(obj) - elif obj_class == datetime: - return self.__parse_string_to_datetime(obj) +if obj_class in [int, float, dict, list, str, bool]: +return obj_class(obj) +elif obj_class == datetime: +return self.__parse_string_to_datetime(obj) - instance = obj_class() +instance = obj_class() - for attr, attr_type in iteritems(instance.swagger_types): - if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: - value = obj[instance.attribute_map[attr]] - if attr_type in ['str', 'int', 'float', 'bool']: - attr_type = eval(attr_type) - try: - value = attr_type(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif attr_type == 'datetime': - setattr(instance, attr, self.__parse_string_to_datetime(value)) - elif 'list[' in attr_type: - match = re.match('list\[(.*)\]', attr_type) - sub_class = match.group(1) - sub_values = [] - if not value: - setattr(instance, attr, None) - else: - for sub_value in value: - sub_values.append(self.deserialize(sub_value, sub_class)) - setattr(instance, attr, sub_values) - else: - setattr(instance, attr, self.deserialize(value, attr_type)) +for attr, attr_type in iteritems(instance.swagger_types): +if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: +value = obj[instance.attribute_map[attr]] +if attr_type in ['str', 'int', 'float', 'bool']: +attr_type = eval(attr_type) +try: +value = attr_type(value) +except UnicodeEncodeError: +value = unicode(value) +except TypeError: +value = value +setattr(instance, attr, value) +elif attr_type == 'datetime': +setattr(instance, attr, self.__parse_string_to_datetime(value)) +elif 'list[' in attr_type: +match = re.match('list\[(.*)\]', attr_type) +sub_class = match.group(1) +sub_values = [] +if not value: +setattr(instance, attr, None) +else: +for sub_value in value: +sub_values.append(self.deserialize(sub_value, sub_class)) +setattr(instance, attr, sub_values) +else: +setattr(instance, attr, self.deserialize(value, attr_type)) - return instance +return instance - def __parse_string_to_datetime(self, string): - """ - Parse datetime in string to datetime. +def __parse_string_to_datetime(self, string): +""" +Parse datetime in string to datetime. - The string should be in iso8601 datetime format. - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string +The string should be in iso8601 datetime format. +""" +try: +from dateutil.parser import parse +return parse(string) +except ImportError: +return string - def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): - """ - Perform http request using RESTClient. - """ - if method == "GET": - return RESTClient.GET(url, query_params=query_params, headers=headers) - elif method == "HEAD": - return RESTClient.HEAD(url, query_params=query_params, headers=headers) - elif method == "POST": - return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) - elif method == "PUT": - return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) - elif method == "PATCH": - return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) - elif method == "DELETE": - return RESTClient.DELETE(url, query_params=query_params, headers=headers) - else: - raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") +def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): +""" +Perform http request using RESTClient. +""" +if method == "GET": +return RESTClient.GET(url, query_params=query_params, headers=headers) +elif method == "HEAD": +return RESTClient.HEAD(url, query_params=query_params, headers=headers) +elif method == "POST": +return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) +elif method == "PUT": +return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) +elif method == "PATCH": +return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) +elif method == "DELETE": +return RESTClient.DELETE(url, query_params=query_params, headers=headers) +else: +raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") - def prepare_post_parameters(self, post_params=None, files=None): - params = {} +def prepare_post_parameters(self, post_params=None, files=None): +params = {} - if post_params: - params.update(post_params) +if post_params: +params.update(post_params) - if files: - for k, v in iteritems(files): - if v: - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) +if files: +for k, v in iteritems(files): +if v: +with open(v, 'rb') as f: +filename = os.path.basename(f.name) +filedata = f.read() +mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' +params[k] = tuple([filename, filedata, mimetype]) - return params +return params - def select_header_accept(self, accepts): - """ - Return `Accept` based on an array of accepts provided - """ - if not accepts: - return +def select_header_accept(self, accepts): +""" +Return `Accept` based on an array of accepts provided +""" +if not accepts: +return - accepts = list(map(lambda x: x.lower(), accepts)) +accepts = list(map(lambda x: x.lower(), accepts)) - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) +if 'application/json' in accepts: +return 'application/json' +else: +return ', '.join(accepts) - def select_header_content_type(self, content_types): - """ - Return `Content-Type` baseed on an array of content_types provided - """ - if not content_types: - return 'application/json' +def select_header_content_type(self, content_types): +""" +Return `Content-Type` baseed on an array of content_types provided +""" +if not content_types: +return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) +content_types = list(map(lambda x: x.lower(), content_types)) - if 'application/json' in content_types: - return 'application/json' - else: - return content_types[0] +if 'application/json' in content_types: +return 'application/json' +else: +return content_types[0] - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Update header and query params based on authentication setting - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] - else: - raise ValueError('Authentication token must be in `query` or `header`') +def update_params_for_auth(self, headers, querys, auth_settings): +""" +Update header and query params based on authentication setting +""" +if not auth_settings: +return + +for auth in auth_settings: +auth_setting = configuration.auth_settings().get(auth) +if auth_setting: +if auth_setting['in'] == 'header': +headers[auth_setting['key']] = auth_setting['value'] +elif auth_setting['in'] == 'query': +querys[auth_setting['key']] = auth_setting['value'] +else: +raise ValueError('Authentication token must be in `query` or `header`') diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index d3a7093a02a..967fabccd99 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -3,44 +3,44 @@ import base64 import urllib3 def get_api_key_with_prefix(key): - global api_key - global api_key_prefix +global api_key +global api_key_prefix - if api_key.get(key) and api_key_prefix.get(key): - return api_key_prefix[key] + ' ' + api_key[key] - elif api_key.get(key): - return api_key[key] +if api_key.get(key) and api_key_prefix.get(key): +return api_key_prefix[key] + ' ' + api_key[key] +elif api_key.get(key): +return api_key[key] def get_basic_auth_token(): - global username - global password +global username +global password - return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') +return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(): - return { {{#authMethods}}{{#isApiKey}} - '{{name}}': { - 'type': 'api_key', - 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, - 'key': '{{keyParamName}}', - 'value': get_api_key_with_prefix('{{keyParamName}}') - }, - {{/isApiKey}}{{#isBasic}} - '{{name}}': { - 'type': 'basic', - 'in': 'header', - 'key': 'Authorization', - 'value': get_basic_auth_token() - }, - {{/isBasic}}{{/authMethods}} - } +return { {{#authMethods}}{{#isApiKey}} + '{{name}}': { + 'type': 'api_key', + 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': get_api_key_with_prefix('{{keyParamName}}') + }, +{{/isApiKey}}{{#isBasic}} + '{{name}}': { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': get_basic_auth_token() + }, +{{/isBasic}}{{/authMethods}} +} # Default Base url host = "{{basePath}}" # Default api client api_client = None - + # Authentication settings api_key = {} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 429eac33ec5..629bc0342d3 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -4,28 +4,28 @@ """ Copyright 2015 SmartBear Software - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. """ {{#models}} -{{#model}} + {{#model}} -class {{classname}}(object): - """ - NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ + class {{classname}}(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ - def __init__(self): + def __init__(self): """ Swagger model @@ -33,27 +33,27 @@ class {{classname}}(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } self.attribute_map = { - {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } {{#vars}} - {{#description}}# {{description}}{{/description}} - self.{{name}} = None # {{{datatype}}} + {{#description}}# {{description}}{{/description}} + self.{{name}} = None # {{{datatype}}} {{/vars}} - def __repr__(self): + def __repr__(self): properties = [] for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) -{{/model}} + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 508f3d6693a..d5c79d8395a 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -15,239 +15,239 @@ import certifi from six import iteritems try: - import urllib3 +import urllib3 except ImportError: - raise ImportError('Swagger python client requires urllib3.') +raise ImportError('Swagger python client requires urllib3.') try: - # for python3 - from urllib.parse import urlencode +# for python3 +from urllib.parse import urlencode except ImportError: - # for python2 - from urllib import urlencode +# for python2 +from urllib import urlencode class RESTResponse(io.IOBase): - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data +def __init__(self, resp): +self.urllib3_response = resp +self.status = resp.status +self.reason = resp.reason +self.data = resp.data - def getheaders(self): - """ - Returns a dictionary of the response headers. - """ - return self.urllib3_response.getheaders() +def getheaders(self): +""" +Returns a dictionary of the response headers. +""" +return self.urllib3_response.getheaders() - def getheader(self, name, default=None): - """ - Returns a given response header. - """ - return self.urllib3_response.getheader(name, default) +def getheader(self, name, default=None): +""" +Returns a given response header. +""" +return self.urllib3_response.getheader(name, default) class RESTClientObject(object): - def __init__(self, pools_size=4): - # http pool manager - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size - ) +def __init__(self, pools_size=4): +# http pool manager +self.pool_manager = urllib3.PoolManager( +num_pools=pools_size +) - # https pool manager - # certificates validated using Mozilla’s root certificates - self.ssl_pool_manager = urllib3.PoolManager( - num_pools=pools_size, - cert_reqs=ssl.CERT_REQUIRED, - ca_certs=certifi.where() - ) +# https pool manager +# certificates validated using Mozilla’s root certificates +self.ssl_pool_manager = urllib3.PoolManager( +num_pools=pools_size, +cert_reqs=ssl.CERT_REQUIRED, +ca_certs=certifi.where() +) - def agent(self, url): - """ - Return proper pool manager for the http\https schemes. - """ - url = urllib3.util.url.parse_url(url) - scheme = url.scheme - if scheme == 'https': - return self.ssl_pool_manager - else: - return self.pool_manager +def agent(self, url): +""" +Return proper pool manager for the http\https schemes. +""" +url = urllib3.util.url.parse_url(url) +scheme = url.scheme +if scheme == 'https': +return self.ssl_pool_manager +else: +return self.pool_manager - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None): - """ - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, `application/x-www-form-urlencode` - and `multipart/form-data` - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] +def request(self, method, url, query_params=None, headers=None, +body=None, post_params=None): +""" +:param method: http request method +:param url: http request url +:param query_params: query parameters in the url +:param headers: http request headers +:param body: request json body, for `application/json` +:param post_params: request post parameters, `application/x-www-form-urlencode` +and `multipart/form-data` +""" +method = method.upper() +assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] - if post_params and body: - raise ValueError("body parameter cannot be used with post_params parameter.") +if post_params and body: +raise ValueError("body parameter cannot be used with post_params parameter.") - post_params = post_params or {} - headers = headers or {} +post_params = post_params or {} +headers = headers or {} - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' +if 'Content-Type' not in headers: +headers['Content-Type'] = 'application/json' - # For `POST`, `PUT`, `PATCH` - if method in ['POST', 'PUT', 'PATCH']: - if query_params: - url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': - r = self.agent(url).request(method, url, - body=json.dumps(body), - headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=False, - headers=headers) - if headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct Content-Type - # which generated by urllib3 will be overwritten. - del headers['Content-Type'] - r = self.agent(url).request(method, url, - fields=post_params, - encode_multipart=True, - headers=headers) - # For `GET`, `HEAD`, `DELETE` - else: - r = self.agent(url).request(method, url, - fields=query_params, - headers=headers) - r = RESTResponse(r) +# For `POST`, `PUT`, `PATCH` +if method in ['POST', 'PUT', 'PATCH']: +if query_params: +url += '?' + urlencode(query_params) +if headers['Content-Type'] == 'application/json': +r = self.agent(url).request(method, url, +body=json.dumps(body), +headers=headers) +if headers['Content-Type'] == 'application/x-www-form-urlencoded': +r = self.agent(url).request(method, url, +fields=post_params, +encode_multipart=False, +headers=headers) +if headers['Content-Type'] == 'multipart/form-data': +# must del headers['Content-Type'], or the correct Content-Type +# which generated by urllib3 will be overwritten. +del headers['Content-Type'] +r = self.agent(url).request(method, url, +fields=post_params, +encode_multipart=True, +headers=headers) +# For `GET`, `HEAD`, `DELETE` +else: +r = self.agent(url).request(method, url, +fields=query_params, +headers=headers) +r = RESTResponse(r) - if r.status not in range(200, 206): - raise ApiException(r) +if r.status not in range(200, 206): +raise ApiException(r) - return self.process_response(r) +return self.process_response(r) - def process_response(self, response): - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if sys.version_info > (3,): - data = response.data.decode('utf8') - else: - data = response.data - try: - resp = json.loads(data) - except ValueError: - resp = data +def process_response(self, response): +# In the python 3, the response.data is bytes. +# we need to decode it to string. +if sys.version_info > (3,): +data = response.data.decode('utf8') +else: +data = response.data +try: +resp = json.loads(data) +except ValueError: +resp = data - return resp +return resp - def GET(self, url, headers=None, query_params=None): - return self.request("GET", url, headers=headers, query_params=query_params) +def GET(self, url, headers=None, query_params=None): +return self.request("GET", url, headers=headers, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None): - return self.request("HEAD", url, headers=headers, query_params=query_params) +def HEAD(self, url, headers=None, query_params=None): +return self.request("HEAD", url, headers=headers, query_params=query_params) - def DELETE(self, url, headers=None, query_params=None): - return self.request("DELETE", url, headers=headers, query_params=query_params) +def DELETE(self, url, headers=None, query_params=None): +return self.request("DELETE", url, headers=headers, query_params=query_params) - def POST(self, url, headers=None, post_params=None, body=None): - return self.request("POST", url, headers=headers, post_params=post_params, body=body) +def POST(self, url, headers=None, post_params=None, body=None): +return self.request("POST", url, headers=headers, post_params=post_params, body=body) - def PUT(self, url, headers=None, post_params=None, body=None): - return self.request("PUT", url, headers=headers, post_params=post_params, body=body) +def PUT(self, url, headers=None, post_params=None, body=None): +return self.request("PUT", url, headers=headers, post_params=post_params, body=body) - def PATCH(self, url, headers=None, post_params=None, body=None): - return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) +def PATCH(self, url, headers=None, post_params=None, body=None): +return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) class ApiException(Exception): - """ - Non-2xx HTTP response - """ +""" +Non-2xx HTTP response +""" - def __init__(self, http_resp): - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() +def __init__(self, http_resp): +self.status = http_resp.status +self.reason = http_resp.reason +self.body = http_resp.data +self.headers = http_resp.getheaders() - # In the python 3, the self.body is bytes. - # we need to decode it to string. - if sys.version_info > (3,): - data = self.body.decode('utf8') - else: - data = self.body - - try: - self.body = json.loads(data) - except ValueError: - self.body = data +# In the python 3, the self.body is bytes. +# we need to decode it to string. +if sys.version_info > (3,): +data = self.body.decode('utf8') +else: +data = self.body - def __str__(self): - """ - Custom error response messages - """ - return "({0})\n"\ - "Reason: {1}\n"\ - "HTTP response headers: {2}\n"\ - "HTTP response body: {3}\n".\ - format(self.status, self.reason, self.headers, self.body) +try: +self.body = json.loads(data) +except ValueError: +self.body = data + +def __str__(self): +""" +Custom error response messages +""" +return "({0})\n"\ +"Reason: {1}\n"\ +"HTTP response headers: {2}\n"\ +"HTTP response body: {3}\n".\ +format(self.status, self.reason, self.headers, self.body) class RESTClient(object): - """ - A class with all class methods to perform JSON requests. - """ +""" +A class with all class methods to perform JSON requests. +""" - IMPL = RESTClientObject() +IMPL = RESTClientObject() - @classmethod - def request(cls, *n, **kw): - """ - Perform a REST request and parse the response. - """ - return cls.IMPL.request(*n, **kw) +@classmethod +def request(cls, *n, **kw): +""" +Perform a REST request and parse the response. +""" +return cls.IMPL.request(*n, **kw) - @classmethod - def GET(cls, *n, **kw): - """ - Perform a GET request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) +@classmethod +def GET(cls, *n, **kw): +""" +Perform a GET request using `RESTClient.request()`. +""" +return cls.IMPL.GET(*n, **kw) - @classmethod - def HEAD(cls, *n, **kw): - """ - Perform a HEAD request using `RESTClient.request()`. - """ - return cls.IMPL.GET(*n, **kw) +@classmethod +def HEAD(cls, *n, **kw): +""" +Perform a HEAD request using `RESTClient.request()`. +""" +return cls.IMPL.GET(*n, **kw) - @classmethod - def POST(cls, *n, **kw): - """ - Perform a POST request using `RESTClient.request()` - """ - return cls.IMPL.POST(*n, **kw) +@classmethod +def POST(cls, *n, **kw): +""" +Perform a POST request using `RESTClient.request()` +""" +return cls.IMPL.POST(*n, **kw) - @classmethod - def PUT(cls, *n, **kw): - """ - Perform a PUT request using `RESTClient.request()` - """ - return cls.IMPL.PUT(*n, **kw) +@classmethod +def PUT(cls, *n, **kw): +""" +Perform a PUT request using `RESTClient.request()` +""" +return cls.IMPL.PUT(*n, **kw) - @classmethod - def PATCH(cls, *n, **kw): - """ - Perform a PATCH request using `RESTClient.request()` - """ - return cls.IMPL.PATCH(*n, **kw) +@classmethod +def PATCH(cls, *n, **kw): +""" +Perform a PATCH request using `RESTClient.request()` +""" +return cls.IMPL.PATCH(*n, **kw) - @classmethod - def DELETE(cls, *n, **kw): - """ - Perform a DELETE request using `RESTClient.request()` - """ - return cls.IMPL.DELETE(*n, **kw) +@classmethod +def DELETE(cls, *n, **kw): +""" +Perform a DELETE request using `RESTClient.request()` +""" +return cls.IMPL.DELETE(*n, **kw) diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index f1ba52d2930..59c8f7f428a 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -3,18 +3,18 @@ from setuptools import setup, find_packages {{#apiInfo}}{{#apis}}{{^hasMore}} -# To install the library, open a Terminal shell, then run this -# file by typing: -# -# python setup.py install -# -# You need to have the setuptools module installed. -# Try reading the setuptools documentation: -# http://pypi.python.org/pypi/setuptools + # To install the library, open a Terminal shell, then run this + # file by typing: + # + # python setup.py install + # + # You need to have the setuptools module installed. + # Try reading the setuptools documentation: + # http://pypi.python.org/pypi/setuptools -REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] + REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] -setup( + setup( name="{{module}}", version="{{version}}", description="{{appName}}", @@ -27,7 +27,7 @@ setup( long_description="""\ {{appDescription}} """ -) + ) {{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/python3/__init__.mustache b/modules/swagger-codegen/src/main/resources/python3/__init__.mustache index 4b41ee706c7..1ca7f06ecf2 100644 --- a/modules/swagger-codegen/src/main/resources/python3/__init__.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/__init__.mustache @@ -5,5 +5,5 @@ import os __all__ = [] for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) +if module != '__init__.py' and module[-3:] == '.py': +__all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python3/api.mustache b/modules/swagger-codegen/src/main/resources/python3/api.mustache index 015158bccec..a40574ca3c2 100644 --- a/modules/swagger-codegen/src/main/resources/python3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/api.mustache @@ -3,17 +3,17 @@ {{classname}}.py Copyright 2015 SmartBear Software - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ @@ -24,20 +24,20 @@ from .models import * {{#operations}} -class {{classname}}(object): + class {{classname}}(object): def __init__(self, apiClient): - self.apiClient = apiClient + self.apiClient = apiClient {{newline}} {{#operation}} - def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs): + def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs): """{{{summary}}} {{{notes}}} Args: - {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} - {{/allParams}} + {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{/allParams}} Returns: {{returnType}} """ @@ -46,9 +46,9 @@ class {{classname}}(object): params = locals() for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) - params[key] = val + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) + params[key] = val del params['kwargs'] resourcePath = '{{path}}' @@ -59,37 +59,37 @@ class {{classname}}(object): headerParams = {} {{#queryParams}} - if ('{{paramName}}' in params): + if ('{{paramName}}' in params): queryParams['{{paramName}}'] = self.apiClient.toPathValue(params['{{paramName}}']) {{/queryParams}} {{#headerParams}} - if ('{{paramName}}' in params): + if ('{{paramName}}' in params): headerParams['{{paramName}}'] = params['{{paramName}}'] {{/headerParams}} {{#pathParams}} - if ('{{paramName}}' in params): + if ('{{paramName}}' in params): replacement = str(self.apiClient.toPathValue(params['{{paramName}}'])) resourcePath = resourcePath.replace('{' + '{{baseName}}' + '}', - replacement) + replacement) {{/pathParams}} postData = (params['body'] if 'body' in params else None) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams) {{#returnType}} - if not response: + if not response: return None - responseObject = self.apiClient.deserialize(response, '{{returnType}}') - return responseObject + responseObject = self.apiClient.deserialize(response, '{{returnType}}') + return responseObject {{/returnType}} {{newline}} {{newline}} {{/operation}} -{{newline}} + {{newline}} {{/operations}} {{newline}} diff --git a/modules/swagger-codegen/src/main/resources/python3/model.mustache b/modules/swagger-codegen/src/main/resources/python3/model.mustache index ef3841a34b9..63d2bedc3da 100644 --- a/modules/swagger-codegen/src/main/resources/python3/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/model.mustache @@ -2,39 +2,39 @@ """ Copyright 2015 SmartBear Software - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 +http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. """ {{#models}} -{{#model}} + {{#model}} -class {{classname}}: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + class {{classname}}: + """NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually.""" - def __init__(self): + def __init__(self): self.swaggerTypes = { - {{#vars}} + {{#vars}} '{{name}}': '{{{datatype}}}'{{#hasMore}}, {{/hasMore}} - {{/vars}}{{newline}} + {{/vars}}{{newline}} } {{#vars}} - {{#description}}#{{description}} - {{/description}} - self.{{name}} = None # {{{datatype}}} + {{#description}}#{{description}} + {{/description}} + self.{{name}} = None # {{{datatype}}} {{/vars}} -{{/model}} + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache index f99f0d4d250..55834b3fd3a 100644 --- a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache @@ -16,215 +16,215 @@ from .models import * class ApiClient: - """Generic API client for Swagger client library builds""" +"""Generic API client for Swagger client library builds""" - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None +def __init__(self, apiKey=None, apiServer=None): +if apiKey == None: +raise Exception('You must pass an apiKey when instantiating the ' +'APIClient') +self.apiKey = apiKey +self.apiServer = apiServer +self.cookie = None - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): +def callAPI(self, resourcePath, method, queryParams, postData, +headerParams=None): - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.items(): - headers[param] = value +url = self.apiServer + resourcePath +headers = {} +if headerParams: +for param, value in headerParams.items(): +headers[param] = value - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey +#headers['Content-type'] = 'application/json' +headers['api_key'] = self.apiKey - if self.cookie: - headers['Cookie'] = self.cookie +if self.cookie: +headers['Cookie'] = self.cookie - data = None +data = None - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) +if queryParams: +# Need to remove None values, these should not be sent +sentQueryParams = {} +for param, value in queryParams.items(): +if value != None: +sentQueryParams[param] = value +url = url + '?' + urllib.parse.urlencode(sentQueryParams) - if method in ['GET']: +if method in ['GET']: - #Options to add statements later on and for compatibility - pass +#Options to add statements later on and for compatibility +pass - elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: +elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) +if postData: +headers['Content-type'] = 'application/json' +data = self.sanitizeForSerialization(postData) +data = json.dumps(data) - else: - raise Exception('Method ' + method + ' is not recognized.') +else: +raise Exception('Method ' + method + ' is not recognized.') - if data: - data = data.encode('utf-8') +if data: +data = data.encode('utf-8') - requestParams = MethodRequest(method=method, url=url, - headers=headers, data=data) +requestParams = MethodRequest(method=method, url=url, +headers=headers, data=data) - # Make the request - request = urllib.request.urlopen(requestParams) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) +# Make the request +request = urllib.request.urlopen(requestParams) +encoding = request.headers.get_content_charset() +if not encoding: +encoding = 'iso-8859-1' +response = request.read().decode(encoding) - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None +try: +data = json.loads(response) +except ValueError: # PUT requests don't return anything +data = None - return data +return data - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.parse.quote(','.join(obj)) - else: - return urllib.parse.quote(str(obj)) +def toPathValue(self, obj): +"""Convert a string or object to a path-friendly value +Args: +obj -- object or string value +Returns: +string -- quoted value +""" +if type(obj) == list: +return urllib.parse.quote(','.join(obj)) +else: +return urllib.parse.quote(str(obj)) - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" +def sanitizeForSerialization(self, obj): +"""Dump an object into JSON for POSTing.""" - if type(obj) == type(None): - return None - elif type(obj) in [str, int, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.items() - if key != 'swaggerTypes'} +if type(obj) == type(None): +return None +elif type(obj) in [str, int, float, bool]: +return obj +elif type(obj) == list: +return [self.sanitizeForSerialization(subObj) for subObj in obj] +elif type(obj) == datetime.datetime: +return obj.isoformat() +else: +if type(obj) == dict: +objDict = obj +else: +objDict = obj.__dict__ +return {key: self.sanitizeForSerialization(val) +for (key, val) in objDict.items() +if key != 'swaggerTypes'} - def _iso8601Format(self, timesep, microsecond, offset, zulu): - """Format for parsing a datetime string with given properties. +def _iso8601Format(self, timesep, microsecond, offset, zulu): +"""Format for parsing a datetime string with given properties. - Args: - timesep -- string separating time from date ('T' or 't') - microsecond -- microsecond portion of time ('.XXX') - offset -- time offset (+/-XX:XX) or None - zulu -- 'Z' or 'z' for UTC, or None for time offset (+/-XX:XX) +Args: +timesep -- string separating time from date ('T' or 't') +microsecond -- microsecond portion of time ('.XXX') +offset -- time offset (+/-XX:XX) or None +zulu -- 'Z' or 'z' for UTC, or None for time offset (+/-XX:XX) - Returns: - str - format string for datetime.strptime""" +Returns: +str - format string for datetime.strptime""" - return '%Y-%m-%d{}%H:%M:%S{}{}'.format( - timesep, - '.%f' if microsecond else '', - zulu or ('%z' if offset else '')) +return '%Y-%m-%d{}%H:%M:%S{}{}'.format( +timesep, +'.%f' if microsecond else '', +zulu or ('%z' if offset else '')) - # http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - _iso8601Regex = re.compile( - r'^\d\d\d\d-\d\d-\d\d([Tt])\d\d:\d\d:\d\d(\.\d+)?(([Zz])|(\+|-)\d\d:?\d\d)?$') +# http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 +_iso8601Regex = re.compile( +r'^\d\d\d\d-\d\d-\d\d([Tt])\d\d:\d\d:\d\d(\.\d+)?(([Zz])|(\+|-)\d\d:?\d\d)?$') - def _parseDatetime(self, d): - if d is None: - return None - m = ApiClient._iso8601Regex.match(d) - if not m: - raise Exception('datetime regex match failed "%s"' % d) - timesep, microsecond, offset, zulu, plusminus = m.groups() - format = self._iso8601Format(timesep, microsecond, offset, zulu) - if offset and not zulu: - d = d.rsplit(sep=plusminus, maxsplit=1)[0] + offset.replace(':', '') - return datetime.datetime.strptime(d, format) +def _parseDatetime(self, d): +if d is None: +return None +m = ApiClient._iso8601Regex.match(d) +if not m: +raise Exception('datetime regex match failed "%s"' % d) +timesep, microsecond, offset, zulu, plusminus = m.groups() +format = self._iso8601Format(timesep, microsecond, offset, zulu) +if offset and not zulu: +d = d.rsplit(sep=plusminus, maxsplit=1)[0] + offset.replace(':', '') +return datetime.datetime.strptime(d, format) - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. +def deserialize(self, obj, objClass): +"""Derialize a JSON string into an object. - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" +Args: +obj -- string or object to be deserialized +objClass -- class literal for deserialzied object, or string +of class name +Returns: +object -- deserialized object""" - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] +# Have to accept objClass as string or actual type. Type could be a +# native Python type, or one of the model classes. +if type(objClass) == str: +if 'list[' in objClass: +match = re.match('list\[(.*)\]', objClass) +subClass = match.group(1) +return [self.deserialize(subObj, subClass) for subObj in obj] - if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) +if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): +objClass = eval(objClass) +else: # not a native type, must be model class +objClass = eval(objClass + '.' + objClass) - if objClass in [int, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - return self._parseDatetime(obj) +if objClass in [int, float, dict, list, str, bool]: +return objClass(obj) +elif objClass == datetime: +return self._parseDatetime(obj) - instance = objClass() +instance = objClass() - for attr, attrType in instance.swaggerTypes.items(): +for attr, attrType in instance.swaggerTypes.items(): - if attr in obj: - value = obj[attr] - if attrType in ['str', 'int', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, self._parseDatetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - attrType)) +if attr in obj: +value = obj[attr] +if attrType in ['str', 'int', 'float', 'bool']: +attrType = eval(attrType) +try: +value = attrType(value) +except UnicodeEncodeError: +value = unicode(value) +except TypeError: +value = value +setattr(instance, attr, value) +elif (attrType == 'datetime'): +setattr(instance, attr, self._parseDatetime(value)) +elif 'list[' in attrType: +match = re.match('list\[(.*)\]', attrType) +subClass = match.group(1) +subValues = [] +if not value: +setattr(instance, attr, None) +else: +for subValue in value: +subValues.append(self.deserialize(subValue, +subClass)) +setattr(instance, attr, subValues) +else: +setattr(instance, attr, self.deserialize(value, +attrType)) - return instance +return instance class MethodRequest(urllib.request.Request): - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" +def __init__(self, *args, **kwargs): +"""Construct a MethodRequest. Usage is the same as for +`urllib.Request` except it also takes an optional `method` +keyword argument. If supplied, `method` will be used instead of +the default.""" - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib.request.Request.__init__(self, *args, **kwargs) +if 'method' in kwargs: +self.method = kwargs.pop('method') +return urllib.request.Request.__init__(self, *args, **kwargs) - def get_method(self): - return getattr(self, 'method', urllib.request.Request.get_method(self)) +def get_method(self): +return getattr(self, 'method', urllib.request.Request.get_method(self)) diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache index b6341104188..88d1bce3563 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-body.mustache @@ -2,180 +2,186 @@ #include "{{prefix}}Helpers.h" #include "{{prefix}}ModelFactory.h" -#include -#include +#include + + #include + -namespace Swagger { -{{classname}}::{{classname}}() {} + namespace Swagger { + {{classname}}::{{classname}}() {} -{{classname}}::~{{classname}}() {} + {{classname}}::~{{classname}}() {} -{{classname}}::{{classname}}(QString host, QString basePath) { - this->host = host; - this->basePath = basePath; -} - -{{#operations}} -{{#operation}} -void -{{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - QString fullPath; - fullPath.append(this->host).append(this->basePath).append("{{path}}"); - - {{#pathParams}} - QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}"); - fullPath.replace({{paramName}}PathParam, stringValue({{paramName}})); - {{/pathParams}} - - {{#queryParams}} - {{^collectionFormat}} - if(fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append(QUrl::toPercentEncoding("{{paramName}}")) - .append("=") - .append(QUrl::toPercentEncoding(stringValue({{paramName}}))); - {{/collectionFormat}} - - {{#collectionFormat}} - - if({{{paramName}}}->size() > 0) { - if(QString("{{collectionFormat}}").indexOf("multi") == 0) { - foreach({{{baseType}}} t, *{{paramName}}) { - if(fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("{{{paramName}}}=").append(stringValue(t)); + {{classname}}::{{classname}}(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; } - } - else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) { - if(fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("{{paramName}}="); - qint32 count = 0; - foreach({{{baseType}}} t, *{{paramName}}) { - if(count > 0) { - fullPath.append(" "); - } - fullPath.append(stringValue(t)); - } - } - else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) { - if(fullPath.indexOf("?") > 0) - fullPath.append("&"); - else - fullPath.append("?"); - fullPath.append("{{paramName}}="); - qint32 count = 0; - foreach({{{baseType}}} t, *{{paramName}}) { - if(count > 0) { - fullPath.append("\t"); - } - fullPath.append(stringValue(t)); - } - } - } - {{/collectionFormat}} - {{/queryParams}} + {{#operations}} + {{#operation}} + void + {{classname}}::{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}} + , {{/hasMore}}{{/allParams}}) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("{{path}}"); - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "{{httpMethod}}"); + {{#pathParams}} + QString {{paramName}}PathParam("{"); {{paramName}}PathParam.append("{{paramName}}").append("}"); + fullPath.replace({{paramName}}PathParam, stringValue({{paramName}})); + {{/pathParams}} - {{#formParams}}{{^isFile}} - if({{paramName}} != NULL) { - input.add_var("{{paramName}}", *{{paramName}}); - } - {{/isFile}}{{/formParams}} + {{#queryParams}} + {{^collectionFormat}} + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("{{paramName}}")) + .append("=") + .append(QUrl::toPercentEncoding(stringValue({{paramName}}))); + {{/collectionFormat}} - {{#bodyParams}} - {{#isContainer}} - QJsonArray* {{paramName}}Array = new QJsonArray(); - toJsonArray((QList*){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*")); + {{#collectionFormat}} - QJsonDocument doc(*{{paramName}}Array); - QByteArray bytes = doc.toJson(); + if({{{paramName}}}->size() > 0) { + if(QString("{{collectionFormat}}").indexOf("multi") == 0) { + foreach({{{baseType}}} t, *{{paramName}}) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{{paramName}}}=").append(stringValue(t)); + } + } + else if (QString("{{collectionFormat}}").indexOf("ssv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{paramName}}="); + qint32 count = 0; + foreach({{{baseType}}} t, *{{paramName}}) { + if(count > 0) { + fullPath.append(" "); + } + fullPath.append(stringValue(t)); + } + } + else if (QString("{{collectionFormat}}").indexOf("tsv") == 0) { + if(fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("{{paramName}}="); + qint32 count = 0; + foreach({{{baseType}}} t, *{{paramName}}) { + if(count > 0) { + fullPath.append("\t"); + } + fullPath.append(stringValue(t)); + } + } + } - input.request_body.append(bytes); - {{/isContainer}} - {{^isContainer}} - QString output = {{paramName}}.asJson(); - input.request_body.append(output); - {{/isContainer}}{{/bodyParams}} + {{/collectionFormat}} + {{/queryParams}} - {{#headerParams}} - // TODO: add header support - {{/headerParams}} + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "{{httpMethod}}"); - connect(worker, - &HttpRequestWorker::on_execution_finished, - this, - &{{classname}}::{{nickname}}Callback); + {{#formParams}}{{^isFile}} + if({{paramName}} != NULL) { + input.add_var("{{paramName}}", *{{paramName}}); + } + {{/isFile}}{{/formParams}} - worker->execute(&input); -} + {{#bodyParams}} + {{#isContainer}} + QJsonArray* {{paramName}}Array = new QJsonArray(); + toJsonArray((QList + *){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*")); -void -{{classname}}::{{nickname}}Callback(HttpRequestWorker * worker) { - QString msg; - if (worker->error_type == QNetworkReply::NoError) { - msg = QString("Success! %1 bytes").arg(worker->response.length()); - } - else { - msg = "Error: " + worker->error_str; - } + QJsonDocument doc(*{{paramName}}Array); + QByteArray bytes = doc.toJson(); - {{#returnType}}{{#isListContainer}} - {{{returnType}}} output = {{{defaultResponse}}}; - QString json(worker->response); - QByteArray array (json.toStdString().c_str()); - QJsonDocument doc = QJsonDocument::fromJson(array); - QJsonArray jsonArray = doc.array(); + input.request_body.append(bytes); + {{/isContainer}} + {{^isContainer}} + QString output = {{paramName}}.asJson(); + input.request_body.append(output); + {{/isContainer}}{{/bodyParams}} - foreach(QJsonValue obj, jsonArray) { - {{{returnBaseType}}}* o = new {{returnBaseType}}(); - QJsonObject jv = obj.toObject(); - QJsonObject * ptr = (QJsonObject*)&jv; - o->fromJsonObject(*ptr); - output->append(o); - } - {{/isListContainer}} + {{#headerParams}} + // TODO: add header support + {{/headerParams}} - {{^isListContainer}}{{#returnTypeIsPrimitive}} - {{{returnType}}} output; // TODO add primitive output support - {{/returnTypeIsPrimitive}} - {{#isMapContainer}} - {{{returnType}}} output = {{{defaultResponse}}}; + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &{{classname}}::{{nickname}}Callback); - QString json(worker->response); - QByteArray array (json.toStdString().c_str()); - QJsonDocument doc = QJsonDocument::fromJson(array); - QJsonObject obj = doc.object(); + worker->execute(&input); + } - foreach(QString key, obj.keys()) { - qint32* val; - setValue(&val, obj[key], "{{returnBaseType}}", ""); - output->insert(key, *val); - } + void + {{classname}}::{{nickname}}Callback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + {{#returnType}}{{#isListContainer}} + {{{returnType}}} output = {{{defaultResponse}}}; + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + + foreach(QJsonValue obj, jsonArray) { + {{{returnBaseType}}}* o = new {{returnBaseType}}(); + QJsonObject jv = obj.toObject(); + QJsonObject * ptr = (QJsonObject*)&jv; + o->fromJsonObject(*ptr); + output->append(o); + } + {{/isListContainer}} + + {{^isListContainer}}{{#returnTypeIsPrimitive}} + {{{returnType}}} output; // TODO add primitive output support + {{/returnTypeIsPrimitive}} + {{#isMapContainer}} + {{{returnType}}} output = {{{defaultResponse}}}; + + QString json(worker->response); + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject obj = doc.object(); + + foreach(QString key, obj.keys()) { + qint32* val; + setValue(&val, obj[key], "{{returnBaseType}}", ""); + output->insert(key, *val); + } - {{/isMapContainer}} - {{^isMapContainer}} - {{^returnTypeIsPrimitive}}QString json(worker->response); - {{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, QString("{{{returnBaseType}}}"))); - {{/returnTypeIsPrimitive}} - {{/isMapContainer}} - {{/isListContainer}}{{/returnType}} + {{/isMapContainer}} + {{^isMapContainer}} + {{^returnTypeIsPrimitive}}QString json(worker->response); + {{{returnType}}} output = static_cast<{{{returnType}}}>(create(json, + QString("{{{returnBaseType}}}"))); + {{/returnTypeIsPrimitive}} + {{/isMapContainer}} + {{/isListContainer}}{{/returnType}} - worker->deleteLater(); + worker->deleteLater(); - {{#returnType}}emit {{nickname}}Signal(output);{{/returnType}} - {{^returnType}}emit {{nickname}}Signal();{{/returnType}} -} -{{/operation}} -{{/operations}} -} /* namespace Swagger */ + {{#returnType}}emit {{nickname}}Signal(output);{{/returnType}} + {{^returnType}}emit {{nickname}}Signal();{{/returnType}} + } + {{/operation}} + {{/operations}} + } /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache index 4260ba6ff86..ffee582a4fc 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/api-header.mustache @@ -6,14 +6,15 @@ {{#imports}}{{{import}}} {{/imports}} -#include +#include + -namespace Swagger { + namespace Swagger { -class {{classname}}: public QObject { + class {{classname}}: public QObject { Q_OBJECT -public: + public: {{classname}}(); {{classname}}(QString host, QString basePath); ~{{classname}}(); @@ -21,14 +22,15 @@ public: QString host; QString basePath; - {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}} + , {{/hasMore}}{{/allParams}}); {{/operation}}{{/operations}} -private: + private: {{#operations}}{{#operation}}void {{nickname}}Callback (HttpRequestWorker * worker); {{/operation}}{{/operations}} -signals: + signals: {{#operations}}{{#operation}}void {{nickname}}Signal({{#returnType}}{{{returnType}}} summary{{/returnType}}); {{/operation}}{{/operations}} -}; -} -#endif \ No newline at end of file + }; + } + #endif \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index 7f4d748c2dc..0cc60d91b90 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -1,166 +1,201 @@ #include "SWGHelpers.h" #include "SWGModelFactory.h" #include "SWGObject.h" -#import -#import -#import +#import + + #import + + #import + -namespace Swagger { + namespace Swagger { -void -setValue(void* value, QJsonValue obj, QString type, QString complexType) { - if(value == NULL) { - // can't set value with a null pointer - return; - } - if(QStringLiteral("bool").compare(type) == 0) { - bool * val = static_cast(value); - *val = obj.toBool(); - } - else if(QStringLiteral("qint32").compare(type) == 0) { - qint32 *val = static_cast(value); - *val = obj.toInt(); - } - else if(QStringLiteral("qint64").compare(type) == 0) { - qint64 *val = static_cast(value); - *val = obj.toVariant().toLongLong(); - } - else if (QStringLiteral("QString").compare(type) == 0) { - QString **val = static_cast(value); + void + setValue(void* value, QJsonValue obj, QString type, QString complexType) { + if(value == NULL) { + // can't set value with a null pointer + return; + } + if(QStringLiteral("bool").compare(type) == 0) { + bool * val = static_cast + (value); + *val = obj.toBool(); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32 *val = static_cast + (value); + *val = obj.toInt(); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64 *val = static_cast + (value); + *val = obj.toVariant().toLongLong(); + } + else if (QStringLiteral("QString").compare(type) == 0) { + QString **val = static_cast + (value); - if(val != NULL) { + if(val != NULL) { if(!obj.isNull()) { - // create a new value and return - delete *val; - *val = new QString(obj.toString()); - return; + // create a new value and return + delete *val; + *val = new QString(obj.toString()); + return; } else { - // set target to NULL - delete *val; - *val = NULL; + // set target to NULL + delete *val; + *val = NULL; } - } - else { + } + else { qDebug() << "Can't set value because the target pointer is NULL"; - } - } - else if(type.startsWith("SWG") && obj.isObject()) { - // complex type - QJsonObject jsonObj = obj.toObject(); - SWGObject * so = (SWGObject*)Swagger::create(type); - if(so != NULL) { + } + } + else if(type.startsWith("SWG") && obj.isObject()) { + // complex type + QJsonObject jsonObj = obj.toObject(); + SWGObject * so = (SWGObject*)Swagger::create(type); + if(so != NULL) { so->fromJsonObject(jsonObj); - SWGObject **val = static_cast(value); + SWGObject **val = static_cast + (value); delete *val; *val = so; - } - } - else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { - // list of values - QList* output = new QList(); - QJsonArray arr = obj.toArray(); - foreach (const QJsonValue & jval, arr) { + } + } + else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { + // list of values + QList + * output = new QList + (); + QJsonArray arr = obj.toArray(); + foreach (const QJsonValue & jval, arr) { if(complexType.startsWith("SWG")) { - // it's an object - SWGObject * val = (SWGObject*)create(complexType); - QJsonObject t = jval.toObject(); + // it's an object + SWGObject * val = (SWGObject*)create(complexType); + QJsonObject t = jval.toObject(); - val->fromJsonObject(t); - output->append(val); + val->fromJsonObject(t); + output->append(val); } else { - // primitives - if(QStringLiteral("qint32").compare(complexType) == 0) { - qint32 val; - setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); - output->append((void*)&val); - } - else if(QStringLiteral("qint64").compare(complexType) == 0) { - qint64 val; - setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); - output->append((void*)&val); - } - else if(QStringLiteral("bool").compare(complexType) == 0) { - bool val; - setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); - output->append((void*)&val); - } + // primitives + if(QStringLiteral("qint32").compare(complexType) == 0) { + qint32 val; + setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("qint64").compare(complexType) == 0) { + qint64 val; + setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("bool").compare(complexType) == 0) { + bool val; + setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); + output->append((void*)&val); + } + } + } + QList + **val = static_cast + **>(value); + delete *val; + *val = output; + } } - } - QList **val = static_cast**>(value); - delete *val; - *val = output; - } -} -void -toJsonValue(QString name, void* value, QJsonObject* output, QString type) { - if(value == NULL) { - return; - } - if(type.startsWith("SWG")) { - SWGObject *swgObject = reinterpret_cast(value); - if(swgObject != NULL) { - QJsonObject* o = (*swgObject).asJsonObject(); - if(name != NULL) { + void + toJsonValue(QString name, void* value, QJsonObject* output, QString type) { + if(value == NULL) { + return; + } + if(type.startsWith("SWG")) { + SWGObject *swgObject = reinterpret_cast + (value); + if(swgObject != NULL) { + QJsonObject* o = (*swgObject).asJsonObject(); + if(name != NULL) { output->insert(name, *o); delete o; - } - else { + } + else { output->empty(); foreach(QString key, o->keys()) { - output->insert(key, o->value(key)); + output->insert(key, o->value(key)); + } + } + } + } + else if(QStringLiteral("QString").compare(type) == 0) { + QString* str = static_cast + (value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32* str = static_cast + (value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64* str = static_cast + (value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("bool").compare(type) == 0) { + bool* str = static_cast + (value); + output->insert(name, QJsonValue(*str)); + } } - } - } - } - else if(QStringLiteral("QString").compare(type) == 0) { - QString* str = static_cast(value); - output->insert(name, QJsonValue(*str)); - } - else if(QStringLiteral("qint32").compare(type) == 0) { - qint32* str = static_cast(value); - output->insert(name, QJsonValue(*str)); - } - else if(QStringLiteral("qint64").compare(type) == 0) { - qint64* str = static_cast(value); - output->insert(name, QJsonValue(*str)); - } - else if(QStringLiteral("bool").compare(type) == 0) { - bool* str = static_cast(value); - output->insert(name, QJsonValue(*str)); - } -} -void -toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType) { - foreach(void* obj, *value) { - QJsonObject element; + void + toJsonArray(QList + * value, QJsonArray* output, QString innerName, QString innerType) { + foreach(void* obj, *value) { + QJsonObject element; - toJsonValue(NULL, obj, &element, innerType); - output->append(element); - } -} + toJsonValue(NULL, obj, &element, innerType); + output->append(element); + } + } -QString -stringValue(QString* value) { - QString* str = static_cast(value); - return QString(*str); -} + QString + stringValue(QString* value) { + QString* str = static_cast + (value); + return QString(*str); + } -QString -stringValue(qint32 value) { - return QString::number(value); -} + QString + stringValue(qint32 value) { + return QString::number(value); + } -QString -stringValue(qint64 value) { - return QString::number(value); -} + QString + stringValue(qint64 value) { + return QString::number(value); + } -QString -stringValue(bool value) { - return QString(value ? "true" : "false"); -} -} /* namespace Swagger */ + QString + stringValue(bool value) { + return QString(value ? "true" : "false"); + } + } /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache index 3a02c0952d5..52bba0455bc 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-header.mustache @@ -1,17 +1,20 @@ #ifndef SWGHELPERS_H #define SWGHELPERS_H -#include +#include + -namespace Swagger { + namespace Swagger { void setValue(void* value, QJsonValue obj, QString type, QString complexType); - void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + void toJsonArray(QList + * value, QJsonArray* output, QString innerName, QString innerType); void toJsonValue(QString name, void* value, QJsonObject* output, QString type); bool isCompatibleJsonValue(QString type); QString stringValue(QString* value); QString stringValue(qint32 value); QString stringValue(qint64 value); QString stringValue(bool value); -} + } -#endif // SWGHELPERS_H + #endif // SWGHELPERS_H diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache index 705cb852108..641457082c3 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache @@ -1,109 +1,114 @@ {{#models}}{{#model}} -#include "{{classname}}.h" + #include "{{classname}}.h" -#include "SWGHelpers.h" + #include "SWGHelpers.h" -#include -#include -#include -#include + #include + + #include + + #include + + #include + -namespace Swagger { + namespace Swagger { -{{classname}}::{{classname}}(QString* json) { - init(); - this->fromJson(*json); -} + {{classname}}::{{classname}}(QString* json) { + init(); + this->fromJson(*json); + } -{{classname}}::{{classname}}() { - init(); -} + {{classname}}::{{classname}}() { + init(); + } -{{classname}}::~{{classname}}() { - this->cleanup(); -} + {{classname}}::~{{classname}}() { + this->cleanup(); + } -void -{{classname}}::init() { + void + {{classname}}::init() { {{#vars}}{{name}} = {{{defaultValue}}}; {{/vars}} -} - -void -{{classname}}::cleanup() { - {{#vars}}{{#complexType}}if({{name}} != NULL) { - {{#isContainer}}QList<{{complexType}}*>* arr = {{name}}; - foreach({{complexType}}* o, *arr) { - delete o; } - {{/isContainer}}delete {{name}}; - }{{/complexType}} + + void + {{classname}}::cleanup() { + {{#vars}}{{#complexType}}if({{name}} != NULL) { + {{#isContainer}}QList<{{complexType}}*>* arr = {{name}}; + foreach({{complexType}}* o, *arr) { + delete o; + } + {{/isContainer}}delete {{name}}; + }{{/complexType}} {{/vars}} -} + } -{{classname}}* -{{classname}}::fromJson(QString &json) { - QByteArray array (json.toStdString().c_str()); - QJsonDocument doc = QJsonDocument::fromJson(array); - QJsonObject jsonObject = doc.object(); - this->fromJsonObject(jsonObject); - return this; -} + {{classname}}* + {{classname}}::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; + } -void -{{classname}}::fromJsonObject(QJsonObject &pJson) { + void + {{classname}}::fromJsonObject(QJsonObject &pJson) { {{#vars}}setValue(&{{name}}, pJson["{{name}}"], "{{baseType}}", "{{complexType}}"); {{/vars}} -} + } -QString -{{classname}}::asJson () -{ - QJsonObject* obj = this->asJsonObject(); - - QJsonDocument doc(*obj); - QByteArray bytes = doc.toJson(); - return QString(bytes); -} + QString + {{classname}}::asJson () + { + QJsonObject* obj = this->asJsonObject(); -QJsonObject* -{{classname}}::asJsonObject() { - QJsonObject* obj = new QJsonObject(); + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); + } + + QJsonObject* + {{classname}}::asJsonObject() { + QJsonObject* obj = new QJsonObject(); {{#vars}}{{#complexType}} - {{^isContainer}}{{#complexType}} - toJsonValue(QString("{{name}}"), {{name}}, obj, QString("{{complexType}}")); - {{/complexType}}{{^complexType}} - else if({{name}} != NULL && *{{name}} != NULL) { - obj->insert("{{name}}", QJsonValue(*{{name}})); - }{{/complexType}} - {{/isContainer}}{{#isContainer}} - QList<{{complexType}}*>* {{name}}List = {{name}}; - QJsonArray {{name}}JsonArray; - toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}"); + {{^isContainer}}{{#complexType}} + toJsonValue(QString("{{name}}"), {{name}}, obj, QString("{{complexType}}")); + {{/complexType}}{{^complexType}} + else if({{name}} != NULL && *{{name}} != NULL) { + obj->insert("{{name}}", QJsonValue(*{{name}})); + }{{/complexType}} + {{/isContainer}}{{#isContainer}} + QList<{{complexType}}*>* {{name}}List = {{name}}; + QJsonArray {{name}}JsonArray; + toJsonArray((QList + *){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}"); - obj->insert("{{name}}", {{name}}JsonArray); - {{/isContainer}} + obj->insert("{{name}}", {{name}}JsonArray); + {{/isContainer}} {{/complexType}}{{^complexType}}obj->insert("{{name}}", QJsonValue({{name}}));{{/complexType}} {{/vars}} - return obj; -} + return obj; + } -{{#vars}} -{{{datatype}}} -{{classname}}::{{getter}}() { - return {{name}}; -} -void -{{classname}}::{{setter}}({{{datatype}}} {{name}}) { - this->{{name}} = {{name}}; -} + {{#vars}} + {{{datatype}}} + {{classname}}::{{getter}}() { + return {{name}}; + } + void + {{classname}}::{{setter}}({{{datatype}}} {{name}}) { + this->{{name}} = {{name}}; + } -{{/vars}} + {{/vars}} -} /* namespace Swagger */ + } /* namespace Swagger */ {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache index 7b0b6cdcc1b..7a63ce9564a 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-header.mustache @@ -1,47 +1,48 @@ {{#models}}{{#model}}/* - * {{classname}}.h - * - * {{description}} - */ +* {{classname}}.h +* +* {{description}} +*/ #ifndef {{classname}}_H_ #define {{classname}}_H_ -#include +#include + {{/model}}{{/models}} {{#imports}}{{{import}}} {{/imports}} -#include "SWGObject.h" + #include "SWGObject.h" {{#models}}{{#model}} -namespace Swagger { + namespace Swagger { -class {{classname}}: public SWGObject { -public: + class {{classname}}: public SWGObject { + public: {{classname}}(); {{classname}}(QString* json); - virtual ~{{classname}}(); - void init(); - void cleanup(); + virtual ~{{classname}}(); + void init(); + void cleanup(); - QString asJson (); - QJsonObject* asJsonObject(); - void fromJsonObject(QJsonObject &json); + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); {{classname}}* fromJson(QString &jsonString); {{#vars}}{{{datatype}}} {{getter}}(); - void {{setter}}({{{datatype}}} {{name}}); + void {{setter}}({{{datatype}}} {{name}}); {{/vars}} -private: + private: {{#vars}}{{{datatype}}} {{name}}; {{/vars}} -}; + }; -} /* namespace Swagger */ + } /* namespace Swagger */ -#endif /* {{classname}}_H_ */ + #endif /* {{classname}}_H_ */ {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache index 1a2a831f5ac..de2eb05066a 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model.mustache @@ -1,58 +1,62 @@ {{#models}}{{#model}}/* - * {{classname}}.h - * - * {{description}} - */ +* {{classname}}.h +* +* {{description}} +*/ #ifndef {{classname}}_H_ #define {{classname}}_H_ -#include -#include -#include -#include -#include "{{prefix}}Helpers.h" -#include "{{prefix}}Object.h" +#include + + #include + + #include + + #include + + #include "{{prefix}}Helpers.h" + #include "{{prefix}}Object.h" -using namespace Tizen::Web::Json; + using namespace Tizen::Web::Json; {{/model}}{{/models}} {{#imports}}{{{import}}} {{/imports}} {{#models}}{{#model}} -namespace Swagger { + namespace Swagger { -class {{classname}}: public {{prefix}}Object { -public: + class {{classname}}: public {{prefix}}Object { + public: {{classname}}(); {{classname}}(String* json); - virtual ~{{classname}}(); + virtual ~{{classname}}(); - void init(); + void init(); - void cleanup(); + void cleanup(); - String asJson (); + String asJson (); - JsonObject* asJsonObject(); + JsonObject* asJsonObject(); - void fromJsonObject(IJsonValue* json); + void fromJsonObject(IJsonValue* json); {{classname}}* fromJson(String* obj); {{#vars}} - {{datatype}} {{getter}}(); - void {{setter}}({{datatype}} {{name}}); + {{datatype}} {{getter}}(); + void {{setter}}({{datatype}} {{name}}); {{/vars}} -private: + private: {{#vars}}{{datatype}} {{name}}; {{/vars}} -}; + }; -} /* namespace Swagger */ + } /* namespace Swagger */ -#endif /* {{classname}}_H_ */ + #endif /* {{classname}}_H_ */ {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache index 4ec9e6f7411..3a29a7ad1f5 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/modelFactory.mustache @@ -2,28 +2,29 @@ #define ModelFactory_H_ {{#models}}{{#model}} -#include "{{classname}}.h"{{/model}}{{/models}} + #include "{{classname}}.h"{{/model}}{{/models}} namespace Swagger { - inline void* create(QString type) { - {{#models}}{{#model}}if(QString("{{classname}}").compare(type) == 0) { - return new {{classname}}(); - } - {{/model}}{{/models}} - return NULL; - } +inline void* create(QString type) { +{{#models}}{{#model}}if(QString("{{classname}}").compare(type) == 0) { +return new {{classname}}(); +} +{{/model}}{{/models}} +return NULL; +} - inline void* create(QString json, QString type) { - void* val = create(type); - if(val != NULL) { - SWGObject* obj = static_cast(val); - return obj->fromJson(json); - } - if(type.startsWith("QString")) { - return new QString(); - } - return NULL; - } +inline void* create(QString json, QString type) { +void* val = create(type); +if(val != NULL) { +SWGObject* obj = static_cast +(val); +return obj->fromJson(json); +} +if(type.startsWith("QString")) { +return new QString(); +} +return NULL; +} } /* namespace Swagger */ #endif /* ModelFactory_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache index 62914cb5162..f4194b68578 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/object.mustache @@ -1,24 +1,25 @@ #ifndef _{{prefix}}_OBJECT_H_ #define _{{prefix}}_OBJECT_H_ -#include +#include + -class {{prefix}}Object { - public: + class {{prefix}}Object { + public: virtual QJsonObject* asJsonObject() { - return NULL; + return NULL; } virtual ~SWGObject() {} virtual SWGObject* fromJson(QString &jsonString) { - Q_UNUSED(jsonString); - return NULL; + Q_UNUSED(jsonString); + return NULL; } virtual void fromJsonObject(QJsonObject &json) { - Q_UNUSED(json); + Q_UNUSED(json); } virtual QString asJson() { - return QString(""); + return QString(""); } -}; + }; -#endif /* _{{prefix}}_OBJECT_H_ */ + #endif /* _{{prefix}}_OBJECT_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache index a916f363ff5..38d436fe735 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache @@ -10,20 +10,20 @@ import java.util.*; {{/imports}} {{#operations}} -public interface {{classname}} { - {{#operation}} - /** - * {{summary}} - * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ - {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} - @{{httpMethod}}("{{path}}") - {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{^hasMore}} - );{{/hasMore}}{{/allParams}} - {{/operation}} -} + public interface {{classname}} { + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} * @param {{paramName}} {{description}} + {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + {{#formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + @{{httpMethod}}("{{path}}") + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + );{{/hasMore}}{{/allParams}} + {{/operation}} + } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache b/modules/swagger-codegen/src/main/resources/retrofit/model.mustache index 85213ed4c95..8764e59fdeb 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/model.mustache @@ -7,44 +7,44 @@ import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; {{#models}} -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#model}}{{#description}} + /** + * {{description}} + **/{{/description}} + @ApiModel(description = "{{{description}}}") + public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { + public enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - };{{/isEnum}} + };{{/isEnum}} /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @SerializedName("{{baseName}}"){{#isEnum}} - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @SerializedName("{{baseName}}"){{#isEnum}} + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - {{#vars}} - public {{{datatypeWithEnum}}} {{getter}}() { + {{#vars}} + public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; - } + } {{/vars}} @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}}sb.append("}\n"); - return sb.toString(); + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); } -} -{{/model}} + } + {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache index 7d999db86ca..24307d97152 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache @@ -1,143 +1,146 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen - - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - - com.google.code.gson - gson - ${gson-version} - compile - - - com.squareup.retrofit - retrofit - ${retrofit-version} - compile - + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.google.code.gson + gson + ${gson-version} + compile + + + com.squareup.retrofit + retrofit + ${retrofit-version} + compile + - - - junit - junit - ${junit-version} - test - - - - 1.5.0 - 2.3.1 - 1.9.0 - 1.0.0 - 4.12 - + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.3.1 + 1.9.0 + 1.0.0 + 4.12 + diff --git a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache index 218a9304071..3350f79ed48 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache @@ -6,18 +6,18 @@ import retrofit.RestAdapter; import retrofit.converter.GsonConverter; public class ServiceGenerator { - // No need to instantiate this class. - private ServiceGenerator() { } +// No need to instantiate this class. +private ServiceGenerator() { } - public static S createService(Class serviceClass) { +public static S createService(Class serviceClass) { Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .create(); + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); RestAdapter adapter = new RestAdapter.Builder() - .setEndpoint("{{basePath}}") - .setConverter(new GsonConverter(gson)) - .build(); + .setEndpoint("{{basePath}}") + .setConverter(new GsonConverter(gson)) + .build(); return adapter.create(serviceClass); - } -} + } + } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 3e1ac14014e..88c6f4b676a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -2,60 +2,60 @@ require "uri" module {{moduleName}} {{#operations}} - class {{classname}} + class {{classname}} basePath = "{{basePath}}" # apiInvoker = APIInvoker -{{#operation}} -{{newline}} - # {{summary}} - # {{notes}} -{{#allParams}}{{#required}} # @param {{paramName}} {{description}} -{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} -{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? - {{/required}}{{/allParams}} + {{#operation}} + {{newline}} + # {{summary}} + # {{notes}} + {{#allParams}}{{#required}} # @param {{paramName}} {{description}} + {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters + {{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} + {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] + def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? + {{/required}}{{/allParams}} - # resource path - path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} + # resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} - # query parameters - query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + # query parameters + query_params = {}{{#queryParams}}{{#required}} + query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} - # header parameters - header_params = {} + # header parameters + header_params = {} - # HTTP header 'Accept' (if needed) - _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Accept' (if needed) + _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - # HTTP header 'Content-Type' - _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} - header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + # HTTP header 'Content-Type' + _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} - # form parameters - form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + # form parameters + form_params = {}{{#formParams}}{{#required}} + form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} - # http body (model) - {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) - {{/bodyParam}} + # http body (model) + {{^bodyParam}}post_body = nil + {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}} - auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - nil{{/returnType}} + auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] + {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body + {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + nil{{/returnType}} + end + {{/operation}} end -{{/operation}} - end {{/operations}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index c0e563a0bb7..70c7afdb889 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -1,83 +1,83 @@ module {{moduleName}} - # base class containing fundamental method such as to_hash, build_from_hash and more - class BaseObject +# base class containing fundamental method such as to_hash, build_from_hash and more +class BaseObject - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end - - # build the object from hash - def build_from_hash(attributes) - return nil unless attributes.is_a?(Hash) - self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i - if attributes[self.class.attribute_map[key]].is_a?(Array) - self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode - end - elsif !attributes[self.class.attribute_map[key]].nil? - self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end - end - - self - end - - def _deserialize(type, value) - case type.to_sym - when :DateTime - DateTime.parse(value) - when :string - value.to_s - when :int - value.to_i - when :double - value.to_f - when :boolean - if value =~ /^(true|t|yes|y|1)$/i - true - else - false - end - else # model - _model = {{moduleName}}.const_get(type).new - _model.build_from_hash(value) - end - end - - # to_body is an alias to to_body (backward compatibility) - def to_hash - hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? - else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value - end - end - end - hash - end - - # Method to output non-array value in the form of hash - # For object, use to_hash. Otherwise, just return the value - def _to_hash(value) - if value.respond_to? :to_hash - value.to_hash - else - value - end - end - - end +# return the object in the form of hash +def to_body +body = {} +self.class.attribute_map.each_pair do |key, value| +body[value] = self.send(key) unless self.send(key).nil? +end +body +end + +# build the object from hash +def build_from_hash(attributes) +return nil unless attributes.is_a?(Hash) +self.class.swagger_types.each_pair do |key, type| +if type =~ /^array\[(.*)\]/i +if attributes[self.class.attribute_map[key]].is_a?(Array) +self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) +else +#TODO show warning in debug mode +end +elsif !attributes[self.class.attribute_map[key]].nil? +self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) +else +# data not found in attributes(hash), not an issue as the data can be optional +end +end + +self +end + +def _deserialize(type, value) +case type.to_sym +when :DateTime +DateTime.parse(value) +when :string +value.to_s +when :int +value.to_i +when :double +value.to_f +when :boolean +if value =~ /^(true|t|yes|y|1)$/i +true +else +false +end +else # model +_model = {{moduleName}}.const_get(type).new +_model.build_from_hash(value) +end +end + +# to_body is an alias to to_body (backward compatibility) +def to_hash +hash = {} +self.class.attribute_map.each_pair do |key, value| +if self.send(key).is_a?(Array) +next if self.send(key).empty? +hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? +else +unless (_tmp_value = _to_hash self.send(key)).nil? +hash[value] = _tmp_value +end +end +end +hash +end + +# Method to output non-array value in the form of hash +# For object, use to_hash. Otherwise, just return the value +def _to_hash(value) +if value.respond_to? :to_hash +value.to_hash +else +value +end +end + +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index d0d4e787756..ca817247130 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,40 +1,40 @@ module {{moduleName}} {{#models}} # {{description}} {{#model}} class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - {{#vars}} - # {{description}} - :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } +attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} +# attribute mapping from ruby-style variable name to JSON key +def self.attribute_map +{ +{{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} +{{/vars}} +} +end + +# attribute type +def self.swagger_types +{ +{{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} +{{/vars}} +} +end + +def initialize(attributes = {}) +return if !attributes.is_a?(Hash) || attributes.empty? + +# convert string to symbol for hash key +attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + +{{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} end - - # attribute type - def self.swagger_types - { - {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - {{#vars}} - if attributes[:'{{{baseName}}}'] - {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) - @{{{name}}} = value - end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} - end - {{/vars}} - end - end +{{/vars}} +end +end {{/model}} {{/models}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache b/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache index 28932890af9..f400813974f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache @@ -1,90 +1,90 @@ # module Swagger - class Object - - unless Object.method_defined? :blank? - def blank? - respond_to?(:empty?) ? empty? : !self - end - end - - unless Object.method_defined? :present? - def present? - !blank? - end - end +class Object - end +unless Object.method_defined? :blank? +def blank? +respond_to?(:empty?) ? empty? : !self +end +end - class String +unless Object.method_defined? :present? +def present? +!blank? +end +end - unless String.method_defined? :underscore - def underscore - self.gsub(/::/, '/'). - gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). - gsub(/([a-z\d])([A-Z])/,'\1_\2'). - tr("-", "_"). - downcase - end - end - - unless String.method_defined? :camelize - def camelize(first_letter_in_uppercase = true) - if first_letter_in_uppercase != :lower - self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } - else - self.to_s[0].chr.downcase + camelize(self)[1..-1] - end - end - end +end - end +class String - class Hash +unless String.method_defined? :underscore +def underscore +self.gsub(/::/, '/'). +gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). +gsub(/([a-z\d])([A-Z])/,'\1_\2'). +tr("-", "_"). +downcase +end +end - unless Hash.method_defined? :stringify_keys - def stringify_keys - inject({}) do |options, (key, value)| - options[key.to_s] = value - options - end - end - end - - unless Hash.method_defined? :stringify_keys! - def stringify_keys! - self.replace(self.stringify_keys) - end - end +unless String.method_defined? :camelize +def camelize(first_letter_in_uppercase = true) +if first_letter_in_uppercase != :lower +self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } +else +self.to_s[0].chr.downcase + camelize(self)[1..-1] +end +end +end - unless Hash.method_defined? :symbolize_keys - def symbolize_keys - inject({}) do |options, (key, value)| - options[(key.to_sym rescue key) || key] = value - options - end - end - end - - unless Hash.method_defined? :symbolize_keys! - def symbolize_keys! - self.replace(self.symbolize_keys) - end - end +end - unless Hash.method_defined? :symbolize_and_underscore_keys - def symbolize_and_underscore_keys - inject({}) do |options, (key, value)| - options[(key.to_s.underscore.to_sym rescue key) || key] = value - options - end - end - end +class Hash - unless Hash.method_defined? :symbolize_and_underscore_keys! - def symbolize_and_underscore_keys! - self.replace(self.symbolize_and_underscore_keys) - end - end - - end +unless Hash.method_defined? :stringify_keys +def stringify_keys +inject({}) do |options, (key, value)| +options[key.to_s] = value +options +end +end +end + +unless Hash.method_defined? :stringify_keys! +def stringify_keys! +self.replace(self.stringify_keys) +end +end + +unless Hash.method_defined? :symbolize_keys +def symbolize_keys +inject({}) do |options, (key, value)| +options[(key.to_sym rescue key) || key] = value +options +end +end +end + +unless Hash.method_defined? :symbolize_keys! +def symbolize_keys! +self.replace(self.symbolize_keys) +end +end + +unless Hash.method_defined? :symbolize_and_underscore_keys +def symbolize_and_underscore_keys +inject({}) do |options, (key, value)| +options[(key.to_s.underscore.to_sym rescue key) || key] = value +options +end +end +end + +unless Hash.method_defined? :symbolize_and_underscore_keys! +def symbolize_and_underscore_keys! +self.replace(self.symbolize_and_underscore_keys) +end +end + +end # end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index dd2f630a8c9..829ecbe0b1e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -2,77 +2,77 @@ require 'logger' require 'json' module {{moduleName}} - module Swagger - class << self - attr_accessor :logger +module Swagger +class << self +attr_accessor :logger - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration +# A Swagger configuration object. Must act like a hash and return sensible +# values for all Swagger configuration options. See Swagger::Configuration. +attr_accessor :configuration - attr_accessor :resources +attr_accessor :resources - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? +# Call this method to modify defaults in your initializers. +# +# @example +# Swagger.configure do |config| +# config.api_key['api_key'] = '1234567890abcdef' # api key authentication +# config.username = 'wordlover' # http basic authentication +# config.password = 'i<3words' # http basic authentication +# config.format = 'json' # optional, defaults to 'json' +# end +# +def configure +yield(configuration) if block_given? - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) +# Configure logger. Default to use Rails +self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') +# remove :// from scheme +configuration.scheme.sub!(/:\/\//, '') - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first +# remove http(s):// and anything after a slash +configuration.host.sub!(/https?:\/\//, '') +configuration.host = configuration.host.split('/').first - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - end - end - - class ServerError < StandardError - end - - class ClientError < StandardError - end +# Add leading and trailing slashes to base_path +configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') +configuration.base_path = "" if configuration.base_path == "/" +end + +def authenticated? +Swagger.configuration.auth_token.present? +end + +def de_authenticate +Swagger.configuration.auth_token = nil +end + +def authenticate +return if Swagger.authenticated? + +if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? +raise ClientError, "Username and password are required to authenticate." +end + +request = Swagger::Request.new( +:get, +"account/authenticate/{username}", +:params => { +:username => Swagger.configuration.username, +:password => Swagger.configuration.password +} +) + +response_body = request.response.body +Swagger.configuration.auth_token = response_body['token'] +end +end +end + +class ServerError < StandardError +end + +class ClientError < StandardError +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache index e9a8af9c162..a6ad16d376a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -1,29 +1,29 @@ module {{moduleName}} - module Swagger - class Configuration - attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl +module Swagger +class Configuration +attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true +# Defaults go in here.. +def initialize +@format = 'json' +@scheme = '{{scheme}}' +@host = '{{host}}' +@base_path = '{{contextPath}}' +@user_agent = "ruby-swagger-#{Swagger::VERSION}" +@inject_format = false +@force_ending_format = false +@camelize_params = true - # keys for API key authentication (param-name => api-key) - @api_key = {} - # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) - @api_key_prefix = {} +# keys for API key authentication (param-name => api-key) +@api_key = {} +# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) +@api_key_prefix = {} - # whether to verify SSL certificate, default to true - # Note: do NOT set it to false in production code, otherwise you would - # face multiple types of cryptographic attacks - @verify_ssl = true - end - end - end +# whether to verify SSL certificate, default to true +# Note: do NOT set it to false in production code, otherwise you would +# face multiple types of cryptographic attacks +@verify_ssl = true +end +end +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index 99b58d58be8..2c7d985f134 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -1,272 +1,272 @@ module {{moduleName}} - module Swagger - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' +module Swagger +class Request +require 'uri' +require 'addressable/uri' +require 'typhoeus' - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names +attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} +# All requests must have an HTTP method and a path +# Optionals parameters are :params, :headers, :body, :format, :host +def initialize(http_method, path, attributes={}) +attributes[:format] ||= Swagger.configuration.format +attributes[:params] ||= {} - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - 'User-Agent' => Swagger.configuration.user_agent - } +# Set default headers +default_headers = { +'Content-Type' => "application/#{attributes[:format].downcase}", +'User-Agent' => Swagger.configuration.user_agent +} - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) +# Merge argument headers into defaults +attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - - update_params_for_auth! - end - - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} - @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} - @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} - http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n") - @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} - end - end - end - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if Swagger.configuration.api_key_prefix[param_name].present? - "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" - else - Swagger.configuration.api_key[param_name] - end - end - - # Construct a base URL - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - u - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo - end - end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - data - elsif @body # http body is JSON - @body.is_a?(String) ? @body : @body.to_json - else - nil - end - end - - # Construct a query string from the query-string-type params - def query_string - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym - end - query_values[key] = value.to_s - end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - - request_options = { - :ssl_verifypeer => Swagger.configuration.verify_ssl, - :headers => self.headers.stringify_keys - } - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - request_options - ) - - when :post,:POST - Typhoeus::Request.post( - self.url, - request_options.merge(:body => self.outgoing_body) - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - request_options.merge(:body => self.outgoing_body) - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - request_options.merge(:body => self.outgoing_body) - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - request_options.merge(:body => self.outgoing_body) - ) - end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end - end +# Stick in the auth token if there is one +if Swagger.authenticated? +attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) +end + +self.http_method = http_method.to_sym +self.path = path +attributes.each do |name, value| +send("#{name.to_s.underscore.to_sym}=", value) +end + +update_params_for_auth! +end + +# Update hearder and query params based on authentication settings. +def update_params_for_auth! +(@auth_names || []).each do |auth_name| +case auth_name +{{#authMethods}}when '{{name}}' +{{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} +@headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} +@params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} +http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n") +@headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} +{{/authMethods}} +end +end +end + +# Get API key (with prefix if set). +# @param [String] param_name the parameter name of API key auth +def get_api_key_with_prefix(param_name) +if Swagger.configuration.api_key_prefix[param_name].present? +"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" +else +Swagger.configuration.api_key[param_name] +end +end + +# Construct a base URL +def url(options = {}) +u = Addressable::URI.new( +:scheme => Swagger.configuration.scheme, +:host => Swagger.configuration.host, +:path => self.interpreted_path, +:query => self.query_string.sub(/\?/, '') +).to_s + +# Drop trailing question mark, if present +u.sub! /\?$/, '' + +u +end + +# Iterate over the params hash, injecting any path values into the path string +# e.g. /word.{format}/{word}/entries => /word.json/cat/entries +def interpreted_path +p = self.path.dup + +# Stick a .{format} placeholder into the path if there isn't +# one already or an actual format like json or xml +# e.g. /words/blah => /words.{format}/blah +if Swagger.configuration.inject_format +unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } +p = p.sub(/^(\/?\w+)/, "\\1.#{format}") +end +end + +# Stick a .{format} placeholder on the end of the path if there isn't +# one already or an actual format like json or xml +# e.g. /words/blah => /words/blah.{format} +if Swagger.configuration.force_ending_format +unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } +p = "#{p}.#{format}" +end +end + +p = p.sub("{format}", self.format.to_s) + +URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') +end + +# Massage the request body into a state of readiness +# If body is a hash, camelize all keys then convert to a json string +def body=(value) +if value.is_a?(Hash) +value = value.inject({}) do |memo, (k,v)| +memo[k.to_s.camelize(:lower).to_sym] = v +memo +end +end +@body = value +end + +# If body is an object, JSONify it before making the actual request. +# For form parameters, remove empty value +def outgoing_body +# http form +if headers['Content-Type'] == 'application/x-www-form-urlencoded' +data = form_params.dup +data.each do |key, value| +data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter +end +data +elsif @body # http body is JSON +@body.is_a?(String) ? @body : @body.to_json +else +nil +end +end + +# Construct a query string from the query-string-type params +def query_string +# Iterate over all params, +# .. removing the ones that are part of the path itself. +# .. stringifying values so Addressable doesn't blow up. +query_values = {} +self.params.each_pair do |key, value| +next if self.path.include? "{#{key}}" # skip path params +next if value.blank? && value.class != FalseClass # skip empties +if Swagger.configuration.camelize_params +key = key.to_s.camelize(:lower).to_sym +end +query_values[key] = value.to_s +end + +# We don't want to end up with '?' as our query string +# if there aren't really any params +return "" if query_values.blank? + +# Addressable requires query_values to be set after initialization.. +qs = Addressable::URI.new +qs.query_values = query_values +qs.to_s +end + +def make +#TODO use configuration setting to determine if debugging +#logger = Logger.new STDOUT +#logger.debug self.url + +request_options = { +:ssl_verifypeer => Swagger.configuration.verify_ssl, +:headers => self.headers.stringify_keys +} +response = case self.http_method.to_sym +when :get,:GET +Typhoeus::Request.get( +self.url, +request_options +) + +when :post,:POST +Typhoeus::Request.post( +self.url, +request_options.merge(:body => self.outgoing_body) +) + +when :patch,:PATCH +Typhoeus::Request.patch( +self.url, +request_options.merge(:body => self.outgoing_body) +) + +when :put,:PUT +Typhoeus::Request.put( +self.url, +request_options.merge(:body => self.outgoing_body) +) + +when :delete,:DELETE +Typhoeus::Request.delete( +self.url, +request_options.merge(:body => self.outgoing_body) +) +end +Response.new(response) +end + +def response +self.make +end + +def response_code_pretty +return unless @response.present? +@response.code.to_s +end + +def response_headers_pretty +return unless @response.present? +# JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient +@response.headers.gsub(/\n/, '
') # <- This is for Typhoeus +end + +# return 'Accept' based on an array of accept provided +# @param [Array] header_accept_array Array fo 'Accept' +# @return String Accept (e.g. application/json) +def self.select_header_accept header_accept_array +if header_accept_array.empty? +return +elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } +'application/json' # look for json data by default +else +header_accept_array.join(',') +end +end + +# return the content type based on an array of content-type provided +# @param [Array] content_type_array Array fo content-type +# @return String Content-Type (e.g. application/json) +def self.select_header_content_type content_type_array +if content_type_array.empty? +'application/json' # use application/json by default +elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } +'application/json' # use application/json if it's included +else +content_type_array[0]; # otherwise, use the first one +end +end + +# static method to convert object (array, hash, object, etc) to JSON string +# @param model object to be converted into JSON string +# @return string JSON string representation of the object +def self.object_to_http_body model +return if model.nil? +_body = nil +if model.is_a?(Array) +_body = model.map{|m| object_to_hash(m) } +else +_body = object_to_hash(model) +end +_body.to_json +end + +# static method to convert object(non-array) to hash +# @param obj object to be converted into JSON string +# @return string JSON string representation of the object +def self.object_to_hash obj +if obj.respond_to?(:to_hash) +obj.to_hash +else +obj +end +end + +end +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index e7bb482fb66..7f9ad4f3281 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -1,70 +1,70 @@ module {{moduleName}} - module Swagger - class Response - require 'json' +module Swagger +class Response +require 'json' - attr_accessor :raw +attr_accessor :raw - def initialize(raw) - self.raw = raw +def initialize(raw) +self.raw = raw - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) - end - end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end +case self.code +when 500..510 then raise(ServerError, self.error_message) +when 299..426 then raise(ClientError, self.error_message) +end +end + +def code +raw.code +end + +# Account for error messages that take different forms... +def error_message +body['message'] +rescue +body +end + +# If body is JSON, parse it +# Otherwise return raw string +def body +JSON.parse(raw.body, :symbolize_names => true) +rescue +raw.body +end + +# `headers_hash` is a Typhoeus-specific extension of Hash, +# so simplify it back into a regular old Hash. +def headers +h = {} +raw.headers_hash.each {|k,v| h[k] = v } +h +end + +# Extract the response format from the header hash +# e.g. {'Content-Type' => 'application/json'} +def format +headers['Content-Type'].split("/").last.downcase +end + +def json? +format == 'json' +end + +def xml? +format == 'xml' +end + +def pretty_body +return unless body.present? +case format +when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') +end +end + +def pretty_headers +JSON.pretty_generate(headers).gsub(/\n/, '
') +end +end +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache index 332a5e66f45..a3c42972c3d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache @@ -1,5 +1,5 @@ module {{moduleName}} - module Swagger - VERSION = "{{appVersion}}" - end +module Swagger +VERSION = "{{appVersion}}" +end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache index 8ae4bfa1a49..26b0a040cbd 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache @@ -3,30 +3,30 @@ $:.push File.expand_path("../lib", __FILE__) require "{{gemName}}/swagger/version" Gem::Specification.new do |s| - s.name = "{{gemName}}" - s.version = {{moduleName}}::Swagger::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] - s.homepage = "http://swagger.io" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - s.license = "Apache-2.0" +s.name = "{{gemName}}" +s.version = {{moduleName}}::Swagger::VERSION +s.platform = Gem::Platform::RUBY +s.authors = ["Zeke Sikelianos", "Tony Tam"] +s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] +s.homepage = "http://swagger.io" +s.summary = %q{A ruby wrapper for the swagger APIs} +s.description = %q{This gem maps to a swagger API} +s.license = "Apache-2.0" - s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' - s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' - s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' +s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' +s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' +s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' - s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' - s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' - s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' - s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' - s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' - s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' - s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' +s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' +s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' +s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' +s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' +s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' +s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' +s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' - s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } - s.test_files = `find spec/*`.split("\n") - s.executables = [] - s.require_paths = ["lib"] +s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } +s.test_files = `find spec/*`.split("\n") +s.executables = [] +s.require_paths = ["lib"] end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index df675ddf26e..5268a42657f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -9,17 +9,17 @@ require '{{gemName}}/swagger/version' # Models require '{{modelPackage}}/base_object' {{#models}} -require '{{importPath}}' + require '{{importPath}}' {{/models}} # APIs {{#apiInfo}} -{{#apis}} -require '{{importPath}}' -{{/apis}} + {{#apis}} + require '{{importPath}}' + {{/apis}} {{/apiInfo}} module {{moduleName}} - # Initialize the default configuration - Swagger.configuration ||= Swagger::Configuration.new +# Initialize the default configuration +Swagger.configuration ||= Swagger::Configuration.new end diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 87b04b5900f..de96bb528f4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -16,77 +16,77 @@ import java.util.Date import scala.collection.mutable.HashMap {{#operations}} -class {{classname}}(val defBasePath: String = "{{basePath}}", - defApiInvoker: ApiInvoker = ApiInvoker) { - var basePath = defBasePath - var apiInvoker = defApiInvoker + class {{classname}}(val defBasePath: String = "{{basePath}}", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker - def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value - {{#operation}} - /** - * {{summary}} - * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ - def {{nickname}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { - // create path and map variables - val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) + {{#operation}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} * @param {{paramName}} {{description}} + {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + def {{nickname}} ({{#allParams}}{{paramName}}: {{dataType}}{{#defaultValue}} /* = {{{defaultValue}}} */{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {{#returnType}}: Option[{{returnType}}]{{/returnType}} = { + // create path and map variables + val path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}",apiInvoker.escape({{paramName}})) - {{/pathParams}} + {{/pathParams}} - val contentTypes = List({{#consumes}}"{{mediaType}}", {{/consumes}}"application/json") - val contentType = contentTypes(0) + val contentTypes = List({{#consumes}}"{{mediaType}}", {{/consumes}}"application/json") + val contentType = contentTypes(0) - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - val formParams = new HashMap[String, String] + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] - {{#requiredParamCount}} - // verify required params are set - (List({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}).filter(_ != null)).size match { - case {{requiredParamCount}} => // all required values set - case _ => throw new Exception("missing required params") - } - {{/requiredParamCount}} + {{#requiredParamCount}} + // verify required params are set + (List({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}).filter(_ != null)).size match { + case {{requiredParamCount}} => // all required values set + case _ => throw new Exception("missing required params") + } + {{/requiredParamCount}} - {{#queryParams}}if(String.valueOf({{paramName}}) != "null") queryParams += "{{baseName}}" -> {{paramName}}.toString - {{/queryParams}} - - {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}} - {{/headerParams}} + {{#queryParams}}if(String.valueOf({{paramName}}) != "null") queryParams += "{{baseName}}" -> {{paramName}}.toString + {{/queryParams}} - var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} + {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}} + {{/headerParams}} - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - {{#formParams}}{{#notFile}} - mp.field("{{baseName}}", {{paramName}}.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - {{/notFile}}{{#isFile}} - mp.field("{{baseName}}", file.getName) - mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)) - {{/isFile}}{{/formParams}} - postBody = mp - } - else { - {{#formParams}}{{#notFile}}formParams += "{{baseName}}" -> {{paramName}}.toString(){{/notFile}} - {{/formParams}} - } + var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} - try { - apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + {{#formParams}}{{#notFile}} + mp.field("{{baseName}}", {{paramName}}.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + {{/notFile}}{{#isFile}} + mp.field("{{baseName}}", file.getName) + mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)) + {{/isFile}}{{/formParams}} + postBody = mp + } + else { + {{#formParams}}{{#notFile}}formParams += "{{baseName}}" -> {{paramName}}.toString(){{/notFile}} + {{/formParams}} + } + + try { + apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) - {{/returnType}} + {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) + {{/returnType}} case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + {{/operation}} } - } - {{/operation}} -} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index f432c2dc59e..d1ac430f6ad 100644 --- a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -25,179 +25,179 @@ import com.fasterxml.jackson.annotation._ import com.fasterxml.jackson.databind.annotation.JsonSerialize object ScalaJsonUtil { - def getJsonMapper = { - val mapper = new ObjectMapper() - mapper.registerModule(new DefaultScalaModule()) - mapper.registerModule(new JodaModule()); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) - mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) - mapper - } +def getJsonMapper = { +val mapper = new ObjectMapper() +mapper.registerModule(new DefaultScalaModule()) +mapper.registerModule(new JodaModule()); +mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); +mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) +mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) +mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) +mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) +mapper +} } class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, - httpHeaders: HashMap[String, String] = HashMap(), - hostMap: HashMap[String, Client] = HashMap(), - asyncHttpClient: Boolean = false, - authScheme: String = "", - authPreemptive: Boolean = false) { +httpHeaders: HashMap[String, String] = HashMap(), +hostMap: HashMap[String, Client] = HashMap(), +asyncHttpClient: Boolean = false, +authScheme: String = "", +authPreemptive: Boolean = false) { - var defaultHeaders: HashMap[String, String] = httpHeaders +var defaultHeaders: HashMap[String, String] = httpHeaders - def escape(value: String): String = { - URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") - } +def escape(value: String): String = { +URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") +} - def escape(value: Long): String = value.toString - def escape(value: Double): String = value.toString - def escape(value: Float): String = value.toString +def escape(value: Long): String = value.toString +def escape(value: Double): String = value.toString +def escape(value: Float): String = value.toString - def deserialize(json: String, containerType: String, cls: Class[_]) = { - if (cls == classOf[String]) { - json match { - case s: String => { - if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) - else s - } - case _ => null - } - } else { - containerType.toLowerCase match { - case "array" => { - val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) - val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] - response.asScala.toList - } - case "list" => { - val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) - val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] - response.asScala.toList - } - case _ => { - json match { - case e: String if ("\"\"" == e) => null - case _ => mapper.readValue(json, cls) - } - } - } - } - } +def deserialize(json: String, containerType: String, cls: Class[_]) = { +if (cls == classOf[String]) { +json match { +case s: String => { +if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) +else s +} +case _ => null +} +} else { +containerType.toLowerCase match { +case "array" => { +val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) +val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] +response.asScala.toList +} +case "list" => { +val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) +val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] +response.asScala.toList +} +case _ => { +json match { +case e: String if ("\"\"" == e) => null +case _ => mapper.readValue(json, cls) +} +} +} +} +} - def serialize(obj: AnyRef): String = { - if (obj != null) { - obj match { - case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) - case _ => mapper.writeValueAsString(obj) - } - } else null - } +def serialize(obj: AnyRef): String = { +if (obj != null) { +obj match { +case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) +case _ => mapper.writeValueAsString(obj) +} +} else null +} - def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { - val client = getClient(host) +def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { +val client = getClient(host) - val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") - val builder = client.resource(host + path + querystring).accept(contentType) - headerParams.map(p => builder.header(p._1, p._2)) - defaultHeaders.map(p => { - headerParams.contains(p._1) match { - case true => // override default with supplied header - case false => if (p._2 != null) builder.header(p._1, p._2) - } - }) - var formData: MultivaluedMapImpl = null - if(contentType == "application/x-www-form-urlencoded") { - formData = new MultivaluedMapImpl() - formParams.map(p => formData.add(p._1, p._2)) - } +val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") +val builder = client.resource(host + path + querystring).accept(contentType) +headerParams.map(p => builder.header(p._1, p._2)) +defaultHeaders.map(p => { +headerParams.contains(p._1) match { +case true => // override default with supplied header +case false => if (p._2 != null) builder.header(p._1, p._2) +} +}) +var formData: MultivaluedMapImpl = null +if(contentType == "application/x-www-form-urlencoded") { +formData = new MultivaluedMapImpl() +formParams.map(p => formData.add(p._1, p._2)) +} - val response: ClientResponse = method match { - case "GET" => { - builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] - } - case "POST" => { - if(formData != null) builder.post(classOf[ClientResponse], formData) - else if(body != null && body.isInstanceOf[File]) { - val file = body.asInstanceOf[File] - val form = new FormDataMultiPart() - form.field("filename", file.getName()) - form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) - builder.post(classOf[ClientResponse], form) - } - else { - if(body == null) builder.post(classOf[ClientResponse], serialize(body)) - else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) - } - } - case "PUT" => { - if(formData != null) builder.post(classOf[ClientResponse], formData) - else if(body == null) builder.put(classOf[ClientResponse], null) - else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) - } - case "DELETE" => { - builder.delete(classOf[ClientResponse]) - } - case _ => null - } - response.getClientResponseStatus().getStatusCode() match { - case 204 => "" - case code: Int if (Range(200, 299).contains(code)) => { - response.hasEntity() match { - case true => response.getEntity(classOf[String]) - case false => "" - } - } - case _ => { - val entity = response.hasEntity() match { - case true => response.getEntity(classOf[String]) - case false => "no data" - } - throw new ApiException( - response.getClientResponseStatus().getStatusCode(), - entity) - } - } - } +val response: ClientResponse = method match { +case "GET" => { +builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] +} +case "POST" => { +if(formData != null) builder.post(classOf[ClientResponse], formData) +else if(body != null && body.isInstanceOf[File]) { +val file = body.asInstanceOf[File] +val form = new FormDataMultiPart() +form.field("filename", file.getName()) +form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) +builder.post(classOf[ClientResponse], form) +} +else { +if(body == null) builder.post(classOf[ClientResponse], serialize(body)) +else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) +} +} +case "PUT" => { +if(formData != null) builder.post(classOf[ClientResponse], formData) +else if(body == null) builder.put(classOf[ClientResponse], null) +else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) +} +case "DELETE" => { +builder.delete(classOf[ClientResponse]) +} +case _ => null +} +response.getClientResponseStatus().getStatusCode() match { +case 204 => "" +case code: Int if (Range(200, 299).contains(code)) => { +response.hasEntity() match { +case true => response.getEntity(classOf[String]) +case false => "" +} +} +case _ => { +val entity = response.hasEntity() match { +case true => response.getEntity(classOf[String]) +case false => "no data" +} +throw new ApiException( +response.getClientResponseStatus().getStatusCode(), +entity) +} +} +} - def getClient(host: String): Client = { - hostMap.contains(host) match { - case true => hostMap(host) - case false => { - val client = newClient(host) - // client.addFilter(new LoggingFilter()) - hostMap += host -> client - client - } - } - } - - def newClient(host: String): Client = asyncHttpClient match { - case true => { - import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig - import org.sonatype.spice.jersey.client.ahc.AhcHttpClient - import com.ning.http.client.Realm +def getClient(host: String): Client = { +hostMap.contains(host) match { +case true => hostMap(host) +case false => { +val client = newClient(host) +// client.addFilter(new LoggingFilter()) +hostMap += host -> client +client +} +} +} - val config: DefaultAhcConfig = new DefaultAhcConfig() - if (!authScheme.isEmpty) { - val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) - config.getAsyncHttpClientConfigBuilder - .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) - .setUsePreemptiveAuth(authPreemptive).build) - } - AhcHttpClient.create(config) - } - case _ => Client.create() - } +def newClient(host: String): Client = asyncHttpClient match { +case true => { +import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig +import org.sonatype.spice.jersey.client.ahc.AhcHttpClient +import com.ning.http.client.Realm + +val config: DefaultAhcConfig = new DefaultAhcConfig() +if (!authScheme.isEmpty) { +val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) +config.getAsyncHttpClientConfigBuilder +.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) +.setUsePreemptiveAuth(authPreemptive).build) +} +AhcHttpClient.create(config) +} +case _ => Client.create() +} } object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, - httpHeaders = HashMap(), - hostMap = HashMap(), - asyncHttpClient = {{asyncHttpClient}}, - authScheme = "{{authScheme}}", - authPreemptive = {{authPreemptive}}) +httpHeaders = HashMap(), +hostMap = HashMap(), +asyncHttpClient = {{asyncHttpClient}}, +authScheme = "{{authScheme}}", +authPreemptive = {{authPreemptive}}) class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/modules/swagger-codegen/src/main/resources/scala/model.mustache b/modules/swagger-codegen/src/main/resources/scala/model.mustache index a45b71a8f8e..cff9a993a84 100644 --- a/modules/swagger-codegen/src/main/resources/scala/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/model.mustache @@ -5,11 +5,11 @@ package {{package}} {{#models}} -{{#model}} + {{#model}} -case class {{classname}} ( - {{#vars}}{{#description}}/* {{{description}}} */ - {{/description}}{{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} - {{/vars}} -{{/model}} + case class {{classname}} ( + {{#vars}}{{#description}}/* {{{description}}} */ + {{/description}}{{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{/vars}} + {{/model}} {{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 2d8a1257eb4..417bf20feee 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -1,221 +1,224 @@ - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - - 2.2.0 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.2.0 + - - - maven-mongodb-plugin-repo - maven mongodb plugin repository - http://maven-mongodb-plugin.googlecode.com/svn/maven/repo - default - - + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - scala-compile-first - process-resources - - add-source - compile - - - - scala-test-compile - process-test-resources - - testCompile - - - - - - -Xms128m - -Xmx1500m - - - - - - - - - org.scala-tools - maven-scala-plugin - - ${scala-version} - - - - - - - com.fasterxml.jackson.module - jackson-module-scala_2.10 - ${jackson-version} - - - com.sun.jersey - jersey-client - ${jersey-version} - - - com.sun.jersey.contribs - jersey-multipart - ${jersey-version} - - - org.jfarcand - jersey-ahc-client - ${jersey-async-version} - compile - - - org.scala-lang - scala-library - ${scala-version} - - - io.swagger - swagger-core - ${swagger-core-version} - - - org.scalatest - scalatest_2.10 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - joda-time - joda-time - ${joda-time-version} - - - org.joda - joda-convert - ${joda-version} - - - - 2.10.4 - 1.2 - 2.2 - 1.7 - 1.5.0 - 1.0.5 - 1.0.0 - 2.4.2 + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + + 2.10.4 + 1.2 + 2.2 + 1.7 + 1.5.0 + 1.0.5 + 1.0.0 + 2.4.2 - 4.8.1 - 3.1.5 - 2.1.3 - + 4.8.1 + 3.1.5 + 2.1.3 + diff --git a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache index 5121079424f..08cc829bd80 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache @@ -5,16 +5,16 @@ import javax.servlet.ServletContext import org.scalatra.LifeCycle class ScalatraBootstrap extends LifeCycle { - implicit val swagger = new SwaggerApp +implicit val swagger = new SwaggerApp - override def init(context: ServletContext) { - implicit val system = ActorSystem("appActorSystem") - try { - {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") - {{/apis}}{{/apiInfo}} - context mount (new ResourcesApp, "/api-docs/*") - } catch { - case e: Throwable => e.printStackTrace() - } - } +override def init(context: ServletContext) { +implicit val system = ActorSystem("appActorSystem") +try { +{{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") +{{/apis}}{{/apiInfo}} +context mount (new ResourcesApp, "/api-docs/*") +} catch { +case e: Throwable => e.printStackTrace() +} +} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala b/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala index e25f16ba392..69ca43c0e1f 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala +++ b/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala @@ -1,17 +1,7 @@ -import org.eclipse.jetty.server._ -import org.eclipse.jetty.webapp.WebAppContext -import org.scalatra.servlet.ScalatraListener + object JettyMain { - object conf { - val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) - val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) - val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) - val webapp = sys.env.get("PUBLIC") getOrElse "webapp" - val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" - } - def main(args: Array[String]) = { val server: Server = new Server println("starting jetty") @@ -40,4 +30,12 @@ object JettyMain { server.start() } + + object conf { + val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) + val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) + val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) + val webapp = sys.env.get("PUBLIC") getOrElse "webapp" + val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" + } } diff --git a/modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala b/modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala index 691a82f563b..1502e1092be 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala +++ b/modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala @@ -1,7 +1,5 @@ package json -import com.fasterxml.jackson.module.scala.DefaultScalaModule -import com.fasterxml.jackson.core.JsonGenerator.Feature import com.fasterxml.jackson.databind._ object JsonUtil { diff --git a/modules/swagger-codegen/src/main/resources/scalatra/README.mustache b/modules/swagger-codegen/src/main/resources/scalatra/README.mustache index 3ffa01fb257..4a80e8480a7 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/README.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/README.mustache @@ -1,7 +1,7 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This is an example of building a swagger-enabled scalatra server. diff --git a/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache index 423b8644712..bae9c83a77f 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache @@ -8,32 +8,32 @@ import org.scalatra.ScalatraServlet import org.json4s.{DefaultFormats, Formats} class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) - extends ScalatraServlet with JacksonSwaggerBase { - before() { - response.headers += ("Access-Control-Allow-Origin" -> "*") - } +extends ScalatraServlet with JacksonSwaggerBase { +before() { +response.headers += ("Access-Control-Allow-Origin" -> "*") +} - protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { - val port = request.getServerPort - val h = request.getServerName - val prot = if (port == 443) "https" else "http" - val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h) - "%s://%s%s%s".format( - proto, - host, - request.getContextPath, - path) - } +protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { +val port = request.getServerPort +val h = request.getServerName +val prot = if (port == 443) "https" else "http" +val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h) +"%s://%s%s%s".format( +proto, +host, +request.getContextPath, +path) +} } class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0", swaggerVersion = "1.2") object ApiSwagger { - val apiInfo = ApiInfo( - """{{{appName}}}""", - """{{{appDescription}}}""", - """{{{infoUrl}}}""", - """{{{infoEmail}}}""", - """{{{licenseInfo}}}""", - """{{{licenseUrl}}}""") +val apiInfo = ApiInfo( +"""{{{appName}}}""", +"""{{{appDescription}}}""", +"""{{{infoUrl}}}""", +"""{{{infoEmail}}}""", +"""{{{licenseInfo}}}""", +"""{{{licenseUrl}}}""") } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache index 54710361fe9..bb559a6b1b3 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -14,26 +14,26 @@ import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintE import scala.collection.JavaConverters._ -class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats +class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet +with FileUploadSupport +with JacksonJsonSupport +with SwaggerSupport { +protected implicit val jsonFormats: Formats = DefaultFormats - protected val applicationDescription: String = "{{classname}}" - override protected val applicationName: Option[String] = Some("{{baseName}}") +protected val applicationDescription: String = "{{classname}}" +override protected val applicationName: Option[String] = Some("{{baseName}}") - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } +before() { +contentType = formats("json") +response.headers += ("Access-Control-Allow-Origin" -> "*") +} {{#operations}} -{{#operation}} - {{newline}} + {{#operation}} + {{newline}} - val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") - summary "{{{summary}}}" - parameters( + val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") + summary "{{{summary}}}" + parameters( {{#allParams}}{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} {{/isQueryParam}} {{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} @@ -46,49 +46,49 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet {{/isFormParam}} {{#hasMore}},{{/hasMore}} {{/allParams}}) - ) + ) - {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { - {{#allParams}} - {{#isFile}} - val {{paramName}} = fileParams("{{paramName}}") - {{/isFile}} - {{^isFile}} - {{#isPathParam}} - val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)) - {{/isPathParam}} + {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { + {{#allParams}} + {{#isFile}} + val {{paramName}} = fileParams("{{paramName}}") + {{/isFile}} + {{^isFile}} + {{#isPathParam}} + val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)) + {{/isPathParam}} - {{#isQueryParam}} - {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") - val {{paramName}} = if("{{collectionFormat}}".equals("default")) { - {{paramName}}String match { - case Some(str) => str.split(",") - case None => List() + {{#isQueryParam}} + {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") + val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + {{paramName}}String match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + {{/collectionFormat}} + {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} + + {{/isQueryParam}} + + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} + + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} + + {{#isBodyParam}} + val {{paramName}} = parsedBody.extract[{{dataType}}] + {{/isBodyParam}} + {{/isFile}} + println("{{paramName}}: " + {{paramName}}) + {{/allParams}} } - } - else - List() - {{/collectionFormat}} - {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} - - {{/isQueryParam}} - {{#isHeaderParam}} - val {{paramName}} = request.getHeader("{{paramName}}") - {{/isHeaderParam}} - - {{#isFormParam}} - val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") - {{/isFormParam}} - - {{#isBodyParam}} - val {{paramName}} = parsedBody.extract[{{dataType}}] - {{/isBodyParam}} - {{/isFile}} - println("{{paramName}}: " + {{paramName}}) - {{/allParams}} - } - -{{/operation}} + {{/operation}} {{/operations}} } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt index 00575312d85..23af47dada0 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt +++ b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt @@ -1,4 +1,6 @@ -import AssemblyKeys._ // put this at the top of the file + + +// put this at the top of the file import NativePackagerKeys._ @@ -10,7 +12,7 @@ scalariformSettings organization := "io.swagger" -seq(webSettings :_*) +seq(webSettings: _*) mainClass in assembly := Some("JettyMain") @@ -23,40 +25,40 @@ scalaVersion := "2.11.2" scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", + "org.scalatra" %% "scalatra" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", + "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", + "org.json4s" %% "json4s-jackson" % "3.2.10", + "org.json4s" %% "json4s-ext" % "3.2.10", + "commons-codec" % "commons-codec" % "1.7", + "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) + "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", + "com.typesafe.akka" %% "akka-actor" % "2.3.6", + "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) ) -resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" +resolvers += "Local Maven Repository" at "file://" + Path.userHome.absolutePath + "/.m2/repository" resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" ivyXML := - - - - + + + + mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => { - case "about.html" => MergeStrategy.discard + case "about.html" => MergeStrategy.discard case x => old(x) } } diff --git a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache index 8c5d1954662..f740d40bc07 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache @@ -5,11 +5,11 @@ package {{package}} {{#models}} -{{#model}} -case class {{classname}} ( - {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}] {{#description}} // {{description}}{{/description}} - {{/isNotRequired}}{{#hasMore}}, - {{/hasMore}}{{/vars}} -) -{{/model}} + {{#model}} + case class {{classname}} ( + {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}] {{#description}} // {{description}}{{/description}} + {{/isNotRequired}}{{#hasMore}}, + {{/hasMore}}{{/vars}} + ) + {{/model}} {{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/web.xml b/modules/swagger-codegen/src/main/resources/scalatra/web.xml index 2a08440458e..a6e529e4aec 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/web.xml +++ b/modules/swagger-codegen/src/main/resources/scalatra/web.xml @@ -1,17 +1,17 @@ - - - org.scalatra.servlet.ScalatraListener - + + + org.scalatra.servlet.ScalatraListener + - - default - /*.html - /css/* - /js/*.js - /images/* - + + default + /*.html + /css/* + /js/*.js + /images/* + diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap-responsive.css b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap-responsive.css index a3352d774ce..41580e0ea07 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap-responsive.css +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap-responsive.css @@ -9,1084 +9,1319 @@ */ @-ms-viewport { - width: device-width; + width: device-width; } .clearfix { - *zoom: 1; + *zoom: 1; } .clearfix:before, .clearfix:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .clearfix:after { - clear: both; + clear: both; } .hide-text { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; } .input-block-level { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } .hidden { - display: none; - visibility: hidden; + display: none; + visibility: hidden; } .visible-phone { - display: none !important; + display: none !important; } .visible-tablet { - display: none !important; + display: none !important; } .hidden-desktop { - display: none !important; + display: none !important; } .visible-desktop { - display: inherit !important; + display: inherit !important; } @media (min-width: 768px) and (max-width: 979px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important ; - } - .visible-tablet { - display: inherit !important; - } - .hidden-tablet { - display: none !important; - } + .hidden-desktop { + display: inherit !important; + } + + .visible-desktop { + display: none !important; + } + + .visible-tablet { + display: inherit !important; + } + + .hidden-tablet { + display: none !important; + } } @media (max-width: 767px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important; - } - .visible-phone { - display: inherit !important; - } - .hidden-phone { - display: none !important; - } + .hidden-desktop { + display: inherit !important; + } + + .visible-desktop { + display: none !important; + } + + .visible-phone { + display: inherit !important; + } + + .hidden-phone { + display: none !important; + } } @media (min-width: 1200px) { - .row { - margin-left: -30px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - line-height: 0; - content: ""; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 30px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 1170px; - } - .span12 { - width: 1170px; - } - .span11 { - width: 1070px; - } - .span10 { - width: 970px; - } - .span9 { - width: 870px; - } - .span8 { - width: 770px; - } - .span7 { - width: 670px; - } - .span6 { - width: 570px; - } - .span5 { - width: 470px; - } - .span4 { - width: 370px; - } - .span3 { - width: 270px; - } - .span2 { - width: 170px; - } - .span1 { - width: 70px; - } - .offset12 { - margin-left: 1230px; - } - .offset11 { - margin-left: 1130px; - } - .offset10 { - margin-left: 1030px; - } - .offset9 { - margin-left: 930px; - } - .offset8 { - margin-left: 830px; - } - .offset7 { - margin-left: 730px; - } - .offset6 { - margin-left: 630px; - } - .offset5 { - margin-left: 530px; - } - .offset4 { - margin-left: 430px; - } - .offset3 { - margin-left: 330px; - } - .offset2 { - margin-left: 230px; - } - .offset1 { - margin-left: 130px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - line-height: 0; - content: ""; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 30px; - margin-left: 2.564102564102564%; - *margin-left: 2.5109110747408616%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.564102564102564%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.45299145299145%; - *width: 91.39979996362975%; - } - .row-fluid .span10 { - width: 82.90598290598291%; - *width: 82.8527914166212%; - } - .row-fluid .span9 { - width: 74.35897435897436%; - *width: 74.30578286961266%; - } - .row-fluid .span8 { - width: 65.81196581196582%; - *width: 65.75877432260411%; - } - .row-fluid .span7 { - width: 57.26495726495726%; - *width: 57.21176577559556%; - } - .row-fluid .span6 { - width: 48.717948717948715%; - *width: 48.664757228587014%; - } - .row-fluid .span5 { - width: 40.17094017094017%; - *width: 40.11774868157847%; - } - .row-fluid .span4 { - width: 31.623931623931625%; - *width: 31.570740134569924%; - } - .row-fluid .span3 { - width: 23.076923076923077%; - *width: 23.023731587561375%; - } - .row-fluid .span2 { - width: 14.52991452991453%; - *width: 14.476723040552828%; - } - .row-fluid .span1 { - width: 5.982905982905983%; - *width: 5.929714493544281%; - } - .row-fluid .offset12 { - margin-left: 105.12820512820512%; - *margin-left: 105.02182214948171%; - } - .row-fluid .offset12:first-child { - margin-left: 102.56410256410257%; - *margin-left: 102.45771958537915%; - } - .row-fluid .offset11 { - margin-left: 96.58119658119658%; - *margin-left: 96.47481360247316%; - } - .row-fluid .offset11:first-child { - margin-left: 94.01709401709402%; - *margin-left: 93.91071103837061%; - } - .row-fluid .offset10 { - margin-left: 88.03418803418803%; - *margin-left: 87.92780505546462%; - } - .row-fluid .offset10:first-child { - margin-left: 85.47008547008548%; - *margin-left: 85.36370249136206%; - } - .row-fluid .offset9 { - margin-left: 79.48717948717949%; - *margin-left: 79.38079650845607%; - } - .row-fluid .offset9:first-child { - margin-left: 76.92307692307693%; - *margin-left: 76.81669394435352%; - } - .row-fluid .offset8 { - margin-left: 70.94017094017094%; - *margin-left: 70.83378796144753%; - } - .row-fluid .offset8:first-child { - margin-left: 68.37606837606839%; - *margin-left: 68.26968539734497%; - } - .row-fluid .offset7 { - margin-left: 62.393162393162385%; - *margin-left: 62.28677941443899%; - } - .row-fluid .offset7:first-child { - margin-left: 59.82905982905982%; - *margin-left: 59.72267685033642%; - } - .row-fluid .offset6 { - margin-left: 53.84615384615384%; - *margin-left: 53.739770867430444%; - } - .row-fluid .offset6:first-child { - margin-left: 51.28205128205128%; - *margin-left: 51.175668303327875%; - } - .row-fluid .offset5 { - margin-left: 45.299145299145295%; - *margin-left: 45.1927623204219%; - } - .row-fluid .offset5:first-child { - margin-left: 42.73504273504273%; - *margin-left: 42.62865975631933%; - } - .row-fluid .offset4 { - margin-left: 36.75213675213675%; - *margin-left: 36.645753773413354%; - } - .row-fluid .offset4:first-child { - margin-left: 34.18803418803419%; - *margin-left: 34.081651209310785%; - } - .row-fluid .offset3 { - margin-left: 28.205128205128204%; - *margin-left: 28.0987452264048%; - } - .row-fluid .offset3:first-child { - margin-left: 25.641025641025642%; - *margin-left: 25.53464266230224%; - } - .row-fluid .offset2 { - margin-left: 19.65811965811966%; - *margin-left: 19.551736679396257%; - } - .row-fluid .offset2:first-child { - margin-left: 17.094017094017094%; - *margin-left: 16.98763411529369%; - } - .row-fluid .offset1 { - margin-left: 11.11111111111111%; - *margin-left: 11.004728132387708%; - } - .row-fluid .offset1:first-child { - margin-left: 8.547008547008547%; - *margin-left: 8.440625568285142%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 30px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 1156px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 1056px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 956px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 856px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 756px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 656px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 556px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 456px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 356px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 256px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 156px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 56px; - } - .thumbnails { - margin-left: -30px; - } - .thumbnails > li { - margin-left: 30px; - } - .row-fluid .thumbnails { - margin-left: 0; - } + .row { + margin-left: -30px; + *zoom: 1; + } + + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + + .row:after { + clear: both; + } + + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 30px; + } + + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 1170px; + } + + .span12 { + width: 1170px; + } + + .span11 { + width: 1070px; + } + + .span10 { + width: 970px; + } + + .span9 { + width: 870px; + } + + .span8 { + width: 770px; + } + + .span7 { + width: 670px; + } + + .span6 { + width: 570px; + } + + .span5 { + width: 470px; + } + + .span4 { + width: 370px; + } + + .span3 { + width: 270px; + } + + .span2 { + width: 170px; + } + + .span1 { + width: 70px; + } + + .offset12 { + margin-left: 1230px; + } + + .offset11 { + margin-left: 1130px; + } + + .offset10 { + margin-left: 1030px; + } + + .offset9 { + margin-left: 930px; + } + + .offset8 { + margin-left: 830px; + } + + .offset7 { + margin-left: 730px; + } + + .offset6 { + margin-left: 630px; + } + + .offset5 { + margin-left: 530px; + } + + .offset4 { + margin-left: 430px; + } + + .offset3 { + margin-left: 330px; + } + + .offset2 { + margin-left: 230px; + } + + .offset1 { + margin-left: 130px; + } + + .row-fluid { + width: 100%; + *zoom: 1; + } + + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + + .row-fluid:after { + clear: both; + } + + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.564102564102564%; + *margin-left: 2.5109110747408616%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.564102564102564%; + } + + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + + .row-fluid .span11 { + width: 91.45299145299145%; + *width: 91.39979996362975%; + } + + .row-fluid .span10 { + width: 82.90598290598291%; + *width: 82.8527914166212%; + } + + .row-fluid .span9 { + width: 74.35897435897436%; + *width: 74.30578286961266%; + } + + .row-fluid .span8 { + width: 65.81196581196582%; + *width: 65.75877432260411%; + } + + .row-fluid .span7 { + width: 57.26495726495726%; + *width: 57.21176577559556%; + } + + .row-fluid .span6 { + width: 48.717948717948715%; + *width: 48.664757228587014%; + } + + .row-fluid .span5 { + width: 40.17094017094017%; + *width: 40.11774868157847%; + } + + .row-fluid .span4 { + width: 31.623931623931625%; + *width: 31.570740134569924%; + } + + .row-fluid .span3 { + width: 23.076923076923077%; + *width: 23.023731587561375%; + } + + .row-fluid .span2 { + width: 14.52991452991453%; + *width: 14.476723040552828%; + } + + .row-fluid .span1 { + width: 5.982905982905983%; + *width: 5.929714493544281%; + } + + .row-fluid .offset12 { + margin-left: 105.12820512820512%; + *margin-left: 105.02182214948171%; + } + + .row-fluid .offset12:first-child { + margin-left: 102.56410256410257%; + *margin-left: 102.45771958537915%; + } + + .row-fluid .offset11 { + margin-left: 96.58119658119658%; + *margin-left: 96.47481360247316%; + } + + .row-fluid .offset11:first-child { + margin-left: 94.01709401709402%; + *margin-left: 93.91071103837061%; + } + + .row-fluid .offset10 { + margin-left: 88.03418803418803%; + *margin-left: 87.92780505546462%; + } + + .row-fluid .offset10:first-child { + margin-left: 85.47008547008548%; + *margin-left: 85.36370249136206%; + } + + .row-fluid .offset9 { + margin-left: 79.48717948717949%; + *margin-left: 79.38079650845607%; + } + + .row-fluid .offset9:first-child { + margin-left: 76.92307692307693%; + *margin-left: 76.81669394435352%; + } + + .row-fluid .offset8 { + margin-left: 70.94017094017094%; + *margin-left: 70.83378796144753%; + } + + .row-fluid .offset8:first-child { + margin-left: 68.37606837606839%; + *margin-left: 68.26968539734497%; + } + + .row-fluid .offset7 { + margin-left: 62.393162393162385%; + *margin-left: 62.28677941443899%; + } + + .row-fluid .offset7:first-child { + margin-left: 59.82905982905982%; + *margin-left: 59.72267685033642%; + } + + .row-fluid .offset6 { + margin-left: 53.84615384615384%; + *margin-left: 53.739770867430444%; + } + + .row-fluid .offset6:first-child { + margin-left: 51.28205128205128%; + *margin-left: 51.175668303327875%; + } + + .row-fluid .offset5 { + margin-left: 45.299145299145295%; + *margin-left: 45.1927623204219%; + } + + .row-fluid .offset5:first-child { + margin-left: 42.73504273504273%; + *margin-left: 42.62865975631933%; + } + + .row-fluid .offset4 { + margin-left: 36.75213675213675%; + *margin-left: 36.645753773413354%; + } + + .row-fluid .offset4:first-child { + margin-left: 34.18803418803419%; + *margin-left: 34.081651209310785%; + } + + .row-fluid .offset3 { + margin-left: 28.205128205128204%; + *margin-left: 28.0987452264048%; + } + + .row-fluid .offset3:first-child { + margin-left: 25.641025641025642%; + *margin-left: 25.53464266230224%; + } + + .row-fluid .offset2 { + margin-left: 19.65811965811966%; + *margin-left: 19.551736679396257%; + } + + .row-fluid .offset2:first-child { + margin-left: 17.094017094017094%; + *margin-left: 16.98763411529369%; + } + + .row-fluid .offset1 { + margin-left: 11.11111111111111%; + *margin-left: 11.004728132387708%; + } + + .row-fluid .offset1:first-child { + margin-left: 8.547008547008547%; + *margin-left: 8.440625568285142%; + } + + input, + textarea, + .uneditable-input { + margin-left: 0; + } + + .controls-row [class*="span"] + [class*="span"] { + margin-left: 30px; + } + + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 1156px; + } + + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 1056px; + } + + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 956px; + } + + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 856px; + } + + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 756px; + } + + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 656px; + } + + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 556px; + } + + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 456px; + } + + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 356px; + } + + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 256px; + } + + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 156px; + } + + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 56px; + } + + .thumbnails { + margin-left: -30px; + } + + .thumbnails > li { + margin-left: 30px; + } + + .row-fluid .thumbnails { + margin-left: 0; + } } @media (min-width: 768px) and (max-width: 979px) { - .row { - margin-left: -20px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - line-height: 0; - content: ""; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 20px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 724px; - } - .span12 { - width: 724px; - } - .span11 { - width: 662px; - } - .span10 { - width: 600px; - } - .span9 { - width: 538px; - } - .span8 { - width: 476px; - } - .span7 { - width: 414px; - } - .span6 { - width: 352px; - } - .span5 { - width: 290px; - } - .span4 { - width: 228px; - } - .span3 { - width: 166px; - } - .span2 { - width: 104px; - } - .span1 { - width: 42px; - } - .offset12 { - margin-left: 764px; - } - .offset11 { - margin-left: 702px; - } - .offset10 { - margin-left: 640px; - } - .offset9 { - margin-left: 578px; - } - .offset8 { - margin-left: 516px; - } - .offset7 { - margin-left: 454px; - } - .offset6 { - margin-left: 392px; - } - .offset5 { - margin-left: 330px; - } - .offset4 { - margin-left: 268px; - } - .offset3 { - margin-left: 206px; - } - .offset2 { - margin-left: 144px; - } - .offset1 { - margin-left: 82px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - line-height: 0; - content: ""; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 30px; - margin-left: 2.7624309392265194%; - *margin-left: 2.709239449864817%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.7624309392265194%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.43646408839778%; - *width: 91.38327259903608%; - } - .row-fluid .span10 { - width: 82.87292817679558%; - *width: 82.81973668743387%; - } - .row-fluid .span9 { - width: 74.30939226519337%; - *width: 74.25620077583166%; - } - .row-fluid .span8 { - width: 65.74585635359117%; - *width: 65.69266486422946%; - } - .row-fluid .span7 { - width: 57.18232044198895%; - *width: 57.12912895262725%; - } - .row-fluid .span6 { - width: 48.61878453038674%; - *width: 48.56559304102504%; - } - .row-fluid .span5 { - width: 40.05524861878453%; - *width: 40.00205712942283%; - } - .row-fluid .span4 { - width: 31.491712707182323%; - *width: 31.43852121782062%; - } - .row-fluid .span3 { - width: 22.92817679558011%; - *width: 22.87498530621841%; - } - .row-fluid .span2 { - width: 14.3646408839779%; - *width: 14.311449394616199%; - } - .row-fluid .span1 { - width: 5.801104972375691%; - *width: 5.747913483013988%; - } - .row-fluid .offset12 { - margin-left: 105.52486187845304%; - *margin-left: 105.41847889972962%; - } - .row-fluid .offset12:first-child { - margin-left: 102.76243093922652%; - *margin-left: 102.6560479605031%; - } - .row-fluid .offset11 { - margin-left: 96.96132596685082%; - *margin-left: 96.8549429881274%; - } - .row-fluid .offset11:first-child { - margin-left: 94.1988950276243%; - *margin-left: 94.09251204890089%; - } - .row-fluid .offset10 { - margin-left: 88.39779005524862%; - *margin-left: 88.2914070765252%; - } - .row-fluid .offset10:first-child { - margin-left: 85.6353591160221%; - *margin-left: 85.52897613729868%; - } - .row-fluid .offset9 { - margin-left: 79.8342541436464%; - *margin-left: 79.72787116492299%; - } - .row-fluid .offset9:first-child { - margin-left: 77.07182320441989%; - *margin-left: 76.96544022569647%; - } - .row-fluid .offset8 { - margin-left: 71.2707182320442%; - *margin-left: 71.16433525332079%; - } - .row-fluid .offset8:first-child { - margin-left: 68.50828729281768%; - *margin-left: 68.40190431409427%; - } - .row-fluid .offset7 { - margin-left: 62.70718232044199%; - *margin-left: 62.600799341718584%; - } - .row-fluid .offset7:first-child { - margin-left: 59.94475138121547%; - *margin-left: 59.838368402492065%; - } - .row-fluid .offset6 { - margin-left: 54.14364640883978%; - *margin-left: 54.037263430116376%; - } - .row-fluid .offset6:first-child { - margin-left: 51.38121546961326%; - *margin-left: 51.27483249088986%; - } - .row-fluid .offset5 { - margin-left: 45.58011049723757%; - *margin-left: 45.47372751851417%; - } - .row-fluid .offset5:first-child { - margin-left: 42.81767955801105%; - *margin-left: 42.71129657928765%; - } - .row-fluid .offset4 { - margin-left: 37.01657458563536%; - *margin-left: 36.91019160691196%; - } - .row-fluid .offset4:first-child { - margin-left: 34.25414364640884%; - *margin-left: 34.14776066768544%; - } - .row-fluid .offset3 { - margin-left: 28.45303867403315%; - *margin-left: 28.346655695309746%; - } - .row-fluid .offset3:first-child { - margin-left: 25.69060773480663%; - *margin-left: 25.584224756083227%; - } - .row-fluid .offset2 { - margin-left: 19.88950276243094%; - *margin-left: 19.783119783707537%; - } - .row-fluid .offset2:first-child { - margin-left: 17.12707182320442%; - *margin-left: 17.02068884448102%; - } - .row-fluid .offset1 { - margin-left: 11.32596685082873%; - *margin-left: 11.219583872105325%; - } - .row-fluid .offset1:first-child { - margin-left: 8.56353591160221%; - *margin-left: 8.457152932878806%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 20px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 710px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 648px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 586px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 524px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 462px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 400px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 338px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 276px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 214px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 152px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 90px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 28px; - } + .row { + margin-left: -20px; + *zoom: 1; + } + + .row:before, + .row:after { + display: table; + line-height: 0; + content: ""; + } + + .row:after { + clear: both; + } + + [class*="span"] { + float: left; + min-height: 1px; + margin-left: 20px; + } + + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { + width: 724px; + } + + .span12 { + width: 724px; + } + + .span11 { + width: 662px; + } + + .span10 { + width: 600px; + } + + .span9 { + width: 538px; + } + + .span8 { + width: 476px; + } + + .span7 { + width: 414px; + } + + .span6 { + width: 352px; + } + + .span5 { + width: 290px; + } + + .span4 { + width: 228px; + } + + .span3 { + width: 166px; + } + + .span2 { + width: 104px; + } + + .span1 { + width: 42px; + } + + .offset12 { + margin-left: 764px; + } + + .offset11 { + margin-left: 702px; + } + + .offset10 { + margin-left: 640px; + } + + .offset9 { + margin-left: 578px; + } + + .offset8 { + margin-left: 516px; + } + + .offset7 { + margin-left: 454px; + } + + .offset6 { + margin-left: 392px; + } + + .offset5 { + margin-left: 330px; + } + + .offset4 { + margin-left: 268px; + } + + .offset3 { + margin-left: 206px; + } + + .offset2 { + margin-left: 144px; + } + + .offset1 { + margin-left: 82px; + } + + .row-fluid { + width: 100%; + *zoom: 1; + } + + .row-fluid:before, + .row-fluid:after { + display: table; + line-height: 0; + content: ""; + } + + .row-fluid:after { + clear: both; + } + + .row-fluid [class*="span"] { + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.7624309392265194%; + *margin-left: 2.709239449864817%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + .row-fluid [class*="span"]:first-child { + margin-left: 0; + } + + .row-fluid .controls-row [class*="span"] + [class*="span"] { + margin-left: 2.7624309392265194%; + } + + .row-fluid .span12 { + width: 100%; + *width: 99.94680851063829%; + } + + .row-fluid .span11 { + width: 91.43646408839778%; + *width: 91.38327259903608%; + } + + .row-fluid .span10 { + width: 82.87292817679558%; + *width: 82.81973668743387%; + } + + .row-fluid .span9 { + width: 74.30939226519337%; + *width: 74.25620077583166%; + } + + .row-fluid .span8 { + width: 65.74585635359117%; + *width: 65.69266486422946%; + } + + .row-fluid .span7 { + width: 57.18232044198895%; + *width: 57.12912895262725%; + } + + .row-fluid .span6 { + width: 48.61878453038674%; + *width: 48.56559304102504%; + } + + .row-fluid .span5 { + width: 40.05524861878453%; + *width: 40.00205712942283%; + } + + .row-fluid .span4 { + width: 31.491712707182323%; + *width: 31.43852121782062%; + } + + .row-fluid .span3 { + width: 22.92817679558011%; + *width: 22.87498530621841%; + } + + .row-fluid .span2 { + width: 14.3646408839779%; + *width: 14.311449394616199%; + } + + .row-fluid .span1 { + width: 5.801104972375691%; + *width: 5.747913483013988%; + } + + .row-fluid .offset12 { + margin-left: 105.52486187845304%; + *margin-left: 105.41847889972962%; + } + + .row-fluid .offset12:first-child { + margin-left: 102.76243093922652%; + *margin-left: 102.6560479605031%; + } + + .row-fluid .offset11 { + margin-left: 96.96132596685082%; + *margin-left: 96.8549429881274%; + } + + .row-fluid .offset11:first-child { + margin-left: 94.1988950276243%; + *margin-left: 94.09251204890089%; + } + + .row-fluid .offset10 { + margin-left: 88.39779005524862%; + *margin-left: 88.2914070765252%; + } + + .row-fluid .offset10:first-child { + margin-left: 85.6353591160221%; + *margin-left: 85.52897613729868%; + } + + .row-fluid .offset9 { + margin-left: 79.8342541436464%; + *margin-left: 79.72787116492299%; + } + + .row-fluid .offset9:first-child { + margin-left: 77.07182320441989%; + *margin-left: 76.96544022569647%; + } + + .row-fluid .offset8 { + margin-left: 71.2707182320442%; + *margin-left: 71.16433525332079%; + } + + .row-fluid .offset8:first-child { + margin-left: 68.50828729281768%; + *margin-left: 68.40190431409427%; + } + + .row-fluid .offset7 { + margin-left: 62.70718232044199%; + *margin-left: 62.600799341718584%; + } + + .row-fluid .offset7:first-child { + margin-left: 59.94475138121547%; + *margin-left: 59.838368402492065%; + } + + .row-fluid .offset6 { + margin-left: 54.14364640883978%; + *margin-left: 54.037263430116376%; + } + + .row-fluid .offset6:first-child { + margin-left: 51.38121546961326%; + *margin-left: 51.27483249088986%; + } + + .row-fluid .offset5 { + margin-left: 45.58011049723757%; + *margin-left: 45.47372751851417%; + } + + .row-fluid .offset5:first-child { + margin-left: 42.81767955801105%; + *margin-left: 42.71129657928765%; + } + + .row-fluid .offset4 { + margin-left: 37.01657458563536%; + *margin-left: 36.91019160691196%; + } + + .row-fluid .offset4:first-child { + margin-left: 34.25414364640884%; + *margin-left: 34.14776066768544%; + } + + .row-fluid .offset3 { + margin-left: 28.45303867403315%; + *margin-left: 28.346655695309746%; + } + + .row-fluid .offset3:first-child { + margin-left: 25.69060773480663%; + *margin-left: 25.584224756083227%; + } + + .row-fluid .offset2 { + margin-left: 19.88950276243094%; + *margin-left: 19.783119783707537%; + } + + .row-fluid .offset2:first-child { + margin-left: 17.12707182320442%; + *margin-left: 17.02068884448102%; + } + + .row-fluid .offset1 { + margin-left: 11.32596685082873%; + *margin-left: 11.219583872105325%; + } + + .row-fluid .offset1:first-child { + margin-left: 8.56353591160221%; + *margin-left: 8.457152932878806%; + } + + input, + textarea, + .uneditable-input { + margin-left: 0; + } + + .controls-row [class*="span"] + [class*="span"] { + margin-left: 20px; + } + + input.span12, + textarea.span12, + .uneditable-input.span12 { + width: 710px; + } + + input.span11, + textarea.span11, + .uneditable-input.span11 { + width: 648px; + } + + input.span10, + textarea.span10, + .uneditable-input.span10 { + width: 586px; + } + + input.span9, + textarea.span9, + .uneditable-input.span9 { + width: 524px; + } + + input.span8, + textarea.span8, + .uneditable-input.span8 { + width: 462px; + } + + input.span7, + textarea.span7, + .uneditable-input.span7 { + width: 400px; + } + + input.span6, + textarea.span6, + .uneditable-input.span6 { + width: 338px; + } + + input.span5, + textarea.span5, + .uneditable-input.span5 { + width: 276px; + } + + input.span4, + textarea.span4, + .uneditable-input.span4 { + width: 214px; + } + + input.span3, + textarea.span3, + .uneditable-input.span3 { + width: 152px; + } + + input.span2, + textarea.span2, + .uneditable-input.span2 { + width: 90px; + } + + input.span1, + textarea.span1, + .uneditable-input.span1 { + width: 28px; + } } @media (max-width: 767px) { - body { - padding-right: 20px; - padding-left: 20px; - } - .navbar-fixed-top, - .navbar-fixed-bottom, - .navbar-static-top { - margin-right: -20px; - margin-left: -20px; - } - .container-fluid { - padding: 0; - } - .dl-horizontal dt { - float: none; - width: auto; - clear: none; - text-align: left; - } - .dl-horizontal dd { - margin-left: 0; - } - .container { - width: auto; - } - .row-fluid { - width: 100%; - } - .row, - .thumbnails { - margin-left: 0; - } - .thumbnails > li { - float: none; - margin-left: 0; - } - [class*="span"], - .uneditable-input[class*="span"], - .row-fluid [class*="span"] { - display: block; - float: none; - width: 100%; - margin-left: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .span12, - .row-fluid .span12 { - width: 100%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="offset"]:first-child { - margin-left: 0; - } - .input-large, - .input-xlarge, - .input-xxlarge, - input[class*="span"], - select[class*="span"], - textarea[class*="span"], - .uneditable-input { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .input-prepend input, - .input-append input, - .input-prepend input[class*="span"], - .input-append input[class*="span"] { - display: inline-block; - width: auto; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 0; - } - .modal { - position: fixed; - top: 20px; - right: 20px; - left: 20px; - width: auto; - margin: 0; - } - .modal.fade { - top: -100px; - } - .modal.fade.in { - top: 20px; - } + body { + padding-right: 20px; + padding-left: 20px; + } + + .navbar-fixed-top, + .navbar-fixed-bottom, + .navbar-static-top { + margin-right: -20px; + margin-left: -20px; + } + + .container-fluid { + padding: 0; + } + + .dl-horizontal dt { + float: none; + width: auto; + clear: none; + text-align: left; + } + + .dl-horizontal dd { + margin-left: 0; + } + + .container { + width: auto; + } + + .row-fluid { + width: 100%; + } + + .row, + .thumbnails { + margin-left: 0; + } + + .thumbnails > li { + float: none; + margin-left: 0; + } + + [class*="span"], + .uneditable-input[class*="span"], + .row-fluid [class*="span"] { + display: block; + float: none; + width: 100%; + margin-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + .span12, + .row-fluid .span12 { + width: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + .row-fluid [class*="offset"]:first-child { + margin-left: 0; + } + + .input-large, + .input-xlarge, + .input-xxlarge, + input[class*="span"], + select[class*="span"], + textarea[class*="span"], + .uneditable-input { + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + } + + .input-prepend input, + .input-append input, + .input-prepend input[class*="span"], + .input-append input[class*="span"] { + display: inline-block; + width: auto; + } + + .controls-row [class*="span"] + [class*="span"] { + margin-left: 0; + } + + .modal { + position: fixed; + top: 20px; + right: 20px; + left: 20px; + width: auto; + margin: 0; + } + + .modal.fade { + top: -100px; + } + + .modal.fade.in { + top: 20px; + } } @media (max-width: 480px) { - .nav-collapse { - -webkit-transform: translate3d(0, 0, 0); - } - .page-header h1 small { - display: block; - line-height: 20px; - } - input[type="checkbox"], - input[type="radio"] { - border: 1px solid #ccc; - } - .form-horizontal .control-label { - float: none; - width: auto; - padding-top: 0; - text-align: left; - } - .form-horizontal .controls { - margin-left: 0; - } - .form-horizontal .control-list { - padding-top: 0; - } - .form-horizontal .form-actions { - padding-right: 10px; - padding-left: 10px; - } - .media .pull-left, - .media .pull-right { - display: block; - float: none; - margin-bottom: 10px; - } - .media-object { - margin-right: 0; - margin-left: 0; - } - .modal { - top: 10px; - right: 10px; - left: 10px; - } - .modal-header .close { - padding: 10px; - margin: -10px; - } - .carousel-caption { - position: static; - } + .nav-collapse { + -webkit-transform: translate3d(0, 0, 0); + } + + .page-header h1 small { + display: block; + line-height: 20px; + } + + input[type="checkbox"], + input[type="radio"] { + border: 1px solid #ccc; + } + + .form-horizontal .control-label { + float: none; + width: auto; + padding-top: 0; + text-align: left; + } + + .form-horizontal .controls { + margin-left: 0; + } + + .form-horizontal .control-list { + padding-top: 0; + } + + .form-horizontal .form-actions { + padding-right: 10px; + padding-left: 10px; + } + + .media .pull-left, + .media .pull-right { + display: block; + float: none; + margin-bottom: 10px; + } + + .media-object { + margin-right: 0; + margin-left: 0; + } + + .modal { + top: 10px; + right: 10px; + left: 10px; + } + + .modal-header .close { + padding: 10px; + margin: -10px; + } + + .carousel-caption { + position: static; + } } @media (max-width: 979px) { - body { - padding-top: 0; - } - .navbar-fixed-top, - .navbar-fixed-bottom { - position: static; - } - .navbar-fixed-top { - margin-bottom: 20px; - } - .navbar-fixed-bottom { - margin-top: 20px; - } - .navbar-fixed-top .navbar-inner, - .navbar-fixed-bottom .navbar-inner { - padding: 5px; - } - .navbar .container { - width: auto; - padding: 0; - } - .navbar .brand { - padding-right: 10px; - padding-left: 10px; - margin: 0 0 0 -5px; - } - .nav-collapse { - clear: both; - } - .nav-collapse .nav { - float: none; - margin: 0 0 10px; - } - .nav-collapse .nav > li { - float: none; - } - .nav-collapse .nav > li > a { - margin-bottom: 2px; - } - .nav-collapse .nav > .divider-vertical { - display: none; - } - .nav-collapse .nav .nav-header { - color: #777777; - text-shadow: none; - } - .nav-collapse .nav > li > a, - .nav-collapse .dropdown-menu a { - padding: 9px 15px; - font-weight: bold; - color: #777777; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - } - .nav-collapse .btn { - padding: 4px 10px 4px; - font-weight: normal; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - } - .nav-collapse .dropdown-menu li + li a { - margin-bottom: 2px; - } - .nav-collapse .nav > li > a:hover, - .nav-collapse .dropdown-menu a:hover { - background-color: #f2f2f2; - } - .navbar-inverse .nav-collapse .nav > li > a, - .navbar-inverse .nav-collapse .dropdown-menu a { - color: #999999; - } - .navbar-inverse .nav-collapse .nav > li > a:hover, - .navbar-inverse .nav-collapse .dropdown-menu a:hover { - background-color: #111111; - } - .nav-collapse.in .btn-group { - padding: 0; - margin-top: 5px; - } - .nav-collapse .dropdown-menu { - position: static; - top: auto; - left: auto; - display: none; - float: none; - max-width: none; - padding: 0; - margin: 0 15px; - background-color: transparent; - border: none; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - } - .nav-collapse .open > .dropdown-menu { - display: block; - } - .nav-collapse .dropdown-menu:before, - .nav-collapse .dropdown-menu:after { - display: none; - } - .nav-collapse .dropdown-menu .divider { - display: none; - } - .nav-collapse .nav > li > .dropdown-menu:before, - .nav-collapse .nav > li > .dropdown-menu:after { - display: none; - } - .nav-collapse .navbar-form, - .nav-collapse .navbar-search { - float: none; - padding: 10px 15px; - margin: 10px 0; - border-top: 1px solid #f2f2f2; - border-bottom: 1px solid #f2f2f2; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - } - .navbar-inverse .nav-collapse .navbar-form, - .navbar-inverse .nav-collapse .navbar-search { - border-top-color: #111111; - border-bottom-color: #111111; - } - .navbar .nav-collapse .nav.pull-right { - float: none; - margin-left: 0; - } - .nav-collapse, - .nav-collapse.collapse { - height: 0; - overflow: hidden; - } - .navbar .btn-navbar { - display: block; - } - .navbar-static .navbar-inner { - padding-right: 10px; - padding-left: 10px; - } + body { + padding-top: 0; + } + + .navbar-fixed-top, + .navbar-fixed-bottom { + position: static; + } + + .navbar-fixed-top { + margin-bottom: 20px; + } + + .navbar-fixed-bottom { + margin-top: 20px; + } + + .navbar-fixed-top .navbar-inner, + .navbar-fixed-bottom .navbar-inner { + padding: 5px; + } + + .navbar .container { + width: auto; + padding: 0; + } + + .navbar .brand { + padding-right: 10px; + padding-left: 10px; + margin: 0 0 0 -5px; + } + + .nav-collapse { + clear: both; + } + + .nav-collapse .nav { + float: none; + margin: 0 0 10px; + } + + .nav-collapse .nav > li { + float: none; + } + + .nav-collapse .nav > li > a { + margin-bottom: 2px; + } + + .nav-collapse .nav > .divider-vertical { + display: none; + } + + .nav-collapse .nav .nav-header { + color: #777777; + text-shadow: none; + } + + .nav-collapse .nav > li > a, + .nav-collapse .dropdown-menu a { + padding: 9px 15px; + font-weight: bold; + color: #777777; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; + } + + .nav-collapse .btn { + padding: 4px 10px 4px; + font-weight: normal; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + } + + .nav-collapse .dropdown-menu li + li a { + margin-bottom: 2px; + } + + .nav-collapse .nav > li > a:hover, + .nav-collapse .dropdown-menu a:hover { + background-color: #f2f2f2; + } + + .navbar-inverse .nav-collapse .nav > li > a, + .navbar-inverse .nav-collapse .dropdown-menu a { + color: #999999; + } + + .navbar-inverse .nav-collapse .nav > li > a:hover, + .navbar-inverse .nav-collapse .dropdown-menu a:hover { + background-color: #111111; + } + + .nav-collapse.in .btn-group { + padding: 0; + margin-top: 5px; + } + + .nav-collapse .dropdown-menu { + position: static; + top: auto; + left: auto; + display: none; + float: none; + max-width: none; + padding: 0; + margin: 0 15px; + background-color: transparent; + border: none; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + } + + .nav-collapse .open > .dropdown-menu { + display: block; + } + + .nav-collapse .dropdown-menu:before, + .nav-collapse .dropdown-menu:after { + display: none; + } + + .nav-collapse .dropdown-menu .divider { + display: none; + } + + .nav-collapse .nav > li > .dropdown-menu:before, + .nav-collapse .nav > li > .dropdown-menu:after { + display: none; + } + + .nav-collapse .navbar-form, + .nav-collapse .navbar-search { + float: none; + padding: 10px 15px; + margin: 10px 0; + border-top: 1px solid #f2f2f2; + border-bottom: 1px solid #f2f2f2; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); + } + + .navbar-inverse .nav-collapse .navbar-form, + .navbar-inverse .nav-collapse .navbar-search { + border-top-color: #111111; + border-bottom-color: #111111; + } + + .navbar .nav-collapse .nav.pull-right { + float: none; + margin-left: 0; + } + + .nav-collapse, + .nav-collapse.collapse { + height: 0; + overflow: hidden; + } + + .navbar .btn-navbar { + display: block; + } + + .navbar-static .navbar-inner { + padding-right: 10px; + padding-left: 10px; + } } @media (min-width: 980px) { - .nav-collapse.collapse { - height: auto !important; - overflow: visible !important; - } + .nav-collapse.collapse { + height: auto !important; + overflow: visible !important; + } } diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap.css b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap.css index db3b3bfd6a0..bbe32a8627b 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap.css +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/bootstrap.css @@ -18,95 +18,95 @@ header, hgroup, nav, section { - display: block; + display: block; } audio, canvas, video { - display: inline-block; - *display: inline; - *zoom: 1; + display: inline-block; + *display: inline; + *zoom: 1; } audio:not([controls]) { - display: none; + display: none; } html { - font-size: 100%; - -webkit-text-size-adjust: 100%; - -ms-text-size-adjust: 100%; + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; } a:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } a:hover, a:active { - outline: 0; + outline: 0; } sub, sup { - position: relative; - font-size: 75%; - line-height: 0; - vertical-align: baseline; + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; } sup { - top: -0.5em; + top: -0.5em; } sub { - bottom: -0.25em; + bottom: -0.25em; } img { - width: auto\9; - height: auto; - max-width: 100%; - vertical-align: middle; - border: 0; - -ms-interpolation-mode: bicubic; + width: auto \9; + height: auto; + max-width: 100%; + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; } #map_canvas img, .google-maps img { - max-width: none; + max-width: none; } button, input, select, textarea { - margin: 0; - font-size: 100%; - vertical-align: middle; + margin: 0; + font-size: 100%; + vertical-align: middle; } button, input { - *overflow: visible; - line-height: normal; + *overflow: visible; + line-height: normal; } button::-moz-focus-inner, input::-moz-focus-inner { - padding: 0; - border: 0; + padding: 0; + border: 0; } button, html input[type="button"], input[type="reset"], input[type="submit"] { - cursor: pointer; - -webkit-appearance: button; + cursor: pointer; + -webkit-appearance: button; } label, @@ -117,601 +117,612 @@ input[type="reset"], input[type="submit"], input[type="radio"], input[type="checkbox"] { - cursor: pointer; + cursor: pointer; } input[type="search"] { - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; - -webkit-appearance: textfield; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + -webkit-appearance: textfield; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { - -webkit-appearance: none; + -webkit-appearance: none; } textarea { - overflow: auto; - vertical-align: top; + overflow: auto; + vertical-align: top; } @media print { - * { - color: #000 !important; - text-shadow: none !important; - background: transparent !important; - box-shadow: none !important; - } - a, - a:visited { - text-decoration: underline; - } - a[href]:after { - content: " (" attr(href) ")"; - } - abbr[title]:after { - content: " (" attr(title) ")"; - } - .ir a:after, - a[href^="javascript:"]:after, - a[href^="#"]:after { - content: ""; - } - pre, - blockquote { - border: 1px solid #999; - page-break-inside: avoid; - } - thead { - display: table-header-group; - } - tr, - img { - page-break-inside: avoid; - } - img { - max-width: 100% !important; - } - @page { - margin: 0.5cm; - } - p, - h2, - h3 { - orphans: 3; - widows: 3; - } - h2, - h3 { - page-break-after: avoid; - } + * { + color: #000 !important; + text-shadow: none !important; + background: transparent !important; + box-shadow: none !important; + } + + a, + a:visited { + text-decoration: underline; + } + + a[href]:after { + content: " (" attr(href) ")"; + } + + abbr[title]:after { + content: " (" attr(title) ")"; + } + + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; + } + + pre, + blockquote { + border: 1px solid #999; + page-break-inside: avoid; + } + + thead { + display: table-header-group; + } + + tr, + img { + page-break-inside: avoid; + } + + img { + max-width: 100% !important; + } + + @page { + margin: 0.5cm; + } + + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + + h2, + h3 { + page-break-after: avoid; + } } .clearfix { - *zoom: 1; + *zoom: 1; } .clearfix:before, .clearfix:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .clearfix:after { - clear: both; + clear: both; } .hide-text { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; } .input-block-level { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + display: block; + width: 100%; + min-height: 30px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } body { - margin: 0; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 14px; - line-height: 20px; - color: #333333; - background-color: #ffffff; + margin: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 20px; + color: #333333; + background-color: #ffffff; } a { - color: #0088cc; - text-decoration: none; + color: #0088cc; + text-decoration: none; } a:hover { - color: #005580; - text-decoration: underline; + color: #005580; + text-decoration: underline; } .img-rounded { - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; } .img-polaroid { - padding: 4px; - background-color: #fff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + padding: 4px; + background-color: #fff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } .img-circle { - -webkit-border-radius: 500px; - -moz-border-radius: 500px; - border-radius: 500px; + -webkit-border-radius: 500px; + -moz-border-radius: 500px; + border-radius: 500px; } .row { - margin-left: -20px; - *zoom: 1; + margin-left: -20px; + *zoom: 1; } .row:before, .row:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .row:after { - clear: both; + clear: both; } [class*="span"] { - float: left; - min-height: 1px; - margin-left: 20px; + float: left; + min-height: 1px; + margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { - width: 940px; + width: 940px; } .span12 { - width: 940px; + width: 940px; } .span11 { - width: 860px; + width: 860px; } .span10 { - width: 780px; + width: 780px; } .span9 { - width: 700px; + width: 700px; } .span8 { - width: 620px; + width: 620px; } .span7 { - width: 540px; + width: 540px; } .span6 { - width: 460px; + width: 460px; } .span5 { - width: 380px; + width: 380px; } .span4 { - width: 300px; + width: 300px; } .span3 { - width: 220px; + width: 220px; } .span2 { - width: 140px; + width: 140px; } .span1 { - width: 60px; + width: 60px; } .offset12 { - margin-left: 980px; + margin-left: 980px; } .offset11 { - margin-left: 900px; + margin-left: 900px; } .offset10 { - margin-left: 820px; + margin-left: 820px; } .offset9 { - margin-left: 740px; + margin-left: 740px; } .offset8 { - margin-left: 660px; + margin-left: 660px; } .offset7 { - margin-left: 580px; + margin-left: 580px; } .offset6 { - margin-left: 500px; + margin-left: 500px; } .offset5 { - margin-left: 420px; + margin-left: 420px; } .offset4 { - margin-left: 340px; + margin-left: 340px; } .offset3 { - margin-left: 260px; + margin-left: 260px; } .offset2 { - margin-left: 180px; + margin-left: 180px; } .offset1 { - margin-left: 100px; + margin-left: 100px; } .row-fluid { - width: 100%; - *zoom: 1; + width: 100%; + *zoom: 1; } .row-fluid:before, .row-fluid:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .row-fluid:after { - clear: both; + clear: both; } .row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 30px; - margin-left: 2.127659574468085%; - *margin-left: 2.074468085106383%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + display: block; + float: left; + width: 100%; + min-height: 30px; + margin-left: 2.127659574468085%; + *margin-left: 2.074468085106383%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } .row-fluid [class*="span"]:first-child { - margin-left: 0; + margin-left: 0; } .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.127659574468085%; + margin-left: 2.127659574468085%; } .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; + width: 100%; + *width: 99.94680851063829%; } .row-fluid .span11 { - width: 91.48936170212765%; - *width: 91.43617021276594%; + width: 91.48936170212765%; + *width: 91.43617021276594%; } .row-fluid .span10 { - width: 82.97872340425532%; - *width: 82.92553191489361%; + width: 82.97872340425532%; + *width: 82.92553191489361%; } .row-fluid .span9 { - width: 74.46808510638297%; - *width: 74.41489361702126%; + width: 74.46808510638297%; + *width: 74.41489361702126%; } .row-fluid .span8 { - width: 65.95744680851064%; - *width: 65.90425531914893%; + width: 65.95744680851064%; + *width: 65.90425531914893%; } .row-fluid .span7 { - width: 57.44680851063829%; - *width: 57.39361702127659%; + width: 57.44680851063829%; + *width: 57.39361702127659%; } .row-fluid .span6 { - width: 48.93617021276595%; - *width: 48.88297872340425%; + width: 48.93617021276595%; + *width: 48.88297872340425%; } .row-fluid .span5 { - width: 40.42553191489362%; - *width: 40.37234042553192%; + width: 40.42553191489362%; + *width: 40.37234042553192%; } .row-fluid .span4 { - width: 31.914893617021278%; - *width: 31.861702127659576%; + width: 31.914893617021278%; + *width: 31.861702127659576%; } .row-fluid .span3 { - width: 23.404255319148934%; - *width: 23.351063829787233%; + width: 23.404255319148934%; + *width: 23.351063829787233%; } .row-fluid .span2 { - width: 14.893617021276595%; - *width: 14.840425531914894%; + width: 14.893617021276595%; + *width: 14.840425531914894%; } .row-fluid .span1 { - width: 6.382978723404255%; - *width: 6.329787234042553%; + width: 6.382978723404255%; + *width: 6.329787234042553%; } .row-fluid .offset12 { - margin-left: 104.25531914893617%; - *margin-left: 104.14893617021275%; + margin-left: 104.25531914893617%; + *margin-left: 104.14893617021275%; } .row-fluid .offset12:first-child { - margin-left: 102.12765957446808%; - *margin-left: 102.02127659574467%; + margin-left: 102.12765957446808%; + *margin-left: 102.02127659574467%; } .row-fluid .offset11 { - margin-left: 95.74468085106382%; - *margin-left: 95.6382978723404%; + margin-left: 95.74468085106382%; + *margin-left: 95.6382978723404%; } .row-fluid .offset11:first-child { - margin-left: 93.61702127659574%; - *margin-left: 93.51063829787232%; + margin-left: 93.61702127659574%; + *margin-left: 93.51063829787232%; } .row-fluid .offset10 { - margin-left: 87.23404255319149%; - *margin-left: 87.12765957446807%; + margin-left: 87.23404255319149%; + *margin-left: 87.12765957446807%; } .row-fluid .offset10:first-child { - margin-left: 85.1063829787234%; - *margin-left: 84.99999999999999%; + margin-left: 85.1063829787234%; + *margin-left: 84.99999999999999%; } .row-fluid .offset9 { - margin-left: 78.72340425531914%; - *margin-left: 78.61702127659572%; + margin-left: 78.72340425531914%; + *margin-left: 78.61702127659572%; } .row-fluid .offset9:first-child { - margin-left: 76.59574468085106%; - *margin-left: 76.48936170212764%; + margin-left: 76.59574468085106%; + *margin-left: 76.48936170212764%; } .row-fluid .offset8 { - margin-left: 70.2127659574468%; - *margin-left: 70.10638297872339%; + margin-left: 70.2127659574468%; + *margin-left: 70.10638297872339%; } .row-fluid .offset8:first-child { - margin-left: 68.08510638297872%; - *margin-left: 67.9787234042553%; + margin-left: 68.08510638297872%; + *margin-left: 67.9787234042553%; } .row-fluid .offset7 { - margin-left: 61.70212765957446%; - *margin-left: 61.59574468085106%; + margin-left: 61.70212765957446%; + *margin-left: 61.59574468085106%; } .row-fluid .offset7:first-child { - margin-left: 59.574468085106375%; - *margin-left: 59.46808510638297%; + margin-left: 59.574468085106375%; + *margin-left: 59.46808510638297%; } .row-fluid .offset6 { - margin-left: 53.191489361702125%; - *margin-left: 53.085106382978715%; + margin-left: 53.191489361702125%; + *margin-left: 53.085106382978715%; } .row-fluid .offset6:first-child { - margin-left: 51.063829787234035%; - *margin-left: 50.95744680851063%; + margin-left: 51.063829787234035%; + *margin-left: 50.95744680851063%; } .row-fluid .offset5 { - margin-left: 44.68085106382979%; - *margin-left: 44.57446808510638%; + margin-left: 44.68085106382979%; + *margin-left: 44.57446808510638%; } .row-fluid .offset5:first-child { - margin-left: 42.5531914893617%; - *margin-left: 42.4468085106383%; + margin-left: 42.5531914893617%; + *margin-left: 42.4468085106383%; } .row-fluid .offset4 { - margin-left: 36.170212765957444%; - *margin-left: 36.06382978723405%; + margin-left: 36.170212765957444%; + *margin-left: 36.06382978723405%; } .row-fluid .offset4:first-child { - margin-left: 34.04255319148936%; - *margin-left: 33.93617021276596%; + margin-left: 34.04255319148936%; + *margin-left: 33.93617021276596%; } .row-fluid .offset3 { - margin-left: 27.659574468085104%; - *margin-left: 27.5531914893617%; + margin-left: 27.659574468085104%; + *margin-left: 27.5531914893617%; } .row-fluid .offset3:first-child { - margin-left: 25.53191489361702%; - *margin-left: 25.425531914893618%; + margin-left: 25.53191489361702%; + *margin-left: 25.425531914893618%; } .row-fluid .offset2 { - margin-left: 19.148936170212764%; - *margin-left: 19.04255319148936%; + margin-left: 19.148936170212764%; + *margin-left: 19.04255319148936%; } .row-fluid .offset2:first-child { - margin-left: 17.02127659574468%; - *margin-left: 16.914893617021278%; + margin-left: 17.02127659574468%; + *margin-left: 16.914893617021278%; } .row-fluid .offset1 { - margin-left: 10.638297872340425%; - *margin-left: 10.53191489361702%; + margin-left: 10.638297872340425%; + *margin-left: 10.53191489361702%; } .row-fluid .offset1:first-child { - margin-left: 8.51063829787234%; - *margin-left: 8.404255319148938%; + margin-left: 8.51063829787234%; + *margin-left: 8.404255319148938%; } [class*="span"].hide, .row-fluid [class*="span"].hide { - display: none; + display: none; } [class*="span"].pull-right, .row-fluid [class*="span"].pull-right { - float: right; + float: right; } .container { - margin-right: auto; - margin-left: auto; - *zoom: 1; + margin-right: auto; + margin-left: auto; + *zoom: 1; } .container:before, .container:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .container:after { - clear: both; + clear: both; } .container-fluid { - padding-right: 20px; - padding-left: 20px; - *zoom: 1; + padding-right: 20px; + padding-left: 20px; + *zoom: 1; } .container-fluid:before, .container-fluid:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .container-fluid:after { - clear: both; + clear: both; } p { - margin: 0 0 10px; + margin: 0 0 10px; } .lead { - margin-bottom: 20px; - font-size: 21px; - font-weight: 200; - line-height: 30px; + margin-bottom: 20px; + font-size: 21px; + font-weight: 200; + line-height: 30px; } small { - font-size: 85%; + font-size: 85%; } strong { - font-weight: bold; + font-weight: bold; } em { - font-style: italic; + font-style: italic; } cite { - font-style: normal; + font-style: normal; } .muted { - color: #999999; + color: #999999; } a.muted:hover { - color: #808080; + color: #808080; } .text-warning { - color: #c09853; + color: #c09853; } a.text-warning:hover { - color: #a47e3c; + color: #a47e3c; } .text-error { - color: #b94a48; + color: #b94a48; } a.text-error:hover { - color: #953b39; + color: #953b39; } .text-info { - color: #3a87ad; + color: #3a87ad; } a.text-info:hover { - color: #2d6987; + color: #2d6987; } .text-success { - color: #468847; + color: #468847; } a.text-success:hover { - color: #356635; + color: #356635; } h1, @@ -720,12 +731,12 @@ h3, h4, h5, h6 { - margin: 10px 0; - font-family: inherit; - font-weight: bold; - line-height: 20px; - color: inherit; - text-rendering: optimizelegibility; + margin: 10px 0; + font-family: inherit; + font-weight: bold; + line-height: 20px; + color: inherit; + text-rendering: optimizelegibility; } h1 small, @@ -734,301 +745,301 @@ h3 small, h4 small, h5 small, h6 small { - font-weight: normal; - line-height: 1; - color: #999999; + font-weight: normal; + line-height: 1; + color: #999999; } h1, h2, h3 { - line-height: 40px; + line-height: 40px; } h1 { - font-size: 38.5px; + font-size: 38.5px; } h2 { - font-size: 31.5px; + font-size: 31.5px; } h3 { - font-size: 24.5px; + font-size: 24.5px; } h4 { - font-size: 17.5px; + font-size: 17.5px; } h5 { - font-size: 14px; + font-size: 14px; } h6 { - font-size: 11.9px; + font-size: 11.9px; } h1 small { - font-size: 24.5px; + font-size: 24.5px; } h2 small { - font-size: 17.5px; + font-size: 17.5px; } h3 small { - font-size: 14px; + font-size: 14px; } h4 small { - font-size: 14px; + font-size: 14px; } .page-header { - padding-bottom: 9px; - margin: 20px 0 30px; - border-bottom: 1px solid #eeeeee; + padding-bottom: 9px; + margin: 20px 0 30px; + border-bottom: 1px solid #eeeeee; } ul, ol { - padding: 0; - margin: 0 0 10px 25px; + padding: 0; + margin: 0 0 10px 25px; } ul ul, ul ol, ol ol, ol ul { - margin-bottom: 0; + margin-bottom: 0; } li { - line-height: 20px; + line-height: 20px; } ul.unstyled, ol.unstyled { - margin-left: 0; - list-style: none; + margin-left: 0; + list-style: none; } ul.inline, ol.inline { - margin-left: 0; - list-style: none; + margin-left: 0; + list-style: none; } ul.inline > li, ol.inline > li { - display: inline-block; - padding-right: 5px; - padding-left: 5px; + display: inline-block; + padding-right: 5px; + padding-left: 5px; } dl { - margin-bottom: 20px; + margin-bottom: 20px; } dt, dd { - line-height: 20px; + line-height: 20px; } dt { - font-weight: bold; + font-weight: bold; } dd { - margin-left: 10px; + margin-left: 10px; } .dl-horizontal { - *zoom: 1; + *zoom: 1; } .dl-horizontal:before, .dl-horizontal:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .dl-horizontal:after { - clear: both; + clear: both; } .dl-horizontal dt { - float: left; - width: 160px; - overflow: hidden; - clear: left; - text-align: right; - text-overflow: ellipsis; - white-space: nowrap; + float: left; + width: 160px; + overflow: hidden; + clear: left; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; } .dl-horizontal dd { - margin-left: 180px; + margin-left: 180px; } hr { - margin: 20px 0; - border: 0; - border-top: 1px solid #eeeeee; - border-bottom: 1px solid #ffffff; + margin: 20px 0; + border: 0; + border-top: 1px solid #eeeeee; + border-bottom: 1px solid #ffffff; } abbr[title], abbr[data-original-title] { - cursor: help; - border-bottom: 1px dotted #999999; + cursor: help; + border-bottom: 1px dotted #999999; } abbr.initialism { - font-size: 90%; - text-transform: uppercase; + font-size: 90%; + text-transform: uppercase; } blockquote { - padding: 0 0 0 15px; - margin: 0 0 20px; - border-left: 5px solid #eeeeee; + padding: 0 0 0 15px; + margin: 0 0 20px; + border-left: 5px solid #eeeeee; } blockquote p { - margin-bottom: 0; - font-size: 16px; - font-weight: 300; - line-height: 25px; + margin-bottom: 0; + font-size: 16px; + font-weight: 300; + line-height: 25px; } blockquote small { - display: block; - line-height: 20px; - color: #999999; + display: block; + line-height: 20px; + color: #999999; } blockquote small:before { - content: '\2014 \00A0'; + content: '\2014 \00A0'; } blockquote.pull-right { - float: right; - padding-right: 15px; - padding-left: 0; - border-right: 5px solid #eeeeee; - border-left: 0; + float: right; + padding-right: 15px; + padding-left: 0; + border-right: 5px solid #eeeeee; + border-left: 0; } blockquote.pull-right p, blockquote.pull-right small { - text-align: right; + text-align: right; } blockquote.pull-right small:before { - content: ''; + content: ''; } blockquote.pull-right small:after { - content: '\00A0 \2014'; + content: '\00A0 \2014'; } q:before, q:after, blockquote:before, blockquote:after { - content: ""; + content: ""; } address { - display: block; - margin-bottom: 20px; - font-style: normal; - line-height: 20px; + display: block; + margin-bottom: 20px; + font-style: normal; + line-height: 20px; } code, pre { - padding: 0 3px 2px; - font-family: Monaco, Menlo, Consolas, "Courier New", monospace; - font-size: 12px; - color: #333333; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; + padding: 0 3px 2px; + font-family: Monaco, Menlo, Consolas, "Courier New", monospace; + font-size: 12px; + color: #333333; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; } code { - padding: 2px 4px; - color: #d14; - white-space: nowrap; - background-color: #f7f7f9; - border: 1px solid #e1e1e8; + padding: 2px 4px; + color: #d14; + white-space: nowrap; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; } pre { - display: block; - padding: 9.5px; - margin: 0 0 10px; - font-size: 13px; - line-height: 20px; - word-break: break-all; - word-wrap: break-word; - white-space: pre; - white-space: pre-wrap; - background-color: #f5f5f5; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.15); - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + display: block; + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + line-height: 20px; + word-break: break-all; + word-wrap: break-word; + white-space: pre; + white-space: pre-wrap; + background-color: #f5f5f5; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.15); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } pre.prettyprint { - margin-bottom: 20px; + margin-bottom: 20px; } pre code { - padding: 0; - color: inherit; - white-space: pre; - white-space: pre-wrap; - background-color: transparent; - border: 0; + padding: 0; + color: inherit; + white-space: pre; + white-space: pre-wrap; + background-color: transparent; + border: 0; } .pre-scrollable { - max-height: 340px; - overflow-y: scroll; + max-height: 340px; + overflow-y: scroll; } form { - margin: 0 0 20px; + margin: 0 0 20px; } fieldset { - padding: 0; - margin: 0; - border: 0; + padding: 0; + margin: 0; + border: 0; } legend { - display: block; - width: 100%; - padding: 0; - margin-bottom: 20px; - font-size: 21px; - line-height: 40px; - color: #333333; - border: 0; - border-bottom: 1px solid #e5e5e5; + display: block; + width: 100%; + padding: 0; + margin-bottom: 20px; + font-size: 21px; + line-height: 40px; + color: #333333; + border: 0; + border-bottom: 1px solid #e5e5e5; } legend small { - font-size: 15px; - color: #999999; + font-size: 15px; + color: #999999; } label, @@ -1036,21 +1047,21 @@ input, button, select, textarea { - font-size: 14px; - font-weight: normal; - line-height: 20px; + font-size: 14px; + font-weight: normal; + line-height: 20px; } input, button, select, textarea { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } label { - display: block; - margin-bottom: 5px; + display: block; + margin-bottom: 5px; } select, @@ -1070,27 +1081,27 @@ input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { - display: inline-block; - height: 20px; - padding: 4px 6px; - margin-bottom: 10px; - font-size: 14px; - line-height: 20px; - color: #555555; - vertical-align: middle; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + display: inline-block; + height: 20px; + padding: 4px 6px; + margin-bottom: 10px; + font-size: 14px; + line-height: 20px; + color: #555555; + vertical-align: middle; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } input, textarea, .uneditable-input { - width: 206px; + width: 206px; } textarea { - height: auto; + height: auto; } textarea, @@ -1109,15 +1120,15 @@ input[type="search"], input[type="tel"], input[type="color"], .uneditable-input { - background-color: #ffffff; - border: 1px solid #cccccc; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; - -moz-transition: border linear 0.2s, box-shadow linear 0.2s; - -o-transition: border linear 0.2s, box-shadow linear 0.2s; - transition: border linear 0.2s, box-shadow linear 0.2s; + background-color: #ffffff; + border: 1px solid #cccccc; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; + -moz-transition: border linear 0.2s, box-shadow linear 0.2s; + -o-transition: border linear 0.2s, box-shadow linear 0.2s; + transition: border linear 0.2s, box-shadow linear 0.2s; } textarea:focus, @@ -1136,22 +1147,22 @@ input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-input:focus { - border-color: rgba(82, 168, 236, 0.8); - outline: 0; - outline: thin dotted \9; - /* IE6-9 */ + border-color: rgba(82, 168, 236, 0.8); + outline: 0; + outline: thin dotted \9; + /* IE6-9 */ - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); } input[type="radio"], input[type="checkbox"] { - margin: 4px 0 0; - margin-top: 1px \9; - *margin-top: 0; - line-height: normal; + margin: 4px 0 0; + margin-top: 1px \9; + *margin-top: 0; + line-height: normal; } input[type="file"], @@ -1161,128 +1172,128 @@ input[type="reset"], input[type="button"], input[type="radio"], input[type="checkbox"] { - width: auto; + width: auto; } select, input[type="file"] { - height: 30px; - /* In IE7, the height of the select element cannot be changed by height, only font-size */ + height: 30px; + /* In IE7, the height of the select element cannot be changed by height, only font-size */ - *margin-top: 4px; - /* For IE7, add top margin to align select with labels */ + *margin-top: 4px; + /* For IE7, add top margin to align select with labels */ - line-height: 30px; + line-height: 30px; } select { - width: 220px; - background-color: #ffffff; - border: 1px solid #cccccc; + width: 220px; + background-color: #ffffff; + border: 1px solid #cccccc; } select[multiple], select[size] { - height: auto; + height: auto; } select:focus, input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } .uneditable-input, .uneditable-textarea { - color: #999999; - cursor: not-allowed; - background-color: #fcfcfc; - border-color: #cccccc; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + color: #999999; + cursor: not-allowed; + background-color: #fcfcfc; + border-color: #cccccc; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); } .uneditable-input { - overflow: hidden; - white-space: nowrap; + overflow: hidden; + white-space: nowrap; } .uneditable-textarea { - width: auto; - height: auto; + width: auto; + height: auto; } input:-moz-placeholder, textarea:-moz-placeholder { - color: #999999; + color: #999999; } input:-ms-input-placeholder, textarea:-ms-input-placeholder { - color: #999999; + color: #999999; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { - color: #999999; + color: #999999; } .radio, .checkbox { - min-height: 20px; - padding-left: 20px; + min-height: 20px; + padding-left: 20px; } .radio input[type="radio"], .checkbox input[type="checkbox"] { - float: left; - margin-left: -20px; + float: left; + margin-left: -20px; } .controls > .radio:first-child, .controls > .checkbox:first-child { - padding-top: 5px; + padding-top: 5px; } .radio.inline, .checkbox.inline { - display: inline-block; - padding-top: 5px; - margin-bottom: 0; - vertical-align: middle; + display: inline-block; + padding-top: 5px; + margin-bottom: 0; + vertical-align: middle; } .radio.inline + .radio.inline, .checkbox.inline + .checkbox.inline { - margin-left: 10px; + margin-left: 10px; } .input-mini { - width: 60px; + width: 60px; } .input-small { - width: 90px; + width: 90px; } .input-medium { - width: 150px; + width: 150px; } .input-large { - width: 210px; + width: 210px; } .input-xlarge { - width: 270px; + width: 270px; } .input-xxlarge { - width: 530px; + width: 530px; } input[class*="span"], @@ -1293,8 +1304,8 @@ textarea[class*="span"], .row-fluid select[class*="span"], .row-fluid textarea[class*="span"], .row-fluid .uneditable-input[class*="span"] { - float: none; - margin-left: 0; + float: none; + margin-left: 0; } .input-append input[class*="span"], @@ -1307,114 +1318,114 @@ textarea[class*="span"], .row-fluid .uneditable-input[class*="span"], .row-fluid .input-prepend [class*="span"], .row-fluid .input-append [class*="span"] { - display: inline-block; + display: inline-block; } input, textarea, .uneditable-input { - margin-left: 0; + margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { - margin-left: 20px; + margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { - width: 926px; + width: 926px; } input.span11, textarea.span11, .uneditable-input.span11 { - width: 846px; + width: 846px; } input.span10, textarea.span10, .uneditable-input.span10 { - width: 766px; + width: 766px; } input.span9, textarea.span9, .uneditable-input.span9 { - width: 686px; + width: 686px; } input.span8, textarea.span8, .uneditable-input.span8 { - width: 606px; + width: 606px; } input.span7, textarea.span7, .uneditable-input.span7 { - width: 526px; + width: 526px; } input.span6, textarea.span6, .uneditable-input.span6 { - width: 446px; + width: 446px; } input.span5, textarea.span5, .uneditable-input.span5 { - width: 366px; + width: 366px; } input.span4, textarea.span4, .uneditable-input.span4 { - width: 286px; + width: 286px; } input.span3, textarea.span3, .uneditable-input.span3 { - width: 206px; + width: 206px; } input.span2, textarea.span2, .uneditable-input.span2 { - width: 126px; + width: 126px; } input.span1, textarea.span1, .uneditable-input.span1 { - width: 46px; + width: 46px; } .controls-row { - *zoom: 1; + *zoom: 1; } .controls-row:before, .controls-row:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .controls-row:after { - clear: both; + clear: both; } .controls-row [class*="span"], .row-fluid .controls-row [class*="span"] { - float: left; + float: left; } .controls-row .checkbox[class*="span"], .controls-row .radio[class*="span"] { - padding-top: 5px; + padding-top: 5px; } input[disabled], @@ -1423,21 +1434,21 @@ textarea[disabled], input[readonly], select[readonly], textarea[readonly] { - cursor: not-allowed; - background-color: #eeeeee; + cursor: not-allowed; + background-color: #eeeeee; } input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"][readonly], input[type="checkbox"][readonly] { - background-color: transparent; + background-color: transparent; } .control-group.warning .control-label, .control-group.warning .help-block, .control-group.warning .help-inline { - color: #c09853; + color: #c09853; } .control-group.warning .checkbox, @@ -1445,38 +1456,38 @@ input[type="checkbox"][readonly] { .control-group.warning input, .control-group.warning select, .control-group.warning textarea { - color: #c09853; + color: #c09853; } .control-group.warning input, .control-group.warning select, .control-group.warning textarea { - border-color: #c09853; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + border-color: #c09853; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.warning input:focus, .control-group.warning select:focus, .control-group.warning textarea:focus { - border-color: #a47e3c; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + border-color: #a47e3c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; } .control-group.warning .input-prepend .add-on, .control-group.warning .input-append .add-on { - color: #c09853; - background-color: #fcf8e3; - border-color: #c09853; + color: #c09853; + background-color: #fcf8e3; + border-color: #c09853; } .control-group.error .control-label, .control-group.error .help-block, .control-group.error .help-inline { - color: #b94a48; + color: #b94a48; } .control-group.error .checkbox, @@ -1484,38 +1495,38 @@ input[type="checkbox"][readonly] { .control-group.error input, .control-group.error select, .control-group.error textarea { - color: #b94a48; + color: #b94a48; } .control-group.error input, .control-group.error select, .control-group.error textarea { - border-color: #b94a48; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + border-color: #b94a48; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.error input:focus, .control-group.error select:focus, .control-group.error textarea:focus { - border-color: #953b39; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + border-color: #953b39; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; } .control-group.error .input-prepend .add-on, .control-group.error .input-append .add-on { - color: #b94a48; - background-color: #f2dede; - border-color: #b94a48; + color: #b94a48; + background-color: #f2dede; + border-color: #b94a48; } .control-group.success .control-label, .control-group.success .help-block, .control-group.success .help-inline { - color: #468847; + color: #468847; } .control-group.success .checkbox, @@ -1523,38 +1534,38 @@ input[type="checkbox"][readonly] { .control-group.success input, .control-group.success select, .control-group.success textarea { - color: #468847; + color: #468847; } .control-group.success input, .control-group.success select, .control-group.success textarea { - border-color: #468847; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + border-color: #468847; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.success input:focus, .control-group.success select:focus, .control-group.success textarea:focus { - border-color: #356635; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + border-color: #356635; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; } .control-group.success .input-prepend .add-on, .control-group.success .input-append .add-on { - color: #468847; - background-color: #dff0d8; - border-color: #468847; + color: #468847; + background-color: #dff0d8; + border-color: #468847; } .control-group.info .control-label, .control-group.info .help-block, .control-group.info .help-inline { - color: #3a87ad; + color: #3a87ad; } .control-group.info .checkbox, @@ -1562,93 +1573,93 @@ input[type="checkbox"][readonly] { .control-group.info input, .control-group.info select, .control-group.info textarea { - color: #3a87ad; + color: #3a87ad; } .control-group.info input, .control-group.info select, .control-group.info textarea { - border-color: #3a87ad; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + border-color: #3a87ad; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .control-group.info input:focus, .control-group.info select:focus, .control-group.info textarea:focus { - border-color: #2d6987; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + border-color: #2d6987; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; } .control-group.info .input-prepend .add-on, .control-group.info .input-append .add-on { - color: #3a87ad; - background-color: #d9edf7; - border-color: #3a87ad; + color: #3a87ad; + background-color: #d9edf7; + border-color: #3a87ad; } input:focus:invalid, textarea:focus:invalid, select:focus:invalid { - color: #b94a48; - border-color: #ee5f5b; + color: #b94a48; + border-color: #ee5f5b; } input:focus:invalid:focus, textarea:focus:invalid:focus, select:focus:invalid:focus { - border-color: #e9322d; - -webkit-box-shadow: 0 0 6px #f8b9b7; - -moz-box-shadow: 0 0 6px #f8b9b7; - box-shadow: 0 0 6px #f8b9b7; + border-color: #e9322d; + -webkit-box-shadow: 0 0 6px #f8b9b7; + -moz-box-shadow: 0 0 6px #f8b9b7; + box-shadow: 0 0 6px #f8b9b7; } .form-actions { - padding: 19px 20px 20px; - margin-top: 20px; - margin-bottom: 20px; - background-color: #f5f5f5; - border-top: 1px solid #e5e5e5; - *zoom: 1; + padding: 19px 20px 20px; + margin-top: 20px; + margin-bottom: 20px; + background-color: #f5f5f5; + border-top: 1px solid #e5e5e5; + *zoom: 1; } .form-actions:before, .form-actions:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .form-actions:after { - clear: both; + clear: both; } .help-block, .help-inline { - color: #595959; + color: #595959; } .help-block { - display: block; - margin-bottom: 10px; + display: block; + margin-bottom: 10px; } .help-inline { - display: inline-block; - *display: inline; - padding-left: 5px; - vertical-align: middle; - *zoom: 1; + display: inline-block; + *display: inline; + padding-left: 5px; + vertical-align: middle; + *zoom: 1; } .input-append, .input-prepend { - margin-bottom: 5px; - font-size: 0; - white-space: nowrap; + margin-bottom: 5px; + font-size: 0; + white-space: nowrap; } .input-append input, @@ -1659,7 +1670,7 @@ select:focus:invalid:focus { .input-prepend .uneditable-input, .input-append .dropdown-menu, .input-prepend .dropdown-menu { - font-size: 14px; + font-size: 14px; } .input-append input, @@ -1668,13 +1679,13 @@ select:focus:invalid:focus { .input-prepend select, .input-append .uneditable-input, .input-prepend .uneditable-input { - position: relative; - margin-bottom: 0; - *margin-left: 0; - vertical-align: top; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + position: relative; + margin-bottom: 0; + *margin-left: 0; + vertical-align: top; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .input-append input:focus, @@ -1683,23 +1694,23 @@ select:focus:invalid:focus { .input-prepend select:focus, .input-append .uneditable-input:focus, .input-prepend .uneditable-input:focus { - z-index: 2; + z-index: 2; } .input-append .add-on, .input-prepend .add-on { - display: inline-block; - width: auto; - height: 20px; - min-width: 16px; - padding: 4px 5px; - font-size: 14px; - font-weight: normal; - line-height: 20px; - text-align: center; - text-shadow: 0 1px 0 #ffffff; - background-color: #eeeeee; - border: 1px solid #ccc; + display: inline-block; + width: auto; + height: 20px; + min-width: 16px; + padding: 4px 5px; + font-size: 14px; + font-weight: normal; + line-height: 20px; + text-align: center; + text-shadow: 0 1px 0 #ffffff; + background-color: #eeeeee; + border: 1px solid #ccc; } .input-append .add-on, @@ -1708,140 +1719,140 @@ select:focus:invalid:focus { .input-prepend .btn, .input-append .btn-group > .dropdown-toggle, .input-prepend .btn-group > .dropdown-toggle { - vertical-align: top; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + vertical-align: top; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .input-append .active, .input-prepend .active { - background-color: #a9dba9; - border-color: #46a546; + background-color: #a9dba9; + border-color: #46a546; } .input-prepend .add-on, .input-prepend .btn { - margin-right: -1px; + margin-right: -1px; } .input-prepend .add-on:first-child, .input-prepend .btn:first-child { - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; } .input-append input, .input-append select, .input-append .uneditable-input { - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; } .input-append input + .btn-group .btn:last-child, .input-append select + .btn-group .btn:last-child, .input-append .uneditable-input + .btn-group .btn:last-child { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .input-append .add-on, .input-append .btn, .input-append .btn-group { - margin-left: -1px; + margin-left: -1px; } .input-append .add-on:last-child, .input-append .btn:last-child, .input-append .btn-group:last-child > .dropdown-toggle { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .input-prepend.input-append input, .input-prepend.input-append select, .input-prepend.input-append .uneditable-input { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .input-prepend.input-append input + .btn-group .btn, .input-prepend.input-append select + .btn-group .btn, .input-prepend.input-append .uneditable-input + .btn-group .btn { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .input-prepend.input-append .add-on:first-child, .input-prepend.input-append .btn:first-child { - margin-right: -1px; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; } .input-prepend.input-append .add-on:last-child, .input-prepend.input-append .btn:last-child { - margin-left: -1px; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .input-prepend.input-append .btn-group:first-child { - margin-left: 0; + margin-left: 0; } input.search-query { - padding-right: 14px; - padding-right: 4px \9; - padding-left: 14px; - padding-left: 4px \9; - /* IE7-8 doesn't have border-radius, so don't indent the padding */ + padding-right: 14px; + padding-right: 4px \9; + padding-left: 14px; + padding-left: 4px \9; + /* IE7-8 doesn't have border-radius, so don't indent the padding */ - margin-bottom: 0; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; + margin-bottom: 0; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; } /* Allow for input prepend/append in search forms */ .form-search .input-append .search-query, .form-search .input-prepend .search-query { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .form-search .input-append .search-query { - -webkit-border-radius: 14px 0 0 14px; - -moz-border-radius: 14px 0 0 14px; - border-radius: 14px 0 0 14px; + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; } .form-search .input-append .btn { - -webkit-border-radius: 0 14px 14px 0; - -moz-border-radius: 0 14px 14px 0; - border-radius: 0 14px 14px 0; + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; } .form-search .input-prepend .search-query { - -webkit-border-radius: 0 14px 14px 0; - -moz-border-radius: 0 14px 14px 0; - border-radius: 0 14px 14px 0; + -webkit-border-radius: 0 14px 14px 0; + -moz-border-radius: 0 14px 14px 0; + border-radius: 0 14px 14px 0; } .form-search .input-prepend .btn { - -webkit-border-radius: 14px 0 0 14px; - -moz-border-radius: 14px 0 0 14px; - border-radius: 14px 0 0 14px; + -webkit-border-radius: 14px 0 0 14px; + -moz-border-radius: 14px 0 0 14px; + border-radius: 14px 0 0 14px; } .form-search input, @@ -1865,96 +1876,96 @@ input.search-query { .form-search .input-append, .form-inline .input-append, .form-horizontal .input-append { - display: inline-block; - *display: inline; - margin-bottom: 0; - vertical-align: middle; - *zoom: 1; + display: inline-block; + *display: inline; + margin-bottom: 0; + vertical-align: middle; + *zoom: 1; } .form-search .hide, .form-inline .hide, .form-horizontal .hide { - display: none; + display: none; } .form-search label, .form-inline label, .form-search .btn-group, .form-inline .btn-group { - display: inline-block; + display: inline-block; } .form-search .input-append, .form-inline .input-append, .form-search .input-prepend, .form-inline .input-prepend { - margin-bottom: 0; + margin-bottom: 0; } .form-search .radio, .form-search .checkbox, .form-inline .radio, .form-inline .checkbox { - padding-left: 0; - margin-bottom: 0; - vertical-align: middle; + padding-left: 0; + margin-bottom: 0; + vertical-align: middle; } .form-search .radio input[type="radio"], .form-search .checkbox input[type="checkbox"], .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { - float: left; - margin-right: 3px; - margin-left: 0; + float: left; + margin-right: 3px; + margin-left: 0; } .control-group { - margin-bottom: 10px; + margin-bottom: 10px; } legend + .control-group { - margin-top: 20px; - -webkit-margin-top-collapse: separate; + margin-top: 20px; + -webkit-margin-top-collapse: separate; } .form-horizontal .control-group { - margin-bottom: 20px; - *zoom: 1; + margin-bottom: 20px; + *zoom: 1; } .form-horizontal .control-group:before, .form-horizontal .control-group:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .form-horizontal .control-group:after { - clear: both; + clear: both; } .form-horizontal .control-label { - float: left; - width: 160px; - padding-top: 5px; - text-align: right; + float: left; + width: 160px; + padding-top: 5px; + text-align: right; } .form-horizontal .controls { - *display: inline-block; - *padding-left: 20px; - margin-left: 180px; - *margin-left: 0; + *display: inline-block; + *padding-left: 20px; + margin-left: 180px; + *margin-left: 0; } .form-horizontal .controls:first-child { - *padding-left: 180px; + *padding-left: 180px; } .form-horizontal .help-block { - margin-bottom: 0; + margin-bottom: 0; } .form-horizontal input + .help-block, @@ -1963,44 +1974,44 @@ legend + .control-group { .form-horizontal .uneditable-input + .help-block, .form-horizontal .input-prepend + .help-block, .form-horizontal .input-append + .help-block { - margin-top: 10px; + margin-top: 10px; } .form-horizontal .form-actions { - padding-left: 180px; + padding-left: 180px; } table { - max-width: 100%; - background-color: transparent; - border-collapse: collapse; - border-spacing: 0; + max-width: 100%; + background-color: transparent; + border-collapse: collapse; + border-spacing: 0; } .table, table { - width: 100%; - margin-bottom: 20px; + width: 100%; + margin-bottom: 20px; } .table th, table th, .table td, table td { - padding: 8px; - line-height: 20px; - text-align: left; - vertical-align: top; - border-top: 1px solid #dddddd; + padding: 8px; + line-height: 20px; + text-align: left; + vertical-align: top; + border-top: 1px solid #dddddd; } .table th, table th { - font-weight: bold; + font-weight: bold; } .table thead th, table thead th { - vertical-align: bottom; + vertical-align: bottom; } .table caption + thead tr:first-child th, @@ -2015,37 +2026,37 @@ table colgroup + thead tr:first-child th, table colgroup + thead tr:first-child td, table thead:first-child tr:first-child th, table thead:first-child tr:first-child td { - border-top: 0; + border-top: 0; } .table tbody + tbody, table tbody + tbody { - border-top: 2px solid #dddddd; + border-top: 2px solid #dddddd; } .table .table, table table { - background-color: #ffffff; + background-color: #ffffff; } .table-condensed th, .table-condensed td { - padding: 4px 5px; + padding: 4px 5px; } .table-bordered { - border: 1px solid #dddddd; - border-collapse: separate; - *border-collapse: collapse; - border-left: 0; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + border: 1px solid #dddddd; + border-collapse: separate; + *border-collapse: collapse; + border-left: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .table-bordered th, .table-bordered td { - border-left: 1px solid #dddddd; + border-left: 1px solid #dddddd; } .table-bordered caption + thead tr:first-child th, @@ -2057,222 +2068,222 @@ table table { .table-bordered thead:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child th, .table-bordered tbody:first-child tr:first-child td { - border-top: 0; + border-top: 0; } .table-bordered thead:first-child tr:first-child > th:first-child, .table-bordered tbody:first-child tr:first-child > td:first-child { - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; } .table-bordered thead:first-child tr:first-child > th:last-child, .table-bordered tbody:first-child tr:first-child > td:last-child { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; } .table-bordered thead:last-child tr:last-child > th:first-child, .table-bordered tbody:last-child tr:last-child > td:first-child, .table-bordered tfoot:last-child tr:last-child > td:first-child { - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; } .table-bordered thead:last-child tr:last-child > th:last-child, .table-bordered tbody:last-child tr:last-child > td:last-child, .table-bordered tfoot:last-child tr:last-child > td:last-child { - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-bottomright: 4px; } .table-bordered tfoot + tbody:last-child tr:last-child td:first-child { - -webkit-border-bottom-left-radius: 0; - border-bottom-left-radius: 0; - -moz-border-radius-bottomleft: 0; + -webkit-border-bottom-left-radius: 0; + border-bottom-left-radius: 0; + -moz-border-radius-bottomleft: 0; } .table-bordered tfoot + tbody:last-child tr:last-child td:last-child { - -webkit-border-bottom-right-radius: 0; - border-bottom-right-radius: 0; - -moz-border-radius-bottomright: 0; + -webkit-border-bottom-right-radius: 0; + border-bottom-right-radius: 0; + -moz-border-radius-bottomright: 0; } .table-bordered caption + thead tr:first-child th:first-child, .table-bordered caption + tbody tr:first-child td:first-child, .table-bordered colgroup + thead tr:first-child th:first-child, .table-bordered colgroup + tbody tr:first-child td:first-child { - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topleft: 4px; } .table-bordered caption + thead tr:first-child th:last-child, .table-bordered caption + tbody tr:first-child td:last-child, .table-bordered colgroup + thead tr:first-child th:last-child, .table-bordered colgroup + tbody tr:first-child td:last-child { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -moz-border-radius-topright: 4px; } .table-striped tbody > tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > th, table tbody > tr:nth-child(odd) > td, table tbody > tr:nth-child(odd) > th { - background-color: #f9f9f9; + background-color: #f9f9f9; } .table-hover tbody tr:hover td, .table-hover tbody tr:hover th { - background-color: #f5f5f5; + background-color: #f5f5f5; } table td[class*="span"], table th[class*="span"], .row-fluid table td[class*="span"], .row-fluid table th[class*="span"] { - display: table-cell; - float: none; - margin-left: 0; + display: table-cell; + float: none; + margin-left: 0; } .table td.span1, .table th.span1 { - float: none; - width: 44px; - margin-left: 0; + float: none; + width: 44px; + margin-left: 0; } .table td.span2, .table th.span2 { - float: none; - width: 124px; - margin-left: 0; + float: none; + width: 124px; + margin-left: 0; } .table td.span3, .table th.span3 { - float: none; - width: 204px; - margin-left: 0; + float: none; + width: 204px; + margin-left: 0; } .table td.span4, .table th.span4 { - float: none; - width: 284px; - margin-left: 0; + float: none; + width: 284px; + margin-left: 0; } .table td.span5, .table th.span5 { - float: none; - width: 364px; - margin-left: 0; + float: none; + width: 364px; + margin-left: 0; } .table td.span6, .table th.span6 { - float: none; - width: 444px; - margin-left: 0; + float: none; + width: 444px; + margin-left: 0; } .table td.span7, .table th.span7 { - float: none; - width: 524px; - margin-left: 0; + float: none; + width: 524px; + margin-left: 0; } .table td.span8, .table th.span8 { - float: none; - width: 604px; - margin-left: 0; + float: none; + width: 604px; + margin-left: 0; } .table td.span9, .table th.span9 { - float: none; - width: 684px; - margin-left: 0; + float: none; + width: 684px; + margin-left: 0; } .table td.span10, .table th.span10 { - float: none; - width: 764px; - margin-left: 0; + float: none; + width: 764px; + margin-left: 0; } .table td.span11, .table th.span11 { - float: none; - width: 844px; - margin-left: 0; + float: none; + width: 844px; + margin-left: 0; } .table td.span12, .table th.span12 { - float: none; - width: 924px; - margin-left: 0; + float: none; + width: 924px; + margin-left: 0; } .table tbody tr.success td, table tbody tr.success td { - background-color: #dff0d8; + background-color: #dff0d8; } .table tbody tr.error td, table tbody tr.error td { - background-color: #f2dede; + background-color: #f2dede; } .table tbody tr.warning td, table tbody tr.warning td { - background-color: #fcf8e3; + background-color: #fcf8e3; } .table tbody tr.info td, table tbody tr.info td { - background-color: #d9edf7; + background-color: #d9edf7; } .table-hover tbody tr.success:hover td { - background-color: #d0e9c6; + background-color: #d0e9c6; } .table-hover tbody tr.error:hover td { - background-color: #ebcccc; + background-color: #ebcccc; } .table-hover tbody tr.warning:hover td { - background-color: #faf2cc; + background-color: #faf2cc; } .table-hover tbody tr.info:hover td { - background-color: #c4e3f3; + background-color: #c4e3f3; } [class^="icon-"], [class*=" icon-"] { - display: inline-block; - width: 14px; - height: 14px; - margin-top: 1px; - *margin-right: .3em; - line-height: 14px; - vertical-align: text-top; - background-image: url("../img/glyphicons-halflings.png"); - background-position: 14px 14px; - background-repeat: no-repeat; + display: inline-block; + width: 14px; + height: 14px; + margin-top: 1px; + *margin-right: .3em; + line-height: 14px; + vertical-align: text-top; + background-image: url("../img/glyphicons-halflings.png"); + background-position: 14px 14px; + background-repeat: no-repeat; } /* White icons with optional class, or on hover/active states of certain elements */ @@ -2290,915 +2301,915 @@ table tbody tr.info td { .dropdown-menu > .active > a > [class*=" icon-"], .dropdown-submenu:hover > a > [class^="icon-"], .dropdown-submenu:hover > a > [class*=" icon-"] { - background-image: url("../img/glyphicons-halflings-white.png"); + background-image: url("../img/glyphicons-halflings-white.png"); } .icon-glass { - background-position: 0 0; + background-position: 0 0; } .icon-music { - background-position: -24px 0; + background-position: -24px 0; } .icon-search { - background-position: -48px 0; + background-position: -48px 0; } .icon-envelope { - background-position: -72px 0; + background-position: -72px 0; } .icon-heart { - background-position: -96px 0; + background-position: -96px 0; } .icon-star { - background-position: -120px 0; + background-position: -120px 0; } .icon-star-empty { - background-position: -144px 0; + background-position: -144px 0; } .icon-user { - background-position: -168px 0; + background-position: -168px 0; } .icon-film { - background-position: -192px 0; + background-position: -192px 0; } .icon-th-large { - background-position: -216px 0; + background-position: -216px 0; } .icon-th { - background-position: -240px 0; + background-position: -240px 0; } .icon-th-list { - background-position: -264px 0; + background-position: -264px 0; } .icon-ok { - background-position: -288px 0; + background-position: -288px 0; } .icon-remove { - background-position: -312px 0; + background-position: -312px 0; } .icon-zoom-in { - background-position: -336px 0; + background-position: -336px 0; } .icon-zoom-out { - background-position: -360px 0; + background-position: -360px 0; } .icon-off { - background-position: -384px 0; + background-position: -384px 0; } .icon-signal { - background-position: -408px 0; + background-position: -408px 0; } .icon-cog { - background-position: -432px 0; + background-position: -432px 0; } .icon-trash { - background-position: -456px 0; + background-position: -456px 0; } .icon-home { - background-position: 0 -24px; + background-position: 0 -24px; } .icon-file { - background-position: -24px -24px; + background-position: -24px -24px; } .icon-time { - background-position: -48px -24px; + background-position: -48px -24px; } .icon-road { - background-position: -72px -24px; + background-position: -72px -24px; } .icon-download-alt { - background-position: -96px -24px; + background-position: -96px -24px; } .icon-download { - background-position: -120px -24px; + background-position: -120px -24px; } .icon-upload { - background-position: -144px -24px; + background-position: -144px -24px; } .icon-inbox { - background-position: -168px -24px; + background-position: -168px -24px; } .icon-play-circle { - background-position: -192px -24px; + background-position: -192px -24px; } .icon-repeat { - background-position: -216px -24px; + background-position: -216px -24px; } .icon-refresh { - background-position: -240px -24px; + background-position: -240px -24px; } .icon-list-alt { - background-position: -264px -24px; + background-position: -264px -24px; } .icon-lock { - background-position: -287px -24px; + background-position: -287px -24px; } .icon-flag { - background-position: -312px -24px; + background-position: -312px -24px; } .icon-headphones { - background-position: -336px -24px; + background-position: -336px -24px; } .icon-volume-off { - background-position: -360px -24px; + background-position: -360px -24px; } .icon-volume-down { - background-position: -384px -24px; + background-position: -384px -24px; } .icon-volume-up { - background-position: -408px -24px; + background-position: -408px -24px; } .icon-qrcode { - background-position: -432px -24px; + background-position: -432px -24px; } .icon-barcode { - background-position: -456px -24px; + background-position: -456px -24px; } .icon-tag { - background-position: 0 -48px; + background-position: 0 -48px; } .icon-tags { - background-position: -25px -48px; + background-position: -25px -48px; } .icon-book { - background-position: -48px -48px; + background-position: -48px -48px; } .icon-bookmark { - background-position: -72px -48px; + background-position: -72px -48px; } .icon-print { - background-position: -96px -48px; + background-position: -96px -48px; } .icon-camera { - background-position: -120px -48px; + background-position: -120px -48px; } .icon-font { - background-position: -144px -48px; + background-position: -144px -48px; } .icon-bold { - background-position: -167px -48px; + background-position: -167px -48px; } .icon-italic { - background-position: -192px -48px; + background-position: -192px -48px; } .icon-text-height { - background-position: -216px -48px; + background-position: -216px -48px; } .icon-text-width { - background-position: -240px -48px; + background-position: -240px -48px; } .icon-align-left { - background-position: -264px -48px; + background-position: -264px -48px; } .icon-align-center { - background-position: -288px -48px; + background-position: -288px -48px; } .icon-align-right { - background-position: -312px -48px; + background-position: -312px -48px; } .icon-align-justify { - background-position: -336px -48px; + background-position: -336px -48px; } .icon-list { - background-position: -360px -48px; + background-position: -360px -48px; } .icon-indent-left { - background-position: -384px -48px; + background-position: -384px -48px; } .icon-indent-right { - background-position: -408px -48px; + background-position: -408px -48px; } .icon-facetime-video { - background-position: -432px -48px; + background-position: -432px -48px; } .icon-picture { - background-position: -456px -48px; + background-position: -456px -48px; } .icon-pencil { - background-position: 0 -72px; + background-position: 0 -72px; } .icon-map-marker { - background-position: -24px -72px; + background-position: -24px -72px; } .icon-adjust { - background-position: -48px -72px; + background-position: -48px -72px; } .icon-tint { - background-position: -72px -72px; + background-position: -72px -72px; } .icon-edit { - background-position: -96px -72px; + background-position: -96px -72px; } .icon-share { - background-position: -120px -72px; + background-position: -120px -72px; } .icon-check { - background-position: -144px -72px; + background-position: -144px -72px; } .icon-move { - background-position: -168px -72px; + background-position: -168px -72px; } .icon-step-backward { - background-position: -192px -72px; + background-position: -192px -72px; } .icon-fast-backward { - background-position: -216px -72px; + background-position: -216px -72px; } .icon-backward { - background-position: -240px -72px; + background-position: -240px -72px; } .icon-play { - background-position: -264px -72px; + background-position: -264px -72px; } .icon-pause { - background-position: -288px -72px; + background-position: -288px -72px; } .icon-stop { - background-position: -312px -72px; + background-position: -312px -72px; } .icon-forward { - background-position: -336px -72px; + background-position: -336px -72px; } .icon-fast-forward { - background-position: -360px -72px; + background-position: -360px -72px; } .icon-step-forward { - background-position: -384px -72px; + background-position: -384px -72px; } .icon-eject { - background-position: -408px -72px; + background-position: -408px -72px; } .icon-chevron-left { - background-position: -432px -72px; + background-position: -432px -72px; } .icon-chevron-right { - background-position: -456px -72px; + background-position: -456px -72px; } .icon-plus-sign { - background-position: 0 -96px; + background-position: 0 -96px; } .icon-minus-sign { - background-position: -24px -96px; + background-position: -24px -96px; } .icon-remove-sign { - background-position: -48px -96px; + background-position: -48px -96px; } .icon-ok-sign { - background-position: -72px -96px; + background-position: -72px -96px; } .icon-question-sign { - background-position: -96px -96px; + background-position: -96px -96px; } .icon-info-sign { - background-position: -120px -96px; + background-position: -120px -96px; } .icon-screenshot { - background-position: -144px -96px; + background-position: -144px -96px; } .icon-remove-circle { - background-position: -168px -96px; + background-position: -168px -96px; } .icon-ok-circle { - background-position: -192px -96px; + background-position: -192px -96px; } .icon-ban-circle { - background-position: -216px -96px; + background-position: -216px -96px; } .icon-arrow-left { - background-position: -240px -96px; + background-position: -240px -96px; } .icon-arrow-right { - background-position: -264px -96px; + background-position: -264px -96px; } .icon-arrow-up { - background-position: -289px -96px; + background-position: -289px -96px; } .icon-arrow-down { - background-position: -312px -96px; + background-position: -312px -96px; } .icon-share-alt { - background-position: -336px -96px; + background-position: -336px -96px; } .icon-resize-full { - background-position: -360px -96px; + background-position: -360px -96px; } .icon-resize-small { - background-position: -384px -96px; + background-position: -384px -96px; } .icon-plus { - background-position: -408px -96px; + background-position: -408px -96px; } .icon-minus { - background-position: -433px -96px; + background-position: -433px -96px; } .icon-asterisk { - background-position: -456px -96px; + background-position: -456px -96px; } .icon-exclamation-sign { - background-position: 0 -120px; + background-position: 0 -120px; } .icon-gift { - background-position: -24px -120px; + background-position: -24px -120px; } .icon-leaf { - background-position: -48px -120px; + background-position: -48px -120px; } .icon-fire { - background-position: -72px -120px; + background-position: -72px -120px; } .icon-eye-open { - background-position: -96px -120px; + background-position: -96px -120px; } .icon-eye-close { - background-position: -120px -120px; + background-position: -120px -120px; } .icon-warning-sign { - background-position: -144px -120px; + background-position: -144px -120px; } .icon-plane { - background-position: -168px -120px; + background-position: -168px -120px; } .icon-calendar { - background-position: -192px -120px; + background-position: -192px -120px; } .icon-random { - width: 16px; - background-position: -216px -120px; + width: 16px; + background-position: -216px -120px; } .icon-comment { - background-position: -240px -120px; + background-position: -240px -120px; } .icon-magnet { - background-position: -264px -120px; + background-position: -264px -120px; } .icon-chevron-up { - background-position: -288px -120px; + background-position: -288px -120px; } .icon-chevron-down { - background-position: -313px -119px; + background-position: -313px -119px; } .icon-retweet { - background-position: -336px -120px; + background-position: -336px -120px; } .icon-shopping-cart { - background-position: -360px -120px; + background-position: -360px -120px; } .icon-folder-close { - background-position: -384px -120px; + background-position: -384px -120px; } .icon-folder-open { - width: 16px; - background-position: -408px -120px; + width: 16px; + background-position: -408px -120px; } .icon-resize-vertical { - background-position: -432px -119px; + background-position: -432px -119px; } .icon-resize-horizontal { - background-position: -456px -118px; + background-position: -456px -118px; } .icon-hdd { - background-position: 0 -144px; + background-position: 0 -144px; } .icon-bullhorn { - background-position: -24px -144px; + background-position: -24px -144px; } .icon-bell { - background-position: -48px -144px; + background-position: -48px -144px; } .icon-certificate { - background-position: -72px -144px; + background-position: -72px -144px; } .icon-thumbs-up { - background-position: -96px -144px; + background-position: -96px -144px; } .icon-thumbs-down { - background-position: -120px -144px; + background-position: -120px -144px; } .icon-hand-right { - background-position: -144px -144px; + background-position: -144px -144px; } .icon-hand-left { - background-position: -168px -144px; + background-position: -168px -144px; } .icon-hand-up { - background-position: -192px -144px; + background-position: -192px -144px; } .icon-hand-down { - background-position: -216px -144px; + background-position: -216px -144px; } .icon-circle-arrow-right { - background-position: -240px -144px; + background-position: -240px -144px; } .icon-circle-arrow-left { - background-position: -264px -144px; + background-position: -264px -144px; } .icon-circle-arrow-up { - background-position: -288px -144px; + background-position: -288px -144px; } .icon-circle-arrow-down { - background-position: -312px -144px; + background-position: -312px -144px; } .icon-globe { - background-position: -336px -144px; + background-position: -336px -144px; } .icon-wrench { - background-position: -360px -144px; + background-position: -360px -144px; } .icon-tasks { - background-position: -384px -144px; + background-position: -384px -144px; } .icon-filter { - background-position: -408px -144px; + background-position: -408px -144px; } .icon-briefcase { - background-position: -432px -144px; + background-position: -432px -144px; } .icon-fullscreen { - background-position: -456px -144px; + background-position: -456px -144px; } .dropup, .dropdown { - position: relative; + position: relative; } .dropdown-toggle { - *margin-bottom: -3px; + *margin-bottom: -3px; } .dropdown-toggle:active, .open .dropdown-toggle { - outline: 0; + outline: 0; } .caret { - display: inline-block; - width: 0; - height: 0; - vertical-align: top; - border-top: 4px solid #000000; - border-right: 4px solid transparent; - border-left: 4px solid transparent; - content: ""; + display: inline-block; + width: 0; + height: 0; + vertical-align: top; + border-top: 4px solid #000000; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; } .dropdown .caret { - margin-top: 8px; - margin-left: 2px; + margin-top: 8px; + margin-left: 2px; } .dropdown-menu { - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 5px 0; - margin: 2px 0 0; - list-style: none; - background-color: #ffffff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - *border-right-width: 2px; - *border-bottom-width: 2px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -webkit-background-clip: padding-box; - -moz-background-clip: padding; - background-clip: padding-box; + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + list-style: none; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + *border-right-width: 2px; + *border-bottom-width: 2px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; } .dropdown-menu.pull-right { - right: 0; - left: auto; + right: 0; + left: auto; } .dropdown-menu .divider { - *width: 100%; - height: 1px; - margin: 9px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; } .dropdown-menu li > a { - display: block; - padding: 3px 20px; - clear: both; - font-weight: normal; - line-height: 20px; - color: #333333; - white-space: nowrap; + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 20px; + color: #333333; + white-space: nowrap; } .dropdown-menu li > a:hover, .dropdown-menu li > a:focus, .dropdown-submenu:hover > a { - color: #ffffff; - text-decoration: none; - background-color: #0081c2; - background-image: -moz-linear-gradient(top, #0088cc, #0077b3); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); - background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); - background-image: -o-linear-gradient(top, #0088cc, #0077b3); - background-image: linear-gradient(to bottom, #0088cc, #0077b3); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); + color: #ffffff; + text-decoration: none; + background-color: #0081c2; + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); } .dropdown-menu .active > a, .dropdown-menu .active > a:hover { - color: #ffffff; - text-decoration: none; - background-color: #0081c2; - background-image: -moz-linear-gradient(top, #0088cc, #0077b3); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); - background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); - background-image: -o-linear-gradient(top, #0088cc, #0077b3); - background-image: linear-gradient(to bottom, #0088cc, #0077b3); - background-repeat: repeat-x; - outline: 0; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); + color: #ffffff; + text-decoration: none; + background-color: #0081c2; + background-image: -moz-linear-gradient(top, #0088cc, #0077b3); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); + background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); + background-image: -o-linear-gradient(top, #0088cc, #0077b3); + background-image: linear-gradient(to bottom, #0088cc, #0077b3); + background-repeat: repeat-x; + outline: 0; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); } .dropdown-menu .disabled > a, .dropdown-menu .disabled > a:hover { - color: #999999; + color: #999999; } .dropdown-menu .disabled > a:hover { - text-decoration: none; - cursor: default; - background-color: transparent; - background-image: none; - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + text-decoration: none; + cursor: default; + background-color: transparent; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .open { - *z-index: 1000; + *z-index: 1000; } .open > .dropdown-menu { - display: block; + display: block; } .pull-right > .dropdown-menu { - right: 0; - left: auto; + right: 0; + left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { - border-top: 0; - border-bottom: 4px solid #000000; - content: ""; + border-top: 0; + border-bottom: 4px solid #000000; + content: ""; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { - top: auto; - bottom: 100%; - margin-bottom: 1px; + top: auto; + bottom: 100%; + margin-bottom: 1px; } .dropdown-submenu { - position: relative; + position: relative; } .dropdown-submenu > .dropdown-menu { - top: 0; - left: 100%; - margin-top: -6px; - margin-left: -1px; - -webkit-border-radius: 0 6px 6px 6px; - -moz-border-radius: 0 6px 6px 6px; - border-radius: 0 6px 6px 6px; + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + -webkit-border-radius: 0 6px 6px 6px; + -moz-border-radius: 0 6px 6px 6px; + border-radius: 0 6px 6px 6px; } .dropdown-submenu:hover > .dropdown-menu { - display: block; + display: block; } .dropup .dropdown-submenu > .dropdown-menu { - top: auto; - bottom: 0; - margin-top: 0; - margin-bottom: -2px; - -webkit-border-radius: 5px 5px 5px 0; - -moz-border-radius: 5px 5px 5px 0; - border-radius: 5px 5px 5px 0; + top: auto; + bottom: 0; + margin-top: 0; + margin-bottom: -2px; + -webkit-border-radius: 5px 5px 5px 0; + -moz-border-radius: 5px 5px 5px 0; + border-radius: 5px 5px 5px 0; } .dropdown-submenu > a:after { - display: block; - float: right; - width: 0; - height: 0; - margin-top: 5px; - margin-right: -10px; - border-color: transparent; - border-left-color: #cccccc; - border-style: solid; - border-width: 5px 0 5px 5px; - content: " "; + display: block; + float: right; + width: 0; + height: 0; + margin-top: 5px; + margin-right: -10px; + border-color: transparent; + border-left-color: #cccccc; + border-style: solid; + border-width: 5px 0 5px 5px; + content: " "; } .dropdown-submenu:hover > a:after { - border-left-color: #ffffff; + border-left-color: #ffffff; } .dropdown-submenu.pull-left { - float: none; + float: none; } .dropdown-submenu.pull-left > .dropdown-menu { - left: -100%; - margin-left: 10px; - -webkit-border-radius: 6px 0 6px 6px; - -moz-border-radius: 6px 0 6px 6px; - border-radius: 6px 0 6px 6px; + left: -100%; + margin-left: 10px; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; } .dropdown .dropdown-menu .nav-header { - padding-right: 20px; - padding-left: 20px; + padding-right: 20px; + padding-left: 20px; } .typeahead { - z-index: 1051; - margin-top: 2px; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + z-index: 1051; + margin-top: 2px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #e3e3e3; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #e3e3e3; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); } .well blockquote { - border-color: #ddd; - border-color: rgba(0, 0, 0, 0.15); + border-color: #ddd; + border-color: rgba(0, 0, 0, 0.15); } .well-large { - padding: 24px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; + padding: 24px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; } .well-small { - padding: 9px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; + padding: 9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; } .fade { - opacity: 0; - -webkit-transition: opacity 0.15s linear; - -moz-transition: opacity 0.15s linear; - -o-transition: opacity 0.15s linear; - transition: opacity 0.15s linear; + opacity: 0; + -webkit-transition: opacity 0.15s linear; + -moz-transition: opacity 0.15s linear; + -o-transition: opacity 0.15s linear; + transition: opacity 0.15s linear; } .fade.in { - opacity: 1; + opacity: 1; } .collapse { - position: relative; - height: 0; - overflow: hidden; - -webkit-transition: height 0.35s ease; - -moz-transition: height 0.35s ease; - -o-transition: height 0.35s ease; - transition: height 0.35s ease; + position: relative; + height: 0; + overflow: hidden; + -webkit-transition: height 0.35s ease; + -moz-transition: height 0.35s ease; + -o-transition: height 0.35s ease; + transition: height 0.35s ease; } .collapse.in { - height: auto; + height: auto; } .close { - float: right; - font-size: 20px; - font-weight: bold; - line-height: 20px; - color: #000000; - text-shadow: 0 1px 0 #ffffff; - opacity: 0.2; - filter: alpha(opacity=20); + float: right; + font-size: 20px; + font-weight: bold; + line-height: 20px; + color: #000000; + text-shadow: 0 1px 0 #ffffff; + opacity: 0.2; + filter: alpha(opacity=20); } .close:hover { - color: #000000; - text-decoration: none; - cursor: pointer; - opacity: 0.4; - filter: alpha(opacity=40); + color: #000000; + text-decoration: none; + cursor: pointer; + opacity: 0.4; + filter: alpha(opacity=40); } button.close { - padding: 0; - cursor: pointer; - background: transparent; - border: 0; - -webkit-appearance: none; + padding: 0; + cursor: pointer; + background: transparent; + border: 0; + -webkit-appearance: none; } .btn { - display: inline-block; - *display: inline; - padding: 4px 12px; - margin-bottom: 0; - *margin-left: .3em; - font-size: 14px; - line-height: 20px; - color: #333333; - text-align: center; - text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); - vertical-align: middle; - cursor: pointer; - background-color: #f5f5f5; - *background-color: #e6e6e6; - background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); - background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); - background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); - background-repeat: repeat-x; - border: 1px solid #bbbbbb; - *border: 0; - border-color: #e6e6e6 #e6e6e6 #bfbfbf; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - border-bottom-color: #a2a2a2; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); - *zoom: 1; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + display: inline-block; + *display: inline; + padding: 4px 12px; + margin-bottom: 0; + *margin-left: .3em; + font-size: 14px; + line-height: 20px; + color: #333333; + text-align: center; + text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); + vertical-align: middle; + cursor: pointer; + background-color: #f5f5f5; + *background-color: #e6e6e6; + background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); + background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); + background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); + background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); + background-repeat: repeat-x; + border: 1px solid #bbbbbb; + *border: 0; + border-color: #e6e6e6 #e6e6e6 #bfbfbf; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + border-bottom-color: #a2a2a2; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); } .btn:hover, @@ -3206,113 +3217,113 @@ button.close { .btn.active, .btn.disabled, .btn[disabled] { - color: #333333; - background-color: #e6e6e6; - *background-color: #d9d9d9; + color: #333333; + background-color: #e6e6e6; + *background-color: #d9d9d9; } .btn:active, .btn.active { - background-color: #cccccc \9; + background-color: #cccccc \9; } .btn:first-child { - *margin-left: 0; + *margin-left: 0; } .btn:hover { - color: #333333; - text-decoration: none; - background-position: 0 -15px; - -webkit-transition: background-position 0.1s linear; - -moz-transition: background-position 0.1s linear; - -o-transition: background-position 0.1s linear; - transition: background-position 0.1s linear; + color: #333333; + text-decoration: none; + background-position: 0 -15px; + -webkit-transition: background-position 0.1s linear; + -moz-transition: background-position 0.1s linear; + -o-transition: background-position 0.1s linear; + transition: background-position 0.1s linear; } .btn:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; + outline: thin dotted #333; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; } .btn.active, .btn:active { - background-image: none; - outline: 0; - -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); } .btn.disabled, .btn[disabled] { - cursor: default; - background-image: none; - opacity: 0.65; - filter: alpha(opacity=65); - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; + cursor: default; + background-image: none; + opacity: 0.65; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; } .btn-large { - padding: 11px 19px; - font-size: 17.5px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; + padding: 11px 19px; + font-size: 17.5px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; } .btn-large [class^="icon-"], .btn-large [class*=" icon-"] { - margin-top: 4px; + margin-top: 4px; } .btn-small { - padding: 2px 10px; - font-size: 11.9px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; + padding: 2px 10px; + font-size: 11.9px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; } .btn-small [class^="icon-"], .btn-small [class*=" icon-"] { - margin-top: 0; + margin-top: 0; } .btn-mini [class^="icon-"], .btn-mini [class*=" icon-"] { - margin-top: -1px; + margin-top: -1px; } .btn-mini { - padding: 0 6px; - font-size: 10.5px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; + padding: 0 6px; + font-size: 10.5px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; } .btn-block { - display: block; - width: 100%; - padding-right: 0; - padding-left: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; + display: block; + width: 100%; + padding-right: 0; + padding-left: 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; } .btn-block + .btn-block { - margin-top: 5px; + margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { - width: 100%; + width: 100%; } .btn-primary.active, @@ -3321,29 +3332,29 @@ input[type="button"].btn-block { .btn-success.active, .btn-info.active, .btn-inverse.active { - color: rgba(255, 255, 255, 0.75); + color: rgba(255, 255, 255, 0.75); } .btn { - border-color: #c5c5c5; - border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); + border-color: #c5c5c5; + border-color: rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25); } .btn-primary { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #006dcc; - *background-color: #0044cc; - background-image: -moz-linear-gradient(top, #0088cc, #0044cc); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); - background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); - background-image: -o-linear-gradient(top, #0088cc, #0044cc); - background-image: linear-gradient(to bottom, #0088cc, #0044cc); - background-repeat: repeat-x; - border-color: #0044cc #0044cc #002a80; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #006dcc; + *background-color: #0044cc; + background-image: -moz-linear-gradient(top, #0088cc, #0044cc); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); + background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); + background-image: -o-linear-gradient(top, #0088cc, #0044cc); + background-image: linear-gradient(to bottom, #0088cc, #0044cc); + background-repeat: repeat-x; + border-color: #0044cc #0044cc #002a80; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-primary:hover, @@ -3351,31 +3362,31 @@ input[type="button"].btn-block { .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { - color: #ffffff; - background-color: #0044cc; - *background-color: #003bb3; + color: #ffffff; + background-color: #0044cc; + *background-color: #003bb3; } .btn-primary:active, .btn-primary.active { - background-color: #003399 \9; + background-color: #003399 \9; } .btn-warning { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #faa732; - *background-color: #f89406; - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(to bottom, #fbb450, #f89406); - background-repeat: repeat-x; - border-color: #f89406 #f89406 #ad6704; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #faa732; + *background-color: #f89406; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-repeat: repeat-x; + border-color: #f89406 #f89406 #ad6704; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-warning:hover, @@ -3383,31 +3394,31 @@ input[type="button"].btn-block { .btn-warning.active, .btn-warning.disabled, .btn-warning[disabled] { - color: #ffffff; - background-color: #f89406; - *background-color: #df8505; + color: #ffffff; + background-color: #f89406; + *background-color: #df8505; } .btn-warning:active, .btn-warning.active { - background-color: #c67605 \9; + background-color: #c67605 \9; } .btn-danger { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #da4f49; - *background-color: #bd362f; - background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); - background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); - background-repeat: repeat-x; - border-color: #bd362f #bd362f #802420; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #da4f49; + *background-color: #bd362f; + background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); + background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); + background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); + background-repeat: repeat-x; + border-color: #bd362f #bd362f #802420; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-danger:hover, @@ -3415,31 +3426,31 @@ input[type="button"].btn-block { .btn-danger.active, .btn-danger.disabled, .btn-danger[disabled] { - color: #ffffff; - background-color: #bd362f; - *background-color: #a9302a; + color: #ffffff; + background-color: #bd362f; + *background-color: #a9302a; } .btn-danger:active, .btn-danger.active { - background-color: #942a25 \9; + background-color: #942a25 \9; } .btn-success { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #5bb75b; - *background-color: #51a351; - background-image: -moz-linear-gradient(top, #62c462, #51a351); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); - background-image: -webkit-linear-gradient(top, #62c462, #51a351); - background-image: -o-linear-gradient(top, #62c462, #51a351); - background-image: linear-gradient(to bottom, #62c462, #51a351); - background-repeat: repeat-x; - border-color: #51a351 #51a351 #387038; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #5bb75b; + *background-color: #51a351; + background-image: -moz-linear-gradient(top, #62c462, #51a351); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); + background-image: -webkit-linear-gradient(top, #62c462, #51a351); + background-image: -o-linear-gradient(top, #62c462, #51a351); + background-image: linear-gradient(to bottom, #62c462, #51a351); + background-repeat: repeat-x; + border-color: #51a351 #51a351 #387038; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-success:hover, @@ -3447,31 +3458,31 @@ input[type="button"].btn-block { .btn-success.active, .btn-success.disabled, .btn-success[disabled] { - color: #ffffff; - background-color: #51a351; - *background-color: #499249; + color: #ffffff; + background-color: #51a351; + *background-color: #499249; } .btn-success:active, .btn-success.active { - background-color: #408140 \9; + background-color: #408140 \9; } .btn-info { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #49afcd; - *background-color: #2f96b4; - background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); - background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); - background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); - background-repeat: repeat-x; - border-color: #2f96b4 #2f96b4 #1f6377; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #49afcd; + *background-color: #2f96b4; + background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); + background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); + background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); + background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); + background-repeat: repeat-x; + border-color: #2f96b4 #2f96b4 #1f6377; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-info:hover, @@ -3479,31 +3490,31 @@ input[type="button"].btn-block { .btn-info.active, .btn-info.disabled, .btn-info[disabled] { - color: #ffffff; - background-color: #2f96b4; - *background-color: #2a85a0; + color: #ffffff; + background-color: #2f96b4; + *background-color: #2a85a0; } .btn-info:active, .btn-info.active { - background-color: #24748c \9; + background-color: #24748c \9; } .btn-inverse { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #363636; - *background-color: #222222; - background-image: -moz-linear-gradient(top, #444444, #222222); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); - background-image: -webkit-linear-gradient(top, #444444, #222222); - background-image: -o-linear-gradient(top, #444444, #222222); - background-image: linear-gradient(to bottom, #444444, #222222); - background-repeat: repeat-x; - border-color: #222222 #222222 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #363636; + *background-color: #222222; + background-image: -moz-linear-gradient(top, #444444, #222222); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); + background-image: -webkit-linear-gradient(top, #444444, #222222); + background-image: -o-linear-gradient(top, #444444, #222222); + background-image: linear-gradient(to bottom, #444444, #222222); + background-repeat: repeat-x; + border-color: #222222 #222222 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .btn-inverse:hover, @@ -3511,271 +3522,271 @@ input[type="button"].btn-block { .btn-inverse.active, .btn-inverse.disabled, .btn-inverse[disabled] { - color: #ffffff; - background-color: #222222; - *background-color: #151515; + color: #ffffff; + background-color: #222222; + *background-color: #151515; } .btn-inverse:active, .btn-inverse.active { - background-color: #080808 \9; + background-color: #080808 \9; } button.btn, input[type="submit"].btn { - *padding-top: 3px; - *padding-bottom: 3px; + *padding-top: 3px; + *padding-bottom: 3px; } button.btn::-moz-focus-inner, input[type="submit"].btn::-moz-focus-inner { - padding: 0; - border: 0; + padding: 0; + border: 0; } button.btn.btn-large, input[type="submit"].btn.btn-large { - *padding-top: 7px; - *padding-bottom: 7px; + *padding-top: 7px; + *padding-bottom: 7px; } button.btn.btn-small, input[type="submit"].btn.btn-small { - *padding-top: 3px; - *padding-bottom: 3px; + *padding-top: 3px; + *padding-bottom: 3px; } button.btn.btn-mini, input[type="submit"].btn.btn-mini { - *padding-top: 1px; - *padding-bottom: 1px; + *padding-top: 1px; + *padding-bottom: 1px; } .btn-link, .btn-link:active, .btn-link[disabled] { - background-color: transparent; - background-image: none; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; + background-color: transparent; + background-image: none; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; } .btn-link { - color: #0088cc; - cursor: pointer; - border-color: transparent; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + color: #0088cc; + cursor: pointer; + border-color: transparent; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .btn-link:hover { - color: #005580; - text-decoration: underline; - background-color: transparent; + color: #005580; + text-decoration: underline; + background-color: transparent; } .btn-link[disabled]:hover { - color: #333333; - text-decoration: none; + color: #333333; + text-decoration: none; } .btn-group { - position: relative; - display: inline-block; - *display: inline; - *margin-left: .3em; - font-size: 0; - white-space: nowrap; - vertical-align: middle; - *zoom: 1; + position: relative; + display: inline-block; + *display: inline; + *margin-left: .3em; + font-size: 0; + white-space: nowrap; + vertical-align: middle; + *zoom: 1; } .btn-group:first-child { - *margin-left: 0; + *margin-left: 0; } .btn-group + .btn-group { - margin-left: 5px; + margin-left: 5px; } .btn-toolbar { - margin-top: 10px; - margin-bottom: 10px; - font-size: 0; + margin-top: 10px; + margin-bottom: 10px; + font-size: 0; } .btn-toolbar > .btn + .btn, .btn-toolbar > .btn-group + .btn, .btn-toolbar > .btn + .btn-group { - margin-left: 5px; + margin-left: 5px; } .btn-group > .btn { - position: relative; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + position: relative; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .btn-group > .btn + .btn { - margin-left: -1px; + margin-left: -1px; } .btn-group > .btn, .btn-group > .dropdown-menu, .btn-group > .popover { - font-size: 14px; + font-size: 14px; } .btn-group > .btn-mini { - font-size: 10.5px; + font-size: 10.5px; } .btn-group > .btn-small { - font-size: 11.9px; + font-size: 11.9px; } .btn-group > .btn-large { - font-size: 17.5px; + font-size: 17.5px; } .btn-group > .btn:first-child { - margin-left: 0; - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - -moz-border-radius-topleft: 4px; + margin-left: 0; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + -moz-border-radius-topleft: 4px; } .btn-group > .btn:last-child, .btn-group > .dropdown-toggle { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -moz-border-radius-topright: 4px; - -moz-border-radius-bottomright: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; } .btn-group > .btn.large:first-child { - margin-left: 0; - -webkit-border-bottom-left-radius: 6px; - border-bottom-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; - -moz-border-radius-bottomleft: 6px; - -moz-border-radius-topleft: 6px; + margin-left: 0; + -webkit-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + -moz-border-radius-topleft: 6px; } .btn-group > .btn.large:last-child, .btn-group > .large.dropdown-toggle { - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -webkit-border-bottom-right-radius: 6px; - border-bottom-right-radius: 6px; - -moz-border-radius-topright: 6px; - -moz-border-radius-bottomright: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + -moz-border-radius-topright: 6px; + -moz-border-radius-bottomright: 6px; } .btn-group > .btn:hover, .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active { - z-index: 2; + z-index: 2; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { - outline: 0; + outline: 0; } .btn-group > .btn + .dropdown-toggle { - *padding-top: 5px; - padding-right: 8px; - *padding-bottom: 5px; - padding-left: 8px; - -webkit-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + *padding-top: 5px; + padding-right: 8px; + *padding-bottom: 5px; + padding-left: 8px; + -webkit-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-group > .btn-mini + .dropdown-toggle { - *padding-top: 2px; - padding-right: 5px; - *padding-bottom: 2px; - padding-left: 5px; + *padding-top: 2px; + padding-right: 5px; + *padding-bottom: 2px; + padding-left: 5px; } .btn-group > .btn-small + .dropdown-toggle { - *padding-top: 5px; - *padding-bottom: 4px; + *padding-top: 5px; + *padding-bottom: 4px; } .btn-group > .btn-large + .dropdown-toggle { - *padding-top: 7px; - padding-right: 12px; - *padding-bottom: 7px; - padding-left: 12px; + *padding-top: 7px; + padding-right: 12px; + *padding-bottom: 7px; + padding-left: 12px; } .btn-group.open .dropdown-toggle { - background-image: none; - -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + background-image: none; + -webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-group.open .btn.dropdown-toggle { - background-color: #e6e6e6; + background-color: #e6e6e6; } .btn-group.open .btn-primary.dropdown-toggle { - background-color: #0044cc; + background-color: #0044cc; } .btn-group.open .btn-warning.dropdown-toggle { - background-color: #f89406; + background-color: #f89406; } .btn-group.open .btn-danger.dropdown-toggle { - background-color: #bd362f; + background-color: #bd362f; } .btn-group.open .btn-success.dropdown-toggle { - background-color: #51a351; + background-color: #51a351; } .btn-group.open .btn-info.dropdown-toggle { - background-color: #2f96b4; + background-color: #2f96b4; } .btn-group.open .btn-inverse.dropdown-toggle { - background-color: #222222; + background-color: #222222; } .btn .caret { - margin-top: 8px; - margin-left: 0; + margin-top: 8px; + margin-left: 0; } .btn-mini .caret, .btn-small .caret, .btn-large .caret { - margin-top: 6px; + margin-top: 6px; } .btn-large .caret { - border-top-width: 5px; - border-right-width: 5px; - border-left-width: 5px; + border-top-width: 5px; + border-right-width: 5px; + border-left-width: 5px; } .dropup .btn-large .caret { - border-bottom-width: 5px; + border-bottom-width: 5px; } .btn-primary .caret, @@ -3784,824 +3795,824 @@ input[type="submit"].btn.btn-mini { .btn-info .caret, .btn-success .caret, .btn-inverse .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; + border-top-color: #ffffff; + border-bottom-color: #ffffff; } .btn-group-vertical { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ + display: inline-block; + *display: inline; + /* IE7 inline-block hack */ - *zoom: 1; + *zoom: 1; } .btn-group-vertical > .btn { - display: block; - float: none; - max-width: 100%; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + display: block; + float: none; + max-width: 100%; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .btn-group-vertical > .btn + .btn { - margin-top: -1px; - margin-left: 0; + margin-top: -1px; + margin-left: 0; } .btn-group-vertical > .btn:first-child { - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; } .btn-group-vertical > .btn:last-child { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; } .btn-group-vertical > .btn-large:first-child { - -webkit-border-radius: 6px 6px 0 0; - -moz-border-radius: 6px 6px 0 0; - border-radius: 6px 6px 0 0; + -webkit-border-radius: 6px 6px 0 0; + -moz-border-radius: 6px 6px 0 0; + border-radius: 6px 6px 0 0; } .btn-group-vertical > .btn-large:last-child { - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; } .alert { - padding: 8px 35px 8px 14px; - margin-bottom: 20px; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - background-color: #fcf8e3; - border: 1px solid #fbeed5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + padding: 8px 35px 8px 14px; + margin-bottom: 20px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + background-color: #fcf8e3; + border: 1px solid #fbeed5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .alert, .alert h4 { - color: #c09853; + color: #c09853; } .alert h4 { - margin: 0; + margin: 0; } .alert .close { - position: relative; - top: -2px; - right: -21px; - line-height: 20px; + position: relative; + top: -2px; + right: -21px; + line-height: 20px; } .alert-success { - color: #468847; - background-color: #dff0d8; - border-color: #d6e9c6; + color: #468847; + background-color: #dff0d8; + border-color: #d6e9c6; } .alert-success h4 { - color: #468847; + color: #468847; } .alert-danger, .alert-error { - color: #b94a48; - background-color: #f2dede; - border-color: #eed3d7; + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; } .alert-danger h4, .alert-error h4 { - color: #b94a48; + color: #b94a48; } .alert-info { - color: #3a87ad; - background-color: #d9edf7; - border-color: #bce8f1; + color: #3a87ad; + background-color: #d9edf7; + border-color: #bce8f1; } .alert-info h4 { - color: #3a87ad; + color: #3a87ad; } .alert-block { - padding-top: 14px; - padding-bottom: 14px; + padding-top: 14px; + padding-bottom: 14px; } .alert-block > p, .alert-block > ul { - margin-bottom: 0; + margin-bottom: 0; } .alert-block p + p { - margin-top: 5px; + margin-top: 5px; } .nav { - margin-bottom: 20px; - margin-left: 0; - list-style: none; + margin-bottom: 20px; + margin-left: 0; + list-style: none; } .nav > li > a { - display: block; + display: block; } .nav > li > a:hover { - text-decoration: none; - background-color: #eeeeee; + text-decoration: none; + background-color: #eeeeee; } .nav > li > a > img { - max-width: none; + max-width: none; } .nav > .pull-right { - float: right; + float: right; } .nav-header { - display: block; - padding: 3px 15px; - font-size: 11px; - font-weight: bold; - line-height: 20px; - color: #999999; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - text-transform: uppercase; + display: block; + padding: 3px 15px; + font-size: 11px; + font-weight: bold; + line-height: 20px; + color: #999999; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-transform: uppercase; } .nav li + .nav-header { - margin-top: 9px; + margin-top: 9px; } .nav-list { - padding-right: 15px; - padding-left: 15px; - margin-bottom: 0; + padding-right: 15px; + padding-left: 15px; + margin-bottom: 0; } .nav-list > li > a, .nav-list .nav-header { - margin-right: -15px; - margin-left: -15px; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + margin-right: -15px; + margin-left: -15px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); } .nav-list > li > a { - padding: 3px 15px; + padding: 3px 15px; } .nav-list > .active > a, .nav-list > .active > a:hover { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); - background-color: #0088cc; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); + background-color: #0088cc; } .nav-list [class^="icon-"], .nav-list [class*=" icon-"] { - margin-right: 2px; + margin-right: 2px; } .nav-list .divider { - *width: 100%; - height: 1px; - margin: 9px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; + *width: 100%; + height: 1px; + margin: 9px 1px; + *margin: -5px 0 5px; + overflow: hidden; + background-color: #e5e5e5; + border-bottom: 1px solid #ffffff; } .nav-tabs, .nav-pills { - *zoom: 1; + *zoom: 1; } .nav-tabs:before, .nav-pills:before, .nav-tabs:after, .nav-pills:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .nav-tabs:after, .nav-pills:after { - clear: both; + clear: both; } .nav-tabs > li, .nav-pills > li { - float: left; + float: left; } .nav-tabs > li > a, .nav-pills > li > a { - padding-right: 12px; - padding-left: 12px; - margin-right: 2px; - line-height: 14px; + padding-right: 12px; + padding-left: 12px; + margin-right: 2px; + line-height: 14px; } .nav-tabs { - border-bottom: 1px solid #ddd; + border-bottom: 1px solid #ddd; } .nav-tabs > li { - margin-bottom: -1px; + margin-bottom: -1px; } .nav-tabs > li > a { - padding-top: 8px; - padding-bottom: 8px; - line-height: 20px; - border: 1px solid transparent; - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; + padding-top: 8px; + padding-bottom: 8px; + line-height: 20px; + border: 1px solid transparent; + -webkit-border-radius: 4px 4px 0 0; + -moz-border-radius: 4px 4px 0 0; + border-radius: 4px 4px 0 0; } .nav-tabs > li > a:hover { - border-color: #eeeeee #eeeeee #dddddd; + border-color: #eeeeee #eeeeee #dddddd; } .nav-tabs > .active > a, .nav-tabs > .active > a:hover { - color: #555555; - cursor: default; - background-color: #ffffff; - border: 1px solid #ddd; - border-bottom-color: transparent; + color: #555555; + cursor: default; + background-color: #ffffff; + border: 1px solid #ddd; + border-bottom-color: transparent; } .nav-pills > li > a { - padding-top: 8px; - padding-bottom: 8px; - margin-top: 2px; - margin-bottom: 2px; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; + padding-top: 8px; + padding-bottom: 8px; + margin-top: 2px; + margin-bottom: 2px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; } .nav-pills > .active > a, .nav-pills > .active > a:hover { - color: #ffffff; - background-color: #0088cc; + color: #ffffff; + background-color: #0088cc; } .nav-stacked > li { - float: none; + float: none; } .nav-stacked > li > a { - margin-right: 0; + margin-right: 0; } .nav-tabs.nav-stacked { - border-bottom: 0; + border-bottom: 0; } .nav-tabs.nav-stacked > li > a { - border: 1px solid #ddd; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + border: 1px solid #ddd; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .nav-tabs.nav-stacked > li:first-child > a { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-topright: 4px; - -moz-border-radius-topleft: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-topleft: 4px; } .nav-tabs.nav-stacked > li:last-child > a { - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -moz-border-radius-bottomright: 4px; - -moz-border-radius-bottomleft: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -moz-border-radius-bottomright: 4px; + -moz-border-radius-bottomleft: 4px; } .nav-tabs.nav-stacked > li > a:hover { - z-index: 2; - border-color: #ddd; + z-index: 2; + border-color: #ddd; } .nav-pills.nav-stacked > li > a { - margin-bottom: 3px; + margin-bottom: 3px; } .nav-pills.nav-stacked > li:last-child > a { - margin-bottom: 1px; + margin-bottom: 1px; } .nav-tabs .dropdown-menu { - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; } .nav-pills .dropdown-menu { - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; } .nav .dropdown-toggle .caret { - margin-top: 6px; - border-top-color: #0088cc; - border-bottom-color: #0088cc; + margin-top: 6px; + border-top-color: #0088cc; + border-bottom-color: #0088cc; } .nav .dropdown-toggle:hover .caret { - border-top-color: #005580; - border-bottom-color: #005580; + border-top-color: #005580; + border-bottom-color: #005580; } /* move down carets for tabs */ .nav-tabs .dropdown-toggle .caret { - margin-top: 8px; + margin-top: 8px; } .nav .active .dropdown-toggle .caret { - border-top-color: #fff; - border-bottom-color: #fff; + border-top-color: #fff; + border-bottom-color: #fff; } .nav-tabs .active .dropdown-toggle .caret { - border-top-color: #555555; - border-bottom-color: #555555; + border-top-color: #555555; + border-bottom-color: #555555; } .nav > .dropdown.active > a:hover { - cursor: pointer; + cursor: pointer; } .nav-tabs .open .dropdown-toggle, .nav-pills .open .dropdown-toggle, .nav > li.dropdown.open.active > a:hover { - color: #ffffff; - background-color: #999999; - border-color: #999999; + color: #ffffff; + background-color: #999999; + border-color: #999999; } .nav li.dropdown.open .caret, .nav li.dropdown.open.active .caret, .nav li.dropdown.open a:hover .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; - opacity: 1; - filter: alpha(opacity=100); + border-top-color: #ffffff; + border-bottom-color: #ffffff; + opacity: 1; + filter: alpha(opacity=100); } .tabs-stacked .open > a:hover { - border-color: #999999; + border-color: #999999; } .tabbable { - *zoom: 1; + *zoom: 1; } .tabbable:before, .tabbable:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .tabbable:after { - clear: both; + clear: both; } .tab-content { - overflow: auto; + overflow: auto; } .tabs-below > .nav-tabs, .tabs-right > .nav-tabs, .tabs-left > .nav-tabs { - border-bottom: 0; + border-bottom: 0; } .tab-content > .tab-pane, .pill-content > .pill-pane { - display: none; + display: none; } .tab-content > .active, .pill-content > .active { - display: block; + display: block; } .tabs-below > .nav-tabs { - border-top: 1px solid #ddd; + border-top: 1px solid #ddd; } .tabs-below > .nav-tabs > li { - margin-top: -1px; - margin-bottom: 0; + margin-top: -1px; + margin-bottom: 0; } .tabs-below > .nav-tabs > li > a { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; + -webkit-border-radius: 0 0 4px 4px; + -moz-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; } .tabs-below > .nav-tabs > li > a:hover { - border-top-color: #ddd; - border-bottom-color: transparent; + border-top-color: #ddd; + border-bottom-color: transparent; } .tabs-below > .nav-tabs > .active > a, .tabs-below > .nav-tabs > .active > a:hover { - border-color: transparent #ddd #ddd #ddd; + border-color: transparent #ddd #ddd #ddd; } .tabs-left > .nav-tabs > li, .tabs-right > .nav-tabs > li { - float: none; + float: none; } .tabs-left > .nav-tabs > li > a, .tabs-right > .nav-tabs > li > a { - min-width: 74px; - margin-right: 0; - margin-bottom: 3px; + min-width: 74px; + margin-right: 0; + margin-bottom: 3px; } .tabs-left > .nav-tabs { - float: left; - margin-right: 19px; - border-right: 1px solid #ddd; + float: left; + margin-right: 19px; + border-right: 1px solid #ddd; } .tabs-left > .nav-tabs > li > a { - margin-right: -1px; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; + margin-right: -1px; + -webkit-border-radius: 4px 0 0 4px; + -moz-border-radius: 4px 0 0 4px; + border-radius: 4px 0 0 4px; } .tabs-left > .nav-tabs > li > a:hover { - border-color: #eeeeee #dddddd #eeeeee #eeeeee; + border-color: #eeeeee #dddddd #eeeeee #eeeeee; } .tabs-left > .nav-tabs .active > a, .tabs-left > .nav-tabs .active > a:hover { - border-color: #ddd transparent #ddd #ddd; - *border-right-color: #ffffff; + border-color: #ddd transparent #ddd #ddd; + *border-right-color: #ffffff; } .tabs-right > .nav-tabs { - float: right; - margin-left: 19px; - border-left: 1px solid #ddd; + float: right; + margin-left: 19px; + border-left: 1px solid #ddd; } .tabs-right > .nav-tabs > li > a { - margin-left: -1px; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; + margin-left: -1px; + -webkit-border-radius: 0 4px 4px 0; + -moz-border-radius: 0 4px 4px 0; + border-radius: 0 4px 4px 0; } .tabs-right > .nav-tabs > li > a:hover { - border-color: #eeeeee #eeeeee #eeeeee #dddddd; + border-color: #eeeeee #eeeeee #eeeeee #dddddd; } .tabs-right > .nav-tabs .active > a, .tabs-right > .nav-tabs .active > a:hover { - border-color: #ddd #ddd #ddd transparent; - *border-left-color: #ffffff; + border-color: #ddd #ddd #ddd transparent; + *border-left-color: #ffffff; } .nav > .disabled > a { - color: #999999; + color: #999999; } .nav > .disabled > a:hover { - text-decoration: none; - cursor: default; - background-color: transparent; + text-decoration: none; + cursor: default; + background-color: transparent; } .navbar { - *position: relative; - *z-index: 2; - margin-bottom: 20px; - overflow: visible; + *position: relative; + *z-index: 2; + margin-bottom: 20px; + overflow: visible; } .navbar-inner { - min-height: 40px; - padding-right: 20px; - padding-left: 20px; - background-color: #fafafa; - background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); - background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); - background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); - background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); - background-repeat: repeat-x; - border: 1px solid #d4d4d4; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); - *zoom: 1; - -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); - -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); - box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + min-height: 40px; + padding-right: 20px; + padding-left: 20px; + background-color: #fafafa; + background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); + background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); + background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); + background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); + background-repeat: repeat-x; + border: 1px solid #d4d4d4; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); + *zoom: 1; + -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); } .navbar-inner:before, .navbar-inner:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .navbar-inner:after { - clear: both; + clear: both; } .navbar .container { - width: auto; + width: auto; } .nav-collapse.collapse { - height: auto; - overflow: visible; + height: auto; + overflow: visible; } .navbar .brand { - display: block; - float: left; - padding: 10px 20px 10px; - margin-left: -20px; - font-size: 20px; - font-weight: 200; - color: #777777; - text-shadow: 0 1px 0 #ffffff; + display: block; + float: left; + padding: 10px 20px 10px; + margin-left: -20px; + font-size: 20px; + font-weight: 200; + color: #777777; + text-shadow: 0 1px 0 #ffffff; } .navbar .brand:hover { - text-decoration: none; + text-decoration: none; } .navbar-text { - margin-bottom: 0; - line-height: 40px; - color: #777777; + margin-bottom: 0; + line-height: 40px; + color: #777777; } .navbar-link { - color: #777777; + color: #777777; } .navbar-link:hover { - color: #333333; + color: #333333; } .navbar .divider-vertical { - height: 40px; - margin: 0 9px; - border-right: 1px solid #ffffff; - border-left: 1px solid #f2f2f2; + height: 40px; + margin: 0 9px; + border-right: 1px solid #ffffff; + border-left: 1px solid #f2f2f2; } .navbar .btn, .navbar .btn-group { - margin-top: 5px; + margin-top: 5px; } .navbar .btn-group .btn, .navbar .input-prepend .btn, .navbar .input-append .btn { - margin-top: 0; + margin-top: 0; } .navbar-form { - margin-bottom: 0; - *zoom: 1; + margin-bottom: 0; + *zoom: 1; } .navbar-form:before, .navbar-form:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .navbar-form:after { - clear: both; + clear: both; } .navbar-form input, .navbar-form select, .navbar-form .radio, .navbar-form .checkbox { - margin-top: 5px; + margin-top: 5px; } .navbar-form input, .navbar-form select, .navbar-form .btn { - display: inline-block; - margin-bottom: 0; + display: inline-block; + margin-bottom: 0; } .navbar-form input[type="image"], .navbar-form input[type="checkbox"], .navbar-form input[type="radio"] { - margin-top: 3px; + margin-top: 3px; } .navbar-form .input-append, .navbar-form .input-prepend { - margin-top: 5px; - white-space: nowrap; + margin-top: 5px; + white-space: nowrap; } .navbar-form .input-append input, .navbar-form .input-prepend input { - margin-top: 0; + margin-top: 0; } .navbar-search { - position: relative; - float: left; - margin-top: 5px; - margin-bottom: 0; + position: relative; + float: left; + margin-top: 5px; + margin-bottom: 0; } .navbar-search .search-query { - padding: 4px 14px; - margin-bottom: 0; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - font-weight: normal; - line-height: 1; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; + padding: 4px 14px; + margin-bottom: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 13px; + font-weight: normal; + line-height: 1; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; } .navbar-static-top { - position: static; - margin-bottom: 0; + position: static; + margin-bottom: 0; } .navbar-static-top .navbar-inner { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .navbar-fixed-top, .navbar-fixed-bottom { - position: fixed; - right: 0; - left: 0; - z-index: 1030; - margin-bottom: 0; + position: fixed; + right: 0; + left: 0; + z-index: 1030; + margin-bottom: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { - border-width: 0 0 1px; + border-width: 0 0 1px; } .navbar-fixed-bottom .navbar-inner { - border-width: 1px 0 0; + border-width: 1px 0 0; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { - padding-right: 0; - padding-left: 0; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; + padding-right: 0; + padding-left: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; } .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { - width: 940px; + width: 940px; } .navbar-fixed-top { - top: 0; + top: 0; } .navbar-fixed-top .navbar-inner, .navbar-static-top .navbar-inner { - -webkit-box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); - -moz-box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); - box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); + -webkit-box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); + box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1); } .navbar-fixed-bottom { - bottom: 0; + bottom: 0; } .navbar-fixed-bottom .navbar-inner { - -webkit-box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); - -moz-box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); - box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); + -webkit-box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); + -moz-box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); + box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1); } .navbar .nav { - position: relative; - left: 0; - display: block; - float: left; - margin: 0 10px 0 0; + position: relative; + left: 0; + display: block; + float: left; + margin: 0 10px 0 0; } .navbar .nav.pull-right { - float: right; - margin-right: 0; + float: right; + margin-right: 0; } .navbar .nav > li { - float: left; + float: left; } .navbar .nav > li > a { - float: none; - padding: 10px 15px 10px; - color: #777777; - text-decoration: none; - text-shadow: 0 1px 0 #ffffff; + float: none; + padding: 10px 15px 10px; + color: #777777; + text-decoration: none; + text-shadow: 0 1px 0 #ffffff; } .navbar .nav .dropdown-toggle .caret { - margin-top: 8px; + margin-top: 8px; } .navbar .nav > li > a:focus, .navbar .nav > li > a:hover { - color: #333333; - text-decoration: none; - background-color: transparent; + color: #333333; + text-decoration: none; + background-color: transparent; } .navbar .nav > .active > a, .navbar .nav > .active > a:hover, .navbar .nav > .active > a:focus { - color: #555555; - text-decoration: none; - background-color: #e5e5e5; - -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); - -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); - box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + color: #555555; + text-decoration: none; + background-color: #e5e5e5; + -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); + box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); } .navbar .btn-navbar { - display: none; - float: right; - padding: 7px 10px; - margin-right: 5px; - margin-left: 5px; - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #ededed; - *background-color: #e5e5e5; - background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); - background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); - background-repeat: repeat-x; - border-color: #e5e5e5 #e5e5e5 #bfbfbf; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + display: none; + float: right; + padding: 7px 10px; + margin-right: 5px; + margin-left: 5px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #ededed; + *background-color: #e5e5e5; + background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); + background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); + background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); + background-repeat: repeat-x; + border-color: #e5e5e5 #e5e5e5 #bfbfbf; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075); } .navbar .btn-navbar:hover, @@ -4609,258 +4620,258 @@ input[type="submit"].btn.btn-mini { .navbar .btn-navbar.active, .navbar .btn-navbar.disabled, .navbar .btn-navbar[disabled] { - color: #ffffff; - background-color: #e5e5e5; - *background-color: #d9d9d9; + color: #ffffff; + background-color: #e5e5e5; + *background-color: #d9d9d9; } .navbar .btn-navbar:active, .navbar .btn-navbar.active { - background-color: #cccccc \9; + background-color: #cccccc \9; } .navbar .btn-navbar .icon-bar { - display: block; - width: 18px; - height: 2px; - background-color: #f5f5f5; - -webkit-border-radius: 1px; - -moz-border-radius: 1px; - border-radius: 1px; - -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + display: block; + width: 18px; + height: 2px; + background-color: #f5f5f5; + -webkit-border-radius: 1px; + -moz-border-radius: 1px; + border-radius: 1px; + -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); + box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); } .btn-navbar .icon-bar + .icon-bar { - margin-top: 3px; + margin-top: 3px; } .navbar .nav > li > .dropdown-menu:before { - position: absolute; - top: -7px; - left: 9px; - display: inline-block; - border-right: 7px solid transparent; - border-bottom: 7px solid #ccc; - border-left: 7px solid transparent; - border-bottom-color: rgba(0, 0, 0, 0.2); - content: ''; + position: absolute; + top: -7px; + left: 9px; + display: inline-block; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-left: 7px solid transparent; + border-bottom-color: rgba(0, 0, 0, 0.2); + content: ''; } .navbar .nav > li > .dropdown-menu:after { - position: absolute; - top: -6px; - left: 10px; - display: inline-block; - border-right: 6px solid transparent; - border-bottom: 6px solid #ffffff; - border-left: 6px solid transparent; - content: ''; + position: absolute; + top: -6px; + left: 10px; + display: inline-block; + border-right: 6px solid transparent; + border-bottom: 6px solid #ffffff; + border-left: 6px solid transparent; + content: ''; } .navbar-fixed-bottom .nav > li > .dropdown-menu:before { - top: auto; - bottom: -7px; - border-top: 7px solid #ccc; - border-bottom: 0; - border-top-color: rgba(0, 0, 0, 0.2); + top: auto; + bottom: -7px; + border-top: 7px solid #ccc; + border-bottom: 0; + border-top-color: rgba(0, 0, 0, 0.2); } .navbar-fixed-bottom .nav > li > .dropdown-menu:after { - top: auto; - bottom: -6px; - border-top: 6px solid #ffffff; - border-bottom: 0; + top: auto; + bottom: -6px; + border-top: 6px solid #ffffff; + border-bottom: 0; } .navbar .nav li.dropdown > a:hover .caret { - border-top-color: #555555; - border-bottom-color: #555555; + border-top-color: #555555; + border-bottom-color: #555555; } .navbar .nav li.dropdown.open > .dropdown-toggle, .navbar .nav li.dropdown.active > .dropdown-toggle, .navbar .nav li.dropdown.open.active > .dropdown-toggle { - color: #555555; - background-color: #e5e5e5; + color: #555555; + background-color: #e5e5e5; } .navbar .nav li.dropdown > .dropdown-toggle .caret { - border-top-color: #777777; - border-bottom-color: #777777; + border-top-color: #777777; + border-bottom-color: #777777; } .navbar .nav li.dropdown.open > .dropdown-toggle .caret, .navbar .nav li.dropdown.active > .dropdown-toggle .caret, .navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { - border-top-color: #555555; - border-bottom-color: #555555; + border-top-color: #555555; + border-bottom-color: #555555; } .navbar .pull-right > li > .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right { - right: 0; - left: auto; + right: 0; + left: auto; } .navbar .pull-right > li > .dropdown-menu:before, .navbar .nav > li > .dropdown-menu.pull-right:before { - right: 12px; - left: auto; + right: 12px; + left: auto; } .navbar .pull-right > li > .dropdown-menu:after, .navbar .nav > li > .dropdown-menu.pull-right:after { - right: 13px; - left: auto; + right: 13px; + left: auto; } .navbar .pull-right > li > .dropdown-menu .dropdown-menu, .navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { - right: 100%; - left: auto; - margin-right: -1px; - margin-left: 0; - -webkit-border-radius: 6px 0 6px 6px; - -moz-border-radius: 6px 0 6px 6px; - border-radius: 6px 0 6px 6px; + right: 100%; + left: auto; + margin-right: -1px; + margin-left: 0; + -webkit-border-radius: 6px 0 6px 6px; + -moz-border-radius: 6px 0 6px 6px; + border-radius: 6px 0 6px 6px; } .navbar-inverse .navbar-inner { - background-color: #1b1b1b; - background-image: -moz-linear-gradient(top, #222222, #111111); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); - background-image: -webkit-linear-gradient(top, #222222, #111111); - background-image: -o-linear-gradient(top, #222222, #111111); - background-image: linear-gradient(to bottom, #222222, #111111); - background-repeat: repeat-x; - border-color: #252525; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); + background-color: #1b1b1b; + background-image: -moz-linear-gradient(top, #222222, #111111); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); + background-image: -webkit-linear-gradient(top, #222222, #111111); + background-image: -o-linear-gradient(top, #222222, #111111); + background-image: linear-gradient(to bottom, #222222, #111111); + background-repeat: repeat-x; + border-color: #252525; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); } .navbar-inverse .brand, .navbar-inverse .nav > li > a { - color: #999999; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + color: #999999; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-inverse .brand:hover, .navbar-inverse .nav > li > a:hover { - color: #ffffff; + color: #ffffff; } .navbar-inverse .brand { - color: #999999; + color: #999999; } .navbar-inverse .navbar-text { - color: #999999; + color: #999999; } .navbar-inverse .nav > li > a:focus, .navbar-inverse .nav > li > a:hover { - color: #ffffff; - background-color: transparent; + color: #ffffff; + background-color: transparent; } .navbar-inverse .nav .active > a, .navbar-inverse .nav .active > a:hover, .navbar-inverse .nav .active > a:focus { - color: #ffffff; - background-color: #111111; + color: #ffffff; + background-color: #111111; } .navbar-inverse .navbar-link { - color: #999999; + color: #999999; } .navbar-inverse .navbar-link:hover { - color: #ffffff; + color: #ffffff; } .navbar-inverse .divider-vertical { - border-right-color: #222222; - border-left-color: #111111; + border-right-color: #222222; + border-left-color: #111111; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { - color: #ffffff; - background-color: #111111; + color: #ffffff; + background-color: #111111; } .navbar-inverse .nav li.dropdown > a:hover .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; + border-top-color: #ffffff; + border-bottom-color: #ffffff; } .navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { - border-top-color: #999999; - border-bottom-color: #999999; + border-top-color: #999999; + border-bottom-color: #999999; } .navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, .navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; + border-top-color: #ffffff; + border-bottom-color: #ffffff; } .navbar-inverse .navbar-search .search-query { - color: #ffffff; - background-color: #515151; - border-color: #111111; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); - -webkit-transition: none; - -moz-transition: none; - -o-transition: none; - transition: none; + color: #ffffff; + background-color: #515151; + border-color: #111111; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15); + -webkit-transition: none; + -moz-transition: none; + -o-transition: none; + transition: none; } .navbar-inverse .navbar-search .search-query:-moz-placeholder { - color: #cccccc; + color: #cccccc; } .navbar-inverse .navbar-search .search-query:-ms-input-placeholder { - color: #cccccc; + color: #cccccc; } .navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { - color: #cccccc; + color: #cccccc; } .navbar-inverse .navbar-search .search-query:focus, .navbar-inverse .navbar-search .search-query.focused { - padding: 5px 15px; - color: #333333; - text-shadow: 0 1px 0 #ffffff; - background-color: #ffffff; - border: 0; - outline: 0; - -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + padding: 5px 15px; + color: #333333; + text-shadow: 0 1px 0 #ffffff; + background-color: #ffffff; + border: 0; + outline: 0; + -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); } .navbar-inverse .btn-navbar { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #0e0e0e; - *background-color: #040404; - background-image: -moz-linear-gradient(top, #151515, #040404); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); - background-image: -webkit-linear-gradient(top, #151515, #040404); - background-image: -o-linear-gradient(top, #151515, #040404); - background-image: linear-gradient(to bottom, #151515, #040404); - background-repeat: repeat-x; - border-color: #040404 #040404 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); - filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e0e0e; + *background-color: #040404; + background-image: -moz-linear-gradient(top, #151515, #040404); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); + background-image: -webkit-linear-gradient(top, #151515, #040404); + background-image: -o-linear-gradient(top, #151515, #040404); + background-image: linear-gradient(to bottom, #151515, #040404); + background-repeat: repeat-x; + border-color: #040404 #040404 #000000; + border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .navbar-inverse .btn-navbar:hover, @@ -4868,1190 +4879,1190 @@ input[type="submit"].btn.btn-mini { .navbar-inverse .btn-navbar.active, .navbar-inverse .btn-navbar.disabled, .navbar-inverse .btn-navbar[disabled] { - color: #ffffff; - background-color: #040404; - *background-color: #000000; + color: #ffffff; + background-color: #040404; + *background-color: #000000; } .navbar-inverse .btn-navbar:active, .navbar-inverse .btn-navbar.active { - background-color: #000000 \9; + background-color: #000000 \9; } .breadcrumb { - padding: 8px 15px; - margin: 0 0 20px; - list-style: none; - background-color: #f5f5f5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + padding: 8px 15px; + margin: 0 0 20px; + list-style: none; + background-color: #f5f5f5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .breadcrumb > li { - display: inline-block; - *display: inline; - text-shadow: 0 1px 0 #ffffff; - *zoom: 1; + display: inline-block; + *display: inline; + text-shadow: 0 1px 0 #ffffff; + *zoom: 1; } .breadcrumb > li > .divider { - padding: 0 5px; - color: #ccc; + padding: 0 5px; + color: #ccc; } .breadcrumb > .active { - color: #999999; + color: #999999; } .pagination { - margin: 20px 0; + margin: 20px 0; } .pagination ul { - display: inline-block; - *display: inline; - margin-bottom: 0; - margin-left: 0; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - *zoom: 1; - -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + display: inline-block; + *display: inline; + margin-bottom: 0; + margin-left: 0; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + *zoom: 1; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .pagination ul > li { - display: inline; + display: inline; } .pagination ul > li > a, .pagination ul > li > span { - float: left; - padding: 4px 12px; - line-height: 20px; - text-decoration: none; - background-color: #ffffff; - border: 1px solid #dddddd; - border-left-width: 0; + float: left; + padding: 4px 12px; + line-height: 20px; + text-decoration: none; + background-color: #ffffff; + border: 1px solid #dddddd; + border-left-width: 0; } .pagination ul > li > a:hover, .pagination ul > .active > a, .pagination ul > .active > span { - background-color: #f5f5f5; + background-color: #f5f5f5; } .pagination ul > .active > a, .pagination ul > .active > span { - color: #999999; - cursor: default; + color: #999999; + cursor: default; } .pagination ul > .disabled > span, .pagination ul > .disabled > a, .pagination ul > .disabled > a:hover { - color: #999999; - cursor: default; - background-color: transparent; + color: #999999; + cursor: default; + background-color: transparent; } .pagination ul > li:first-child > a, .pagination ul > li:first-child > span { - border-left-width: 1px; - -webkit-border-bottom-left-radius: 4px; - border-bottom-left-radius: 4px; - -webkit-border-top-left-radius: 4px; - border-top-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - -moz-border-radius-topleft: 4px; + border-left-width: 1px; + -webkit-border-bottom-left-radius: 4px; + border-bottom-left-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-bottomleft: 4px; + -moz-border-radius-topleft: 4px; } .pagination ul > li:last-child > a, .pagination ul > li:last-child > span { - -webkit-border-top-right-radius: 4px; - border-top-right-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - border-bottom-right-radius: 4px; - -moz-border-radius-topright: 4px; - -moz-border-radius-bottomright: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; } .pagination-centered { - text-align: center; + text-align: center; } .pagination-right { - text-align: right; + text-align: right; } .pagination-large ul > li > a, .pagination-large ul > li > span { - padding: 11px 19px; - font-size: 17.5px; + padding: 11px 19px; + font-size: 17.5px; } .pagination-large ul > li:first-child > a, .pagination-large ul > li:first-child > span { - -webkit-border-bottom-left-radius: 6px; - border-bottom-left-radius: 6px; - -webkit-border-top-left-radius: 6px; - border-top-left-radius: 6px; - -moz-border-radius-bottomleft: 6px; - -moz-border-radius-topleft: 6px; + -webkit-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -webkit-border-top-left-radius: 6px; + border-top-left-radius: 6px; + -moz-border-radius-bottomleft: 6px; + -moz-border-radius-topleft: 6px; } .pagination-large ul > li:last-child > a, .pagination-large ul > li:last-child > span { - -webkit-border-top-right-radius: 6px; - border-top-right-radius: 6px; - -webkit-border-bottom-right-radius: 6px; - border-bottom-right-radius: 6px; - -moz-border-radius-topright: 6px; - -moz-border-radius-bottomright: 6px; + -webkit-border-top-right-radius: 6px; + border-top-right-radius: 6px; + -webkit-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + -moz-border-radius-topright: 6px; + -moz-border-radius-bottomright: 6px; } .pagination-mini ul > li:first-child > a, .pagination-small ul > li:first-child > a, .pagination-mini ul > li:first-child > span, .pagination-small ul > li:first-child > span { - -webkit-border-bottom-left-radius: 3px; - border-bottom-left-radius: 3px; - -webkit-border-top-left-radius: 3px; - border-top-left-radius: 3px; - -moz-border-radius-bottomleft: 3px; - -moz-border-radius-topleft: 3px; + -webkit-border-bottom-left-radius: 3px; + border-bottom-left-radius: 3px; + -webkit-border-top-left-radius: 3px; + border-top-left-radius: 3px; + -moz-border-radius-bottomleft: 3px; + -moz-border-radius-topleft: 3px; } .pagination-mini ul > li:last-child > a, .pagination-small ul > li:last-child > a, .pagination-mini ul > li:last-child > span, .pagination-small ul > li:last-child > span { - -webkit-border-top-right-radius: 3px; - border-top-right-radius: 3px; - -webkit-border-bottom-right-radius: 3px; - border-bottom-right-radius: 3px; - -moz-border-radius-topright: 3px; - -moz-border-radius-bottomright: 3px; + -webkit-border-top-right-radius: 3px; + border-top-right-radius: 3px; + -webkit-border-bottom-right-radius: 3px; + border-bottom-right-radius: 3px; + -moz-border-radius-topright: 3px; + -moz-border-radius-bottomright: 3px; } .pagination-small ul > li > a, .pagination-small ul > li > span { - padding: 2px 10px; - font-size: 11.9px; + padding: 2px 10px; + font-size: 11.9px; } .pagination-mini ul > li > a, .pagination-mini ul > li > span { - padding: 0 6px; - font-size: 10.5px; + padding: 0 6px; + font-size: 10.5px; } .pager { - margin: 20px 0; - text-align: center; - list-style: none; - *zoom: 1; + margin: 20px 0; + text-align: center; + list-style: none; + *zoom: 1; } .pager:before, .pager:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .pager:after { - clear: both; + clear: both; } .pager li { - display: inline; + display: inline; } .pager li > a, .pager li > span { - display: inline-block; - padding: 5px 14px; - background-color: #fff; - border: 1px solid #ddd; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + -webkit-border-radius: 15px; + -moz-border-radius: 15px; + border-radius: 15px; } .pager li > a:hover { - text-decoration: none; - background-color: #f5f5f5; + text-decoration: none; + background-color: #f5f5f5; } .pager .next > a, .pager .next > span { - float: right; + float: right; } .pager .previous > a, .pager .previous > span { - float: left; + float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > span { - color: #999999; - cursor: default; - background-color: #fff; + color: #999999; + cursor: default; + background-color: #fff; } .modal-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - background-color: #000000; + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000000; } .modal-backdrop.fade { - opacity: 0; + opacity: 0; } .modal-backdrop, .modal-backdrop.fade.in { - opacity: 0.8; - filter: alpha(opacity=80); + opacity: 0.8; + filter: alpha(opacity=80); } .modal { - position: fixed; - top: 10%; - left: 50%; - z-index: 1050; - width: 560px; - margin-left: -280px; - background-color: #ffffff; - border: 1px solid #999; - border: 1px solid rgba(0, 0, 0, 0.3); - *border: 1px solid #999; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - outline: none; - -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -webkit-background-clip: padding-box; - -moz-background-clip: padding-box; - background-clip: padding-box; + position: fixed; + top: 10%; + left: 50%; + z-index: 1050; + width: 560px; + margin-left: -280px; + background-color: #ffffff; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, 0.3); + *border: 1px solid #999; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + outline: none; + -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); + -webkit-background-clip: padding-box; + -moz-background-clip: padding-box; + background-clip: padding-box; } .modal.fade { - top: -25%; - -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; - -moz-transition: opacity 0.3s linear, top 0.3s ease-out; - -o-transition: opacity 0.3s linear, top 0.3s ease-out; - transition: opacity 0.3s linear, top 0.3s ease-out; + top: -25%; + -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; + -moz-transition: opacity 0.3s linear, top 0.3s ease-out; + -o-transition: opacity 0.3s linear, top 0.3s ease-out; + transition: opacity 0.3s linear, top 0.3s ease-out; } .modal.fade.in { - top: 10%; + top: 10%; } .modal-header { - padding: 9px 15px; - border-bottom: 1px solid #eee; + padding: 9px 15px; + border-bottom: 1px solid #eee; } .modal-header .close { - margin-top: 2px; + margin-top: 2px; } .modal-header h3 { - margin: 0; - line-height: 30px; + margin: 0; + line-height: 30px; } .modal-body { - position: relative; - max-height: 400px; - padding: 15px; - overflow-y: auto; + position: relative; + max-height: 400px; + padding: 15px; + overflow-y: auto; } .modal-form { - margin-bottom: 0; + margin-bottom: 0; } .modal-footer { - padding: 14px 15px 15px; - margin-bottom: 0; - text-align: right; - background-color: #f5f5f5; - border-top: 1px solid #ddd; - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; - *zoom: 1; - -webkit-box-shadow: inset 0 1px 0 #ffffff; - -moz-box-shadow: inset 0 1px 0 #ffffff; - box-shadow: inset 0 1px 0 #ffffff; + padding: 14px 15px 15px; + margin-bottom: 0; + text-align: right; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + -webkit-border-radius: 0 0 6px 6px; + -moz-border-radius: 0 0 6px 6px; + border-radius: 0 0 6px 6px; + *zoom: 1; + -webkit-box-shadow: inset 0 1px 0 #ffffff; + -moz-box-shadow: inset 0 1px 0 #ffffff; + box-shadow: inset 0 1px 0 #ffffff; } .modal-footer:before, .modal-footer:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .modal-footer:after { - clear: both; + clear: both; } .modal-footer .btn + .btn { - margin-bottom: 0; - margin-left: 5px; + margin-bottom: 0; + margin-left: 5px; } .modal-footer .btn-group .btn + .btn { - margin-left: -1px; + margin-left: -1px; } .modal-footer .btn-block + .btn-block { - margin-left: 0; + margin-left: 0; } .tooltip { - position: absolute; - z-index: 1030; - display: block; - padding: 5px; - font-size: 11px; - opacity: 0; - filter: alpha(opacity=0); - visibility: visible; + position: absolute; + z-index: 1030; + display: block; + padding: 5px; + font-size: 11px; + opacity: 0; + filter: alpha(opacity=0); + visibility: visible; } .tooltip.in { - opacity: 0.8; - filter: alpha(opacity=80); + opacity: 0.8; + filter: alpha(opacity=80); } .tooltip.top { - margin-top: -3px; + margin-top: -3px; } .tooltip.right { - margin-left: 3px; + margin-left: 3px; } .tooltip.bottom { - margin-top: 3px; + margin-top: 3px; } .tooltip.left { - margin-left: -3px; + margin-left: -3px; } .tooltip-inner { - max-width: 200px; - padding: 3px 8px; - color: #ffffff; - text-align: center; - text-decoration: none; - background-color: #000000; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + max-width: 200px; + padding: 3px 8px; + color: #ffffff; + text-align: center; + text-decoration: none; + background-color: #000000; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .tooltip-arrow { - position: absolute; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; + position: absolute; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; } .tooltip.top .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-top-color: #000000; - border-width: 5px 5px 0; + bottom: 0; + left: 50%; + margin-left: -5px; + border-top-color: #000000; + border-width: 5px 5px 0; } .tooltip.right .tooltip-arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-right-color: #000000; - border-width: 5px 5px 5px 0; + top: 50%; + left: 0; + margin-top: -5px; + border-right-color: #000000; + border-width: 5px 5px 5px 0; } .tooltip.left .tooltip-arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-left-color: #000000; - border-width: 5px 0 5px 5px; + top: 50%; + right: 0; + margin-top: -5px; + border-left-color: #000000; + border-width: 5px 0 5px 5px; } .tooltip.bottom .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-bottom-color: #000000; - border-width: 0 5px 5px; + top: 0; + left: 50%; + margin-left: -5px; + border-bottom-color: #000000; + border-width: 0 5px 5px; } .popover { - position: absolute; - top: 0; - left: 0; - z-index: 1010; - display: none; - width: 236px; - padding: 1px; - text-align: left; - white-space: normal; - background-color: #ffffff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -webkit-background-clip: padding-box; - -moz-background-clip: padding; - background-clip: padding-box; + position: absolute; + top: 0; + left: 0; + z-index: 1010; + display: none; + width: 236px; + padding: 1px; + text-align: left; + white-space: normal; + background-color: #ffffff; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, 0.2); + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; } .popover.top { - margin-top: -10px; + margin-top: -10px; } .popover.right { - margin-left: 10px; + margin-left: 10px; } .popover.bottom { - margin-top: 10px; + margin-top: 10px; } .popover.left { - margin-left: -10px; + margin-left: -10px; } .popover-title { - padding: 8px 14px; - margin: 0; - font-size: 14px; - font-weight: normal; - line-height: 18px; - background-color: #f7f7f7; - border-bottom: 1px solid #ebebeb; - -webkit-border-radius: 5px 5px 0 0; - -moz-border-radius: 5px 5px 0 0; - border-radius: 5px 5px 0 0; + padding: 8px 14px; + margin: 0; + font-size: 14px; + font-weight: normal; + line-height: 18px; + background-color: #f7f7f7; + border-bottom: 1px solid #ebebeb; + -webkit-border-radius: 5px 5px 0 0; + -moz-border-radius: 5px 5px 0 0; + border-radius: 5px 5px 0 0; } .popover-content { - padding: 9px 14px; + padding: 9px 14px; } .popover .arrow, .popover .arrow:after { - position: absolute; - display: block; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; } .popover .arrow { - border-width: 11px; + border-width: 11px; } .popover .arrow:after { - border-width: 10px; - content: ""; + border-width: 10px; + content: ""; } .popover.top .arrow { - bottom: -11px; - left: 50%; - margin-left: -11px; - border-top-color: #999; - border-top-color: rgba(0, 0, 0, 0.25); - border-bottom-width: 0; + bottom: -11px; + left: 50%; + margin-left: -11px; + border-top-color: #999; + border-top-color: rgba(0, 0, 0, 0.25); + border-bottom-width: 0; } .popover.top .arrow:after { - bottom: 1px; - margin-left: -10px; - border-top-color: #ffffff; - border-bottom-width: 0; + bottom: 1px; + margin-left: -10px; + border-top-color: #ffffff; + border-bottom-width: 0; } .popover.right .arrow { - top: 50%; - left: -11px; - margin-top: -11px; - border-right-color: #999; - border-right-color: rgba(0, 0, 0, 0.25); - border-left-width: 0; + top: 50%; + left: -11px; + margin-top: -11px; + border-right-color: #999; + border-right-color: rgba(0, 0, 0, 0.25); + border-left-width: 0; } .popover.right .arrow:after { - bottom: -10px; - left: 1px; - border-right-color: #ffffff; - border-left-width: 0; + bottom: -10px; + left: 1px; + border-right-color: #ffffff; + border-left-width: 0; } .popover.bottom .arrow { - top: -11px; - left: 50%; - margin-left: -11px; - border-bottom-color: #999; - border-bottom-color: rgba(0, 0, 0, 0.25); - border-top-width: 0; + top: -11px; + left: 50%; + margin-left: -11px; + border-bottom-color: #999; + border-bottom-color: rgba(0, 0, 0, 0.25); + border-top-width: 0; } .popover.bottom .arrow:after { - top: 1px; - margin-left: -10px; - border-bottom-color: #ffffff; - border-top-width: 0; + top: 1px; + margin-left: -10px; + border-bottom-color: #ffffff; + border-top-width: 0; } .popover.left .arrow { - top: 50%; - right: -11px; - margin-top: -11px; - border-left-color: #999; - border-left-color: rgba(0, 0, 0, 0.25); - border-right-width: 0; + top: 50%; + right: -11px; + margin-top: -11px; + border-left-color: #999; + border-left-color: rgba(0, 0, 0, 0.25); + border-right-width: 0; } .popover.left .arrow:after { - right: 1px; - bottom: -10px; - border-left-color: #ffffff; - border-right-width: 0; + right: 1px; + bottom: -10px; + border-left-color: #ffffff; + border-right-width: 0; } .thumbnails { - margin-left: -20px; - list-style: none; - *zoom: 1; + margin-left: -20px; + list-style: none; + *zoom: 1; } .thumbnails:before, .thumbnails:after { - display: table; - line-height: 0; - content: ""; + display: table; + line-height: 0; + content: ""; } .thumbnails:after { - clear: both; + clear: both; } .row-fluid .thumbnails { - margin-left: 0; + margin-left: 0; } .thumbnails > li { - float: left; - margin-bottom: 20px; - margin-left: 20px; + float: left; + margin-bottom: 20px; + margin-left: 20px; } .thumbnail { - display: block; - padding: 4px; - line-height: 20px; - border: 1px solid #ddd; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - -webkit-transition: all 0.2s ease-in-out; - -moz-transition: all 0.2s ease-in-out; - -o-transition: all 0.2s ease-in-out; - transition: all 0.2s ease-in-out; + display: block; + padding: 4px; + line-height: 20px; + border: 1px solid #ddd; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); + -webkit-transition: all 0.2s ease-in-out; + -moz-transition: all 0.2s ease-in-out; + -o-transition: all 0.2s ease-in-out; + transition: all 0.2s ease-in-out; } a.thumbnail:hover { - border-color: #0088cc; - -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + border-color: #0088cc; + -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); + box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); } .thumbnail > img { - display: block; - max-width: 100%; - margin-right: auto; - margin-left: auto; + display: block; + max-width: 100%; + margin-right: auto; + margin-left: auto; } .thumbnail .caption { - padding: 9px; - color: #555555; + padding: 9px; + color: #555555; } .media, .media-body { - overflow: hidden; - *overflow: visible; - zoom: 1; + overflow: hidden; + *overflow: visible; + zoom: 1; } .media, .media .media { - margin-top: 15px; + margin-top: 15px; } .media:first-child { - margin-top: 0; + margin-top: 0; } .media-object { - display: block; + display: block; } .media-heading { - margin: 0 0 5px; + margin: 0 0 5px; } .media .pull-left { - margin-right: 10px; + margin-right: 10px; } .media .pull-right { - margin-left: 10px; + margin-left: 10px; } .media-list { - margin-left: 0; - list-style: none; + margin-left: 0; + list-style: none; } .label, .badge { - display: inline-block; - padding: 2px 4px; - font-size: 11.844px; - font-weight: bold; - line-height: 14px; - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - white-space: nowrap; - vertical-align: baseline; - background-color: #999999; + display: inline-block; + padding: 2px 4px; + font-size: 11.844px; + font-weight: bold; + line-height: 14px; + color: #ffffff; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + white-space: nowrap; + vertical-align: baseline; + background-color: #999999; } .label { - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + border-radius: 3px; } .badge { - padding-right: 9px; - padding-left: 9px; - -webkit-border-radius: 9px; - -moz-border-radius: 9px; - border-radius: 9px; + padding-right: 9px; + padding-left: 9px; + -webkit-border-radius: 9px; + -moz-border-radius: 9px; + border-radius: 9px; } .label:empty, .badge:empty { - display: none; + display: none; } a.label:hover, a.badge:hover { - color: #ffffff; - text-decoration: none; - cursor: pointer; + color: #ffffff; + text-decoration: none; + cursor: pointer; } .label-important, .badge-important { - background-color: #b94a48; + background-color: #b94a48; } .label-important[href], .badge-important[href] { - background-color: #953b39; + background-color: #953b39; } .label-warning, .badge-warning { - background-color: #f89406; + background-color: #f89406; } .label-warning[href], .badge-warning[href] { - background-color: #c67605; + background-color: #c67605; } .label-success, .badge-success { - background-color: #468847; + background-color: #468847; } .label-success[href], .badge-success[href] { - background-color: #356635; + background-color: #356635; } .label-info, .badge-info { - background-color: #3a87ad; + background-color: #3a87ad; } .label-info[href], .badge-info[href] { - background-color: #2d6987; + background-color: #2d6987; } .label-inverse, .badge-inverse { - background-color: #333333; + background-color: #333333; } .label-inverse[href], .badge-inverse[href] { - background-color: #1a1a1a; + background-color: #1a1a1a; } .btn .label, .btn .badge { - position: relative; - top: -1px; + position: relative; + top: -1px; } .btn-mini .label, .btn-mini .badge { - top: 0; + top: 0; } @-webkit-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } @-moz-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } @-ms-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } @-o-keyframes progress-bar-stripes { - from { - background-position: 0 0; - } - to { - background-position: 40px 0; - } + from { + background-position: 0 0; + } + to { + background-position: 40px 0; + } } @keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } } .progress { - height: 20px; - margin-bottom: 20px; - overflow: hidden; - background-color: #f7f7f7; - background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); - background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); - background-repeat: repeat-x; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + height: 20px; + margin-bottom: 20px; + overflow: hidden; + background-color: #f7f7f7; + background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); + background-repeat: repeat-x; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); } .progress .bar { - float: left; - width: 0; - height: 100%; - font-size: 12px; - color: #ffffff; - text-align: center; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #0e90d2; - background-image: -moz-linear-gradient(top, #149bdf, #0480be); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); - background-image: -webkit-linear-gradient(top, #149bdf, #0480be); - background-image: -o-linear-gradient(top, #149bdf, #0480be); - background-image: linear-gradient(to bottom, #149bdf, #0480be); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); - -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - -webkit-transition: width 0.6s ease; - -moz-transition: width 0.6s ease; - -o-transition: width 0.6s ease; - transition: width 0.6s ease; + float: left; + width: 0; + height: 100%; + font-size: 12px; + color: #ffffff; + text-align: center; + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); + background-color: #0e90d2; + background-image: -moz-linear-gradient(top, #149bdf, #0480be); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, #0480be); + background-image: -o-linear-gradient(top, #149bdf, #0480be); + background-image: linear-gradient(to bottom, #149bdf, #0480be); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-transition: width 0.6s ease; + -moz-transition: width 0.6s ease; + -o-transition: width 0.6s ease; + transition: width 0.6s ease; } .progress .bar + .bar { - -webkit-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -moz-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); - box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15); } .progress-striped .bar { - background-color: #149bdf; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - -webkit-background-size: 40px 40px; - -moz-background-size: 40px 40px; - -o-background-size: 40px 40px; - background-size: 40px 40px; + background-color: #149bdf; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + -webkit-background-size: 40px 40px; + -moz-background-size: 40px 40px; + -o-background-size: 40px 40px; + background-size: 40px 40px; } .progress.active .bar { - -webkit-animation: progress-bar-stripes 2s linear infinite; - -moz-animation: progress-bar-stripes 2s linear infinite; - -ms-animation: progress-bar-stripes 2s linear infinite; - -o-animation: progress-bar-stripes 2s linear infinite; - animation: progress-bar-stripes 2s linear infinite; + -webkit-animation: progress-bar-stripes 2s linear infinite; + -moz-animation: progress-bar-stripes 2s linear infinite; + -ms-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; } .progress-danger .bar, .progress .bar-danger { - background-color: #dd514c; - background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); - background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); + background-color: #dd514c; + background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); + background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); + background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); + background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); } .progress-danger.progress-striped .bar, .progress-striped .bar-danger { - background-color: #ee5f5b; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-color: #ee5f5b; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-success .bar, .progress .bar-success { - background-color: #5eb95e; - background-image: -moz-linear-gradient(top, #62c462, #57a957); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); - background-image: -webkit-linear-gradient(top, #62c462, #57a957); - background-image: -o-linear-gradient(top, #62c462, #57a957); - background-image: linear-gradient(to bottom, #62c462, #57a957); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); + background-color: #5eb95e; + background-image: -moz-linear-gradient(top, #62c462, #57a957); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); + background-image: -webkit-linear-gradient(top, #62c462, #57a957); + background-image: -o-linear-gradient(top, #62c462, #57a957); + background-image: linear-gradient(to bottom, #62c462, #57a957); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); } .progress-success.progress-striped .bar, .progress-striped .bar-success { - background-color: #62c462; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-color: #62c462; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-info .bar, .progress .bar-info { - background-color: #4bb1cf; - background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); - background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); - background-image: -o-linear-gradient(top, #5bc0de, #339bb9); - background-image: linear-gradient(to bottom, #5bc0de, #339bb9); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); + background-color: #4bb1cf; + background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); + background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); + background-image: -o-linear-gradient(top, #5bc0de, #339bb9); + background-image: linear-gradient(to bottom, #5bc0de, #339bb9); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); } .progress-info.progress-striped .bar, .progress-striped .bar-info { - background-color: #5bc0de; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-color: #5bc0de; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-warning .bar, .progress .bar-warning { - background-color: #faa732; - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(to bottom, #fbb450, #f89406); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); + background-color: #faa732; + background-image: -moz-linear-gradient(top, #fbb450, #f89406); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); + background-image: -webkit-linear-gradient(top, #fbb450, #f89406); + background-image: -o-linear-gradient(top, #fbb450, #f89406); + background-image: linear-gradient(to bottom, #fbb450, #f89406); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); } .progress-warning.progress-striped .bar, .progress-striped .bar-warning { - background-color: #fbb450; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-color: #fbb450; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .accordion { - margin-bottom: 20px; + margin-bottom: 20px; } .accordion-group { - margin-bottom: 2px; - border: 1px solid #e5e5e5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + margin-bottom: 2px; + border: 1px solid #e5e5e5; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; } .accordion-heading { - border-bottom: 0; + border-bottom: 0; } .accordion-heading .accordion-toggle { - display: block; - padding: 8px 15px; + display: block; + padding: 8px 15px; } .accordion-toggle { - cursor: pointer; + cursor: pointer; } .accordion-inner { - padding: 9px 15px; - border-top: 1px solid #e5e5e5; + padding: 9px 15px; + border-top: 1px solid #e5e5e5; } .carousel { - position: relative; - margin-bottom: 20px; - line-height: 1; + position: relative; + margin-bottom: 20px; + line-height: 1; } .carousel-inner { - position: relative; - width: 100%; - overflow: hidden; + position: relative; + width: 100%; + overflow: hidden; } .carousel-inner > .item { - position: relative; - display: none; - -webkit-transition: 0.6s ease-in-out left; - -moz-transition: 0.6s ease-in-out left; - -o-transition: 0.6s ease-in-out left; - transition: 0.6s ease-in-out left; + position: relative; + display: none; + -webkit-transition: 0.6s ease-in-out left; + -moz-transition: 0.6s ease-in-out left; + -o-transition: 0.6s ease-in-out left; + transition: 0.6s ease-in-out left; } .carousel-inner > .item > img { - display: block; - line-height: 1; + display: block; + line-height: 1; } .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { - display: block; + display: block; } .carousel-inner > .active { - left: 0; + left: 0; } .carousel-inner > .next, .carousel-inner > .prev { - position: absolute; - top: 0; - width: 100%; + position: absolute; + top: 0; + width: 100%; } .carousel-inner > .next { - left: 100%; + left: 100%; } .carousel-inner > .prev { - left: -100%; + left: -100%; } .carousel-inner > .next.left, .carousel-inner > .prev.right { - left: 0; + left: 0; } .carousel-inner > .active.left { - left: -100%; + left: -100%; } .carousel-inner > .active.right { - left: 100%; + left: 100%; } .carousel-control { - position: absolute; - top: 40%; - left: 15px; - width: 40px; - height: 40px; - margin-top: -20px; - font-size: 60px; - font-weight: 100; - line-height: 30px; - color: #ffffff; - text-align: center; - background: #222222; - border: 3px solid #ffffff; - -webkit-border-radius: 23px; - -moz-border-radius: 23px; - border-radius: 23px; - opacity: 0.5; - filter: alpha(opacity=50); + position: absolute; + top: 40%; + left: 15px; + width: 40px; + height: 40px; + margin-top: -20px; + font-size: 60px; + font-weight: 100; + line-height: 30px; + color: #ffffff; + text-align: center; + background: #222222; + border: 3px solid #ffffff; + -webkit-border-radius: 23px; + -moz-border-radius: 23px; + border-radius: 23px; + opacity: 0.5; + filter: alpha(opacity=50); } .carousel-control.right { - right: 15px; - left: auto; + right: 15px; + left: auto; } .carousel-control:hover { - color: #ffffff; - text-decoration: none; - opacity: 0.9; - filter: alpha(opacity=90); + color: #ffffff; + text-decoration: none; + opacity: 0.9; + filter: alpha(opacity=90); } .carousel-caption { - position: absolute; - right: 0; - bottom: 0; - left: 0; - padding: 15px; - background: #333333; - background: rgba(0, 0, 0, 0.75); + position: absolute; + right: 0; + bottom: 0; + left: 0; + padding: 15px; + background: #333333; + background: rgba(0, 0, 0, 0.75); } .carousel-caption h4, .carousel-caption p { - line-height: 20px; - color: #ffffff; + line-height: 20px; + color: #ffffff; } .carousel-caption h4 { - margin: 0 0 5px; + margin: 0 0 5px; } .carousel-caption p { - margin-bottom: 0; + margin-bottom: 0; } .hero-unit { - padding: 60px; - margin-bottom: 30px; - font-size: 18px; - font-weight: 200; - line-height: 30px; - color: inherit; - background-color: #eeeeee; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; + padding: 60px; + margin-bottom: 30px; + font-size: 18px; + font-weight: 200; + line-height: 30px; + color: inherit; + background-color: #eeeeee; + -webkit-border-radius: 6px; + -moz-border-radius: 6px; + border-radius: 6px; } .hero-unit h1 { - margin-bottom: 0; - font-size: 60px; - line-height: 1; - letter-spacing: -1px; - color: inherit; + margin-bottom: 0; + font-size: 60px; + line-height: 1; + letter-spacing: -1px; + color: inherit; } .hero-unit li { - line-height: 30px; + line-height: 30px; } .pull-right { - float: right; + float: right; } .pull-left { - float: left; + float: left; } .hide { - display: none; + display: none; } .show { - display: block; + display: block; } .invisible { - visibility: hidden; + visibility: hidden; } .affix { - position: fixed; + position: fixed; } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css index f14f6bdb62c..59a05ee958a 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/css/style.css @@ -1,308 +1,309 @@ .line-numbers { - margin-right: 1.0em; + margin-right: 1.0em; } .content { - padding-bottom: 100px; + padding-bottom: 100px; } .column_header_name { - width: 150px; + width: 150px; } .column_header_path { - width: 350px; + width: 350px; } .column_header_name .column_header_param_type .column_header_data_type .column_header_return_type { - width: 200px; + width: 200px; } .expandable { - display: none; + display: none; } .main_content { - margin-top: 80px; - margin-left: 25px; - margin-right: 25px; + margin-top: 80px; + margin-left: 25px; + margin-right: 25px; } .model { - float: left; + float: left; } .model-container { - float: left; - width: 500px; - padding: 0px; + float: left; + width: 500px; + padding: 0px; } .model-detail-container { - clear: left; - float: left; - width: 500px; - margin-left: 40px; + clear: left; + float: left; + width: 500px; + margin-left: 40px; } .model-detail-popup { - box-shadow: rgba(0, 0, 0, 0.2) 0 2px 8px 5px; - border-style: solid; - border-width: 1px; - border-color: black; - padding-left: 10px; - padding-right: 10px; - padding-top: 10px; - padding-bottom: 10px; - background-color: white; - opacity: 0.99; - z-index: 1; - overflow: scroll; - width: 400px; + box-shadow: rgba(0, 0, 0, 0.2) 0 2px 8px 5px; + border-style: solid; + border-width: 1px; + border-color: black; + padding-left: 10px; + padding-right: 10px; + padding-top: 10px; + padding-bottom: 10px; + background-color: white; + opacity: 0.99; + z-index: 1; + overflow: scroll; + width: 400px; } .model-detail-popup .code { - background-color: #E4F5FF; - font-family: monospace; - white-space: pre; - margin: 10px; - overflow: auto; + background-color: #E4F5FF; + font-family: monospace; + white-space: pre; + margin: 10px; + overflow: auto; } .model-detail-popup h2 { - margin-top: 0px; - padding-top: 0px; + margin-top: 0px; + padding-top: 0px; } .model-detail-popup li { - padding-bottom: 5px; + padding-bottom: 5px; } .model-detail-popup .param-reqiured-true { - font-family: monospace; - font-weight: bold; - clear: left; - display: block; - float: left; - width: 100%; + font-family: monospace; + font-weight: bold; + clear: left; + display: block; + float: left; + width: 100%; } .model-detail-popup .param-required-false { - font-family: monospace; - clear: left; - display: block; - float: left; - width: 100%; + font-family: monospace; + clear: left; + display: block; + float: left; + width: 100%; } .model-detail-popup .param-description { - margin-left: 50px; - float: left; + margin-left: 50px; + float: left; } .section-header { - border-bottom: 2px; - font-weight: bold; - font-size: 15px; - padding: 6px 0; - color: rgb(57,57,57); + border-bottom: 2px; + font-weight: bold; + font-size: 15px; + padding: 6px 0; + color: rgb(57, 57, 57); } .content { - padding-top: 100px; + padding-top: 100px; } .content h1 { - font-size: 43px; - text-align: center; - margin-top: 40px; - margin-bottom: 40px; + font-size: 43px; + text-align: center; + margin-top: 40px; + margin-bottom: 40px; } .sidebar { - box-sizing: border-box; - float: left; - display: block; - width: 240px; - overflow: scroll; - position: fixed; + box-sizing: border-box; + float: left; + display: block; + width: 240px; + overflow: scroll; + position: fixed; } .section-box { - border-bottom-style: solid; - border-bottom: 10px; + border-bottom-style: solid; + border-bottom: 10px; } .section-box ul li { - list-style: none; - margin-left: 0px; + list-style: none; + margin-left: 0px; } .non-sidebar { - box-sizing: border-box; - display: block; - margin-left: 240px; - margin-right: 0px; - width: 638px; + box-sizing: border-box; + display: block; + margin-left: 240px; + margin-right: 0px; + width: 638px; } .non-sidebar h2 { - clear: left; - padding-top: 20px; + clear: left; + padding-top: 20px; } li.parameter { - list-style: none; - display: block; - padding-left: 1em; + list-style: none; + display: block; + padding-left: 1em; } -.param{ - display: block; +.param { + display: block; } .param-name { - margin-left: 1em; + margin-left: 1em; } .param-in { - font-weight: bold; - font-size: 1.1em; + font-weight: bold; + font-size: 1.1em; } + .param-type { - margin-left: 1em; - font-style: italic; + margin-left: 1em; + font-style: italic; } .param-description { - display: block; - font-family: 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; + display: block; + font-family: 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; } .param-optional-flag { - font-style: italic; + font-style: italic; } .section { - font-weight: normal; - clear: left; + font-weight: normal; + clear: left; } .section a { - text-decoration: underline; + text-decoration: underline; } .code { - background-color: #E4F5FF; - font-family: monospace; - white-space: pre; - margin: 10px; - overflow: auto; - width: 600px; + background-color: #E4F5FF; + font-family: monospace; + white-space: pre; + margin: 10px; + overflow: auto; + width: 600px; } .header { - position: fixed; - text-align: left; - background-color: black; - float: left; - top: 0; - width: 100%; - height: 70px auto; - padding-bottom: 20px; - box-shadow: rgba(0, 0, 0, 0.2) 0 2px 8px 5px; + position: fixed; + text-align: left; + background-color: black; + float: left; + top: 0; + width: 100%; + height: 70px auto; + padding-bottom: 20px; + box-shadow: rgba(0, 0, 0, 0.2) 0 2px 8px 5px; } .top-bar h1 a { - width: auto; + width: auto; } .top-bar h1#logo a { - width: auto; - display: block; - clear: none; - float: left; - background-position: left;; - color: white; - text-decoration: none; + width: auto; + display: block; + clear: none; + float: left; + background-position: left;; + color: white; + text-decoration: none; } .top-bar ul li { - list-style: none; + list-style: none; } .top-bar h1#logo span { - display: block; - clear: none; - float: left; - padding-top: 10px; - padding-left: 10px; - margin: 0px; + display: block; + clear: none; + float: left; + padding-top: 10px; + padding-left: 10px; + margin: 0px; } .top-bar h1#logo a span.light { - color: #ffc97a; - color: #666666; - padding-left: 0px; + color: #ffc97a; + color: #666666; + padding-left: 0px; } .top-bar ul#nav { - float: none; - clear: both; - overflow: hidden; - margin: 0; - padding: 0; - display: block; - float: right; - clear: none; + float: none; + clear: both; + overflow: hidden; + margin: 0; + padding: 0; + display: block; + float: right; + clear: none; } .top-bar ul#nav li { - float: left; - clear: none; - margin: 0; - padding: 2px 10px; - border-right: 1px solid #dddddd; + float: left; + clear: none; + margin: 0; + padding: 2px 10px; + border-right: 1px solid #dddddd; } .top-bar ul#nav li:first-child, .top-bar ul#nav li.first { - padding-left: 0; + padding-left: 0; } .top-bar ul#nav li:last-child, .top-bar ul#nav li.last { - padding-right: 0; - border-right: none; + padding-right: 0; + border-right: none; } .top-bar ul#nav li { - border: none; - padding: 0 5px; + border: none; + padding: 0 5px; } .top-bar ul#nav li a { - display: block; - padding: 8px 10px 8px 10px; - color: #999999; - text-decoration: none; + display: block; + padding: 8px 10px 8px 10px; + color: #999999; + text-decoration: none; } .top-bar ul#nav li a.strong { - color: white; + color: white; } .top-bar ul#nav li a:active, .top-bar ul#nav li a.active, .top-bar ul#nav li a:hover { - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - -o-border-radius: 4px; - -ms-border-radius: 4px; - -khtml-border-radius: 4px; - border-radius: 4px; - background-image: -webkit-gradient(linear, 0% 100%, 0% 0%, color-stop(0%, #ff5401), color-stop(100%, #ffa014)); - background-image: -moz-linear-gradient(bottom, #ff5401 0%, #ffa014 100%); - background-image: linear-gradient(bottom, #ff5401 0%, #ffa014 100%); - color: white; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -o-border-radius: 4px; + -ms-border-radius: 4px; + -khtml-border-radius: 4px; + border-radius: 4px; + background-image: -webkit-gradient(linear, 0% 100%, 0% 0%, color-stop(0%, #ff5401), color-stop(100%, #ffa014)); + background-image: -moz-linear-gradient(bottom, #ff5401 0%, #ffa014 100%); + background-image: linear-gradient(bottom, #ff5401 0%, #ffa014 100%); + color: white; } .top-bar ul#nav:hover li { - border-color: #222222; + border-color: #222222; } diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/bootstrap.js b/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/bootstrap.js index 6c15a583296..96bc4e8c103 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/bootstrap.js +++ b/modules/swagger-codegen/src/main/resources/swagger-static/assets/js/bootstrap.js @@ -20,44 +20,45 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) - * ======================================================= */ + /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) + * ======================================================= */ - $(function () { + $(function () { - $.support.transition = (function () { + $.support.transition = (function () { - var transitionEnd = (function () { + var transitionEnd = (function () { - var el = document.createElement('bootstrap') - , transEndEventNames = { - 'WebkitTransition' : 'webkitTransitionEnd' - , 'MozTransition' : 'transitionend' - , 'OTransition' : 'oTransitionEnd otransitionend' - , 'transition' : 'transitionend' - } - , name + var el = document.createElement('bootstrap') + , transEndEventNames = { + 'WebkitTransition': 'webkitTransitionEnd' + , 'MozTransition': 'transitionend' + , 'OTransition': 'oTransitionEnd otransitionend' + , 'transition': 'transitionend' + } + , name - for (name in transEndEventNames){ - if (el.style[name] !== undefined) { - return transEndEventNames[name] - } - } + for (name in transEndEventNames) { + if (el.style[name] !== undefined) { + return transEndEventNames[name] + } + } - }()) + }()) - return transitionEnd && { - end: transitionEnd - } + return transitionEnd && { + end: transitionEnd + } - })() + })() - }) + }) -}(window.jQuery);/* ========================================================== +}(window.jQuery); +/* ========================================================== * bootstrap-alert.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== @@ -79,83 +80,84 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* ALERT CLASS DEFINITION - * ====================== */ + /* ALERT CLASS DEFINITION + * ====================== */ - var dismiss = '[data-dismiss="alert"]' - , Alert = function (el) { - $(el).on('click', dismiss, this.close) - } + var dismiss = '[data-dismiss="alert"]' + , Alert = function (el) { + $(el).on('click', dismiss, this.close) + } - Alert.prototype.close = function (e) { - var $this = $(this) - , selector = $this.attr('data-target') - , $parent + Alert.prototype.close = function (e) { + var $this = $(this) + , selector = $this.attr('data-target') + , $parent - if (!selector) { - selector = $this.attr('href') - selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + } + + $parent = $(selector) + + e && e.preventDefault() + + $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) + + $parent.trigger(e = $.Event('close')) + + if (e.isDefaultPrevented()) return + + $parent.removeClass('in') + + function removeElement() { + $parent + .trigger('closed') + .remove() + } + + $.support.transition && $parent.hasClass('fade') ? + $parent.on($.support.transition.end, removeElement) : + removeElement() } - $parent = $(selector) - e && e.preventDefault() + /* ALERT PLUGIN DEFINITION + * ======================= */ - $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) + var old = $.fn.alert - $parent.trigger(e = $.Event('close')) - - if (e.isDefaultPrevented()) return - - $parent.removeClass('in') - - function removeElement() { - $parent - .trigger('closed') - .remove() + $.fn.alert = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('alert') + if (!data) $this.data('alert', (data = new Alert(this))) + if (typeof option == 'string') data[option].call($this) + }) } - $.support.transition && $parent.hasClass('fade') ? - $parent.on($.support.transition.end, removeElement) : - removeElement() - } + $.fn.alert.Constructor = Alert - /* ALERT PLUGIN DEFINITION - * ======================= */ + /* ALERT NO CONFLICT + * ================= */ - var old = $.fn.alert - - $.fn.alert = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('alert') - if (!data) $this.data('alert', (data = new Alert(this))) - if (typeof option == 'string') data[option].call($this) - }) - } - - $.fn.alert.Constructor = Alert + $.fn.alert.noConflict = function () { + $.fn.alert = old + return this + } - /* ALERT NO CONFLICT - * ================= */ + /* ALERT DATA-API + * ============== */ - $.fn.alert.noConflict = function () { - $.fn.alert = old - return this - } + $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) - - /* ALERT DATA-API - * ============== */ - - $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) - -}(window.jQuery);/* ============================================================ +}(window.jQuery); +/* ============================================================ * bootstrap-button.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ @@ -177,89 +179,90 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* BUTTON PUBLIC CLASS DEFINITION - * ============================== */ + /* BUTTON PUBLIC CLASS DEFINITION + * ============================== */ - var Button = function (element, options) { - this.$element = $(element) - this.options = $.extend({}, $.fn.button.defaults, options) - } + var Button = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, $.fn.button.defaults, options) + } - Button.prototype.setState = function (state) { - var d = 'disabled' - , $el = this.$element - , data = $el.data() - , val = $el.is('input') ? 'val' : 'html' + Button.prototype.setState = function (state) { + var d = 'disabled' + , $el = this.$element + , data = $el.data() + , val = $el.is('input') ? 'val' : 'html' - state = state + 'Text' - data.resetText || $el.data('resetText', $el[val]()) + state = state + 'Text' + data.resetText || $el.data('resetText', $el[val]()) - $el[val](data[state] || this.options[state]) + $el[val](data[state] || this.options[state]) - // push to event loop to allow forms to submit - setTimeout(function () { - state == 'loadingText' ? - $el.addClass(d).attr(d, d) : - $el.removeClass(d).removeAttr(d) - }, 0) - } + // push to event loop to allow forms to submit + setTimeout(function () { + state == 'loadingText' ? + $el.addClass(d).attr(d, d) : + $el.removeClass(d).removeAttr(d) + }, 0) + } - Button.prototype.toggle = function () { - var $parent = this.$element.closest('[data-toggle="buttons-radio"]') + Button.prototype.toggle = function () { + var $parent = this.$element.closest('[data-toggle="buttons-radio"]') - $parent && $parent - .find('.active') - .removeClass('active') + $parent && $parent + .find('.active') + .removeClass('active') - this.$element.toggleClass('active') - } + this.$element.toggleClass('active') + } - /* BUTTON PLUGIN DEFINITION - * ======================== */ + /* BUTTON PLUGIN DEFINITION + * ======================== */ - var old = $.fn.button + var old = $.fn.button - $.fn.button = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('button') - , options = typeof option == 'object' && option - if (!data) $this.data('button', (data = new Button(this, options))) - if (option == 'toggle') data.toggle() - else if (option) data.setState(option) + $.fn.button = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('button') + , options = typeof option == 'object' && option + if (!data) $this.data('button', (data = new Button(this, options))) + if (option == 'toggle') data.toggle() + else if (option) data.setState(option) + }) + } + + $.fn.button.defaults = { + loadingText: 'loading...' + } + + $.fn.button.Constructor = Button + + + /* BUTTON NO CONFLICT + * ================== */ + + $.fn.button.noConflict = function () { + $.fn.button = old + return this + } + + + /* BUTTON DATA-API + * =============== */ + + $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { + var $btn = $(e.target) + if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') + $btn.button('toggle') }) - } - $.fn.button.defaults = { - loadingText: 'loading...' - } - - $.fn.button.Constructor = Button - - - /* BUTTON NO CONFLICT - * ================== */ - - $.fn.button.noConflict = function () { - $.fn.button = old - return this - } - - - /* BUTTON DATA-API - * =============== */ - - $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { - var $btn = $(e.target) - if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') - $btn.button('toggle') - }) - -}(window.jQuery);/* ========================================================== +}(window.jQuery); +/* ========================================================== * bootstrap-carousel.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== @@ -281,169 +284,172 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* CAROUSEL CLASS DEFINITION - * ========================= */ + /* CAROUSEL CLASS DEFINITION + * ========================= */ - var Carousel = function (element, options) { - this.$element = $(element) - this.options = options - this.options.pause == 'hover' && this.$element - .on('mouseenter', $.proxy(this.pause, this)) - .on('mouseleave', $.proxy(this.cycle, this)) - } - - Carousel.prototype = { - - cycle: function (e) { - if (!e) this.paused = false - this.options.interval - && !this.paused - && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) - return this + var Carousel = function (element, options) { + this.$element = $(element) + this.options = options + this.options.pause == 'hover' && this.$element + .on('mouseenter', $.proxy(this.pause, this)) + .on('mouseleave', $.proxy(this.cycle, this)) } - , to: function (pos) { - var $active = this.$element.find('.item.active') - , children = $active.parent().children() - , activePos = children.index($active) - , that = this + Carousel.prototype = { - if (pos > (children.length - 1) || pos < 0) return + cycle: function (e) { + if (!e) this.paused = false + this.options.interval + && !this.paused + && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) + return this + } - if (this.sliding) { - return this.$element.one('slid', function () { - that.to(pos) + , to: function (pos) { + var $active = this.$element.find('.item.active') + , children = $active.parent().children() + , activePos = children.index($active) + , that = this + + if (pos > (children.length - 1) || pos < 0) return + + if (this.sliding) { + return this.$element.one('slid', function () { + that.to(pos) + }) + } + + if (activePos == pos) { + return this.pause().cycle() + } + + return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) + } + + , pause: function (e) { + if (!e) this.paused = true + if (this.$element.find('.next, .prev').length && $.support.transition.end) { + this.$element.trigger($.support.transition.end) + this.cycle() + } + clearInterval(this.interval) + this.interval = null + return this + } + + , next: function () { + if (this.sliding) return + return this.slide('next') + } + + , prev: function () { + if (this.sliding) return + return this.slide('prev') + } + + , slide: function (type, next) { + var $active = this.$element.find('.item.active') + , $next = next || $active[type]() + , isCycling = this.interval + , direction = type == 'next' ? 'left' : 'right' + , fallback = type == 'next' ? 'first' : 'last' + , that = this + , e + + this.sliding = true + + isCycling && this.pause() + + $next = $next.length ? $next : this.$element.find('.item')[fallback]() + + e = $.Event('slide', { + relatedTarget: $next[0] + }) + + if ($next.hasClass('active')) return + + if ($.support.transition && this.$element.hasClass('slide')) { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $next.addClass(type) + $next[0].offsetWidth // force reflow + $active.addClass(direction) + $next.addClass(direction) + this.$element.one($.support.transition.end, function () { + $next.removeClass([type, direction].join(' ')).addClass('active') + $active.removeClass(['active', direction].join(' ')) + that.sliding = false + setTimeout(function () { + that.$element.trigger('slid') + }, 0) + }) + } else { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + $active.removeClass('active') + $next.addClass('active') + this.sliding = false + this.$element.trigger('slid') + } + + isCycling && this.cycle() + + return this + } + + } + + + /* CAROUSEL PLUGIN DEFINITION + * ========================== */ + + var old = $.fn.carousel + + $.fn.carousel = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('carousel') + , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) + , action = typeof option == 'string' ? option : options.slide + if (!data) $this.data('carousel', (data = new Carousel(this, options))) + if (typeof option == 'number') data.to(option) + else if (action) data[action]() + else if (options.interval) data.cycle() }) - } - - if (activePos == pos) { - return this.pause().cycle() - } - - return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) } - , pause: function (e) { - if (!e) this.paused = true - if (this.$element.find('.next, .prev').length && $.support.transition.end) { - this.$element.trigger($.support.transition.end) - this.cycle() - } - clearInterval(this.interval) - this.interval = null - return this + $.fn.carousel.defaults = { + interval: 5000 + , pause: 'hover' } - , next: function () { - if (this.sliding) return - return this.slide('next') + $.fn.carousel.Constructor = Carousel + + + /* CAROUSEL NO CONFLICT + * ==================== */ + + $.fn.carousel.noConflict = function () { + $.fn.carousel = old + return this } - , prev: function () { - if (this.sliding) return - return this.slide('prev') - } + /* CAROUSEL DATA-API + * ================= */ - , slide: function (type, next) { - var $active = this.$element.find('.item.active') - , $next = next || $active[type]() - , isCycling = this.interval - , direction = type == 'next' ? 'left' : 'right' - , fallback = type == 'next' ? 'first' : 'last' - , that = this - , e - - this.sliding = true - - isCycling && this.pause() - - $next = $next.length ? $next : this.$element.find('.item')[fallback]() - - e = $.Event('slide', { - relatedTarget: $next[0] - }) - - if ($next.hasClass('active')) return - - if ($.support.transition && this.$element.hasClass('slide')) { - this.$element.trigger(e) - if (e.isDefaultPrevented()) return - $next.addClass(type) - $next[0].offsetWidth // force reflow - $active.addClass(direction) - $next.addClass(direction) - this.$element.one($.support.transition.end, function () { - $next.removeClass([type, direction].join(' ')).addClass('active') - $active.removeClass(['active', direction].join(' ')) - that.sliding = false - setTimeout(function () { that.$element.trigger('slid') }, 0) - }) - } else { - this.$element.trigger(e) - if (e.isDefaultPrevented()) return - $active.removeClass('active') - $next.addClass('active') - this.sliding = false - this.$element.trigger('slid') - } - - isCycling && this.cycle() - - return this - } - - } - - - /* CAROUSEL PLUGIN DEFINITION - * ========================== */ - - var old = $.fn.carousel - - $.fn.carousel = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('carousel') - , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) - , action = typeof option == 'string' ? option : options.slide - if (!data) $this.data('carousel', (data = new Carousel(this, options))) - if (typeof option == 'number') data.to(option) - else if (action) data[action]() - else if (options.interval) data.cycle() + $(document).on('click.carousel.data-api', '[data-slide]', function (e) { + var $this = $(this), href + , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 + , options = $.extend({}, $target.data(), $this.data()) + $target.carousel(options) + e.preventDefault() }) - } - $.fn.carousel.defaults = { - interval: 5000 - , pause: 'hover' - } - - $.fn.carousel.Constructor = Carousel - - - /* CAROUSEL NO CONFLICT - * ==================== */ - - $.fn.carousel.noConflict = function () { - $.fn.carousel = old - return this - } - - /* CAROUSEL DATA-API - * ================= */ - - $(document).on('click.carousel.data-api', '[data-slide]', function (e) { - var $this = $(this), href - , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 - , options = $.extend({}, $target.data(), $this.data()) - $target.carousel(options) - e.preventDefault() - }) - -}(window.jQuery);/* ============================================================= +}(window.jQuery); +/* ============================================================= * bootstrap-collapse.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= @@ -465,151 +471,152 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* COLLAPSE PUBLIC CLASS DEFINITION - * ================================ */ + /* COLLAPSE PUBLIC CLASS DEFINITION + * ================================ */ - var Collapse = function (element, options) { - this.$element = $(element) - this.options = $.extend({}, $.fn.collapse.defaults, options) + var Collapse = function (element, options) { + this.$element = $(element) + this.options = $.extend({}, $.fn.collapse.defaults, options) - if (this.options.parent) { - this.$parent = $(this.options.parent) + if (this.options.parent) { + this.$parent = $(this.options.parent) + } + + this.options.toggle && this.toggle() } - this.options.toggle && this.toggle() - } + Collapse.prototype = { - Collapse.prototype = { + constructor: Collapse - constructor: Collapse + , dimension: function () { + var hasWidth = this.$element.hasClass('width') + return hasWidth ? 'width' : 'height' + } + + , show: function () { + var dimension + , scroll + , actives + , hasData + + if (this.transitioning) return + + dimension = this.dimension() + scroll = $.camelCase(['scroll', dimension].join('-')) + actives = this.$parent && this.$parent.find('> .accordion-group > .in') + + if (actives && actives.length) { + hasData = actives.data('collapse') + if (hasData && hasData.transitioning) return + actives.collapse('hide') + hasData || actives.data('collapse', null) + } + + this.$element[dimension](0) + this.transition('addClass', $.Event('show'), 'shown') + $.support.transition && this.$element[dimension](this.$element[0][scroll]) + } + + , hide: function () { + var dimension + if (this.transitioning) return + dimension = this.dimension() + this.reset(this.$element[dimension]()) + this.transition('removeClass', $.Event('hide'), 'hidden') + this.$element[dimension](0) + } + + , reset: function (size) { + var dimension = this.dimension() + + this.$element + .removeClass('collapse') + [dimension](size || 'auto') + [0].offsetWidth + + this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') + + return this + } + + , transition: function (method, startEvent, completeEvent) { + var that = this + , complete = function () { + if (startEvent.type == 'show') that.reset() + that.transitioning = 0 + that.$element.trigger(completeEvent) + } + + this.$element.trigger(startEvent) + + if (startEvent.isDefaultPrevented()) return + + this.transitioning = 1 + + this.$element[method]('in') + + $.support.transition && this.$element.hasClass('collapse') ? + this.$element.one($.support.transition.end, complete) : + complete() + } + + , toggle: function () { + this[this.$element.hasClass('in') ? 'hide' : 'show']() + } - , dimension: function () { - var hasWidth = this.$element.hasClass('width') - return hasWidth ? 'width' : 'height' } - , show: function () { - var dimension - , scroll - , actives - , hasData - if (this.transitioning) return + /* COLLAPSE PLUGIN DEFINITION + * ========================== */ - dimension = this.dimension() - scroll = $.camelCase(['scroll', dimension].join('-')) - actives = this.$parent && this.$parent.find('> .accordion-group > .in') + var old = $.fn.collapse - if (actives && actives.length) { - hasData = actives.data('collapse') - if (hasData && hasData.transitioning) return - actives.collapse('hide') - hasData || actives.data('collapse', null) - } - - this.$element[dimension](0) - this.transition('addClass', $.Event('show'), 'shown') - $.support.transition && this.$element[dimension](this.$element[0][scroll]) + $.fn.collapse = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('collapse') + , options = typeof option == 'object' && option + if (!data) $this.data('collapse', (data = new Collapse(this, options))) + if (typeof option == 'string') data[option]() + }) } - , hide: function () { - var dimension - if (this.transitioning) return - dimension = this.dimension() - this.reset(this.$element[dimension]()) - this.transition('removeClass', $.Event('hide'), 'hidden') - this.$element[dimension](0) + $.fn.collapse.defaults = { + toggle: true } - , reset: function (size) { - var dimension = this.dimension() + $.fn.collapse.Constructor = Collapse - this.$element - .removeClass('collapse') - [dimension](size || 'auto') - [0].offsetWidth - this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') + /* COLLAPSE NO CONFLICT + * ==================== */ - return this + $.fn.collapse.noConflict = function () { + $.fn.collapse = old + return this } - , transition: function (method, startEvent, completeEvent) { - var that = this - , complete = function () { - if (startEvent.type == 'show') that.reset() - that.transitioning = 0 - that.$element.trigger(completeEvent) - } - this.$element.trigger(startEvent) + /* COLLAPSE DATA-API + * ================= */ - if (startEvent.isDefaultPrevented()) return - - this.transitioning = 1 - - this.$element[method]('in') - - $.support.transition && this.$element.hasClass('collapse') ? - this.$element.one($.support.transition.end, complete) : - complete() - } - - , toggle: function () { - this[this.$element.hasClass('in') ? 'hide' : 'show']() - } - - } - - - /* COLLAPSE PLUGIN DEFINITION - * ========================== */ - - var old = $.fn.collapse - - $.fn.collapse = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('collapse') - , options = typeof option == 'object' && option - if (!data) $this.data('collapse', (data = new Collapse(this, options))) - if (typeof option == 'string') data[option]() + $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { + var $this = $(this), href + , target = $this.attr('data-target') + || e.preventDefault() + || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 + , option = $(target).data('collapse') ? 'toggle' : $this.data() + $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') + $(target).collapse(option) }) - } - $.fn.collapse.defaults = { - toggle: true - } - - $.fn.collapse.Constructor = Collapse - - - /* COLLAPSE NO CONFLICT - * ==================== */ - - $.fn.collapse.noConflict = function () { - $.fn.collapse = old - return this - } - - - /* COLLAPSE DATA-API - * ================= */ - - $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { - var $this = $(this), href - , target = $this.attr('data-target') - || e.preventDefault() - || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 - , option = $(target).data('collapse') ? 'toggle' : $this.data() - $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') - $(target).collapse(option) - }) - -}(window.jQuery);/* ============================================================ +}(window.jQuery); +/* ============================================================ * bootstrap-dropdown.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ @@ -631,145 +638,150 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* DROPDOWN CLASS DEFINITION - * ========================= */ + /* DROPDOWN CLASS DEFINITION + * ========================= */ - var toggle = '[data-toggle=dropdown]' - , Dropdown = function (element) { - var $el = $(element).on('click.dropdown.data-api', this.toggle) - $('html').on('click.dropdown.data-api', function () { - $el.parent().removeClass('open') + var toggle = '[data-toggle=dropdown]' + , Dropdown = function (element) { + var $el = $(element).on('click.dropdown.data-api', this.toggle) + $('html').on('click.dropdown.data-api', function () { + $el.parent().removeClass('open') + }) + } + + Dropdown.prototype = { + + constructor: Dropdown + + , toggle: function (e) { + var $this = $(this) + , $parent + , isActive + + if ($this.is('.disabled, :disabled')) return + + $parent = getParent($this) + + isActive = $parent.hasClass('open') + + clearMenus() + + if (!isActive) { + $parent.toggleClass('open') + } + + $this.focus() + + return false + } + + , keydown: function (e) { + var $this + , $items + , $active + , $parent + , isActive + , index + + if (!/(38|40|27)/.test(e.keyCode)) return + + $this = $(this) + + e.preventDefault() + e.stopPropagation() + + if ($this.is('.disabled, :disabled')) return + + $parent = getParent($this) + + isActive = $parent.hasClass('open') + + if (!isActive || (isActive && e.keyCode == 27)) return $this.click() + + $items = $('[role=menu] li:not(.divider):visible a', $parent) + + if (!$items.length) return + + index = $items.index($items.filter(':focus')) + + if (e.keyCode == 38 && index > 0) index-- // up + if (e.keyCode == 40 && index < $items.length - 1) index++ // down + if (!~index) index = 0 + + $items + .eq(index) + .focus() + } + + } + + function clearMenus() { + $(toggle).each(function () { + getParent($(this)).removeClass('open') }) - } - - Dropdown.prototype = { - - constructor: Dropdown - - , toggle: function (e) { - var $this = $(this) - , $parent - , isActive - - if ($this.is('.disabled, :disabled')) return - - $parent = getParent($this) - - isActive = $parent.hasClass('open') - - clearMenus() - - if (!isActive) { - $parent.toggleClass('open') - } - - $this.focus() - - return false } - , keydown: function (e) { - var $this - , $items - , $active - , $parent - , isActive - , index + function getParent($this) { + var selector = $this.attr('data-target') + , $parent - if (!/(38|40|27)/.test(e.keyCode)) return + if (!selector) { + selector = $this.attr('href') + selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + } - $this = $(this) + $parent = $(selector) + $parent.length || ($parent = $this.parent()) - e.preventDefault() - e.stopPropagation() - - if ($this.is('.disabled, :disabled')) return - - $parent = getParent($this) - - isActive = $parent.hasClass('open') - - if (!isActive || (isActive && e.keyCode == 27)) return $this.click() - - $items = $('[role=menu] li:not(.divider):visible a', $parent) - - if (!$items.length) return - - index = $items.index($items.filter(':focus')) - - if (e.keyCode == 38 && index > 0) index-- // up - if (e.keyCode == 40 && index < $items.length - 1) index++ // down - if (!~index) index = 0 - - $items - .eq(index) - .focus() + return $parent } - } - function clearMenus() { - $(toggle).each(function () { - getParent($(this)).removeClass('open') - }) - } + /* DROPDOWN PLUGIN DEFINITION + * ========================== */ - function getParent($this) { - var selector = $this.attr('data-target') - , $parent + var old = $.fn.dropdown - if (!selector) { - selector = $this.attr('href') - selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + $.fn.dropdown = function (option) { + return this.each(function () { + var $this = $(this) + , data = $this.data('dropdown') + if (!data) $this.data('dropdown', (data = new Dropdown(this))) + if (typeof option == 'string') data[option].call($this) + }) } - $parent = $(selector) - $parent.length || ($parent = $this.parent()) - - return $parent - } + $.fn.dropdown.Constructor = Dropdown - /* DROPDOWN PLUGIN DEFINITION - * ========================== */ + /* DROPDOWN NO CONFLICT + * ==================== */ - var old = $.fn.dropdown - - $.fn.dropdown = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('dropdown') - if (!data) $this.data('dropdown', (data = new Dropdown(this))) - if (typeof option == 'string') data[option].call($this) - }) - } - - $.fn.dropdown.Constructor = Dropdown + $.fn.dropdown.noConflict = function () { + $.fn.dropdown = old + return this + } - /* DROPDOWN NO CONFLICT - * ==================== */ + /* APPLY TO STANDARD DROPDOWN ELEMENTS + * =================================== */ - $.fn.dropdown.noConflict = function () { - $.fn.dropdown = old - return this - } + $(document) + .on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus) + .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { + e.stopPropagation() + }) + .on('touchstart.dropdown.data-api', '.dropdown-menu', function (e) { + e.stopPropagation() + }) + .on('click.dropdown.data-api touchstart.dropdown.data-api', toggle, Dropdown.prototype.toggle) + .on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]', Dropdown.prototype.keydown) - - /* APPLY TO STANDARD DROPDOWN ELEMENTS - * =================================== */ - - $(document) - .on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus) - .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) - .on('touchstart.dropdown.data-api', '.dropdown-menu', function (e) { e.stopPropagation() }) - .on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle) - .on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) - -}(window.jQuery);/* ========================================================= +}(window.jQuery); +/* ========================================================= * bootstrap-modal.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= @@ -791,227 +803,229 @@ !function ($) { - "use strict"; // jshint ;_; + "use strict"; // jshint ;_; - /* MODAL CLASS DEFINITION - * ====================== */ + /* MODAL CLASS DEFINITION + * ====================== */ - var Modal = function (element, options) { - this.options = options - this.$element = $(element) - .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) - this.options.remote && this.$element.find('.modal-body').load(this.options.remote) - } + var Modal = function (element, options) { + this.options = options + this.$element = $(element) + .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) + this.options.remote && this.$element.find('.modal-body').load(this.options.remote) + } - Modal.prototype = { + Modal.prototype = { - constructor: Modal + constructor: Modal - , toggle: function () { - return this[!this.isShown ? 'show' : 'hide']() - } - - , show: function () { - var that = this - , e = $.Event('show') - - this.$element.trigger(e) - - if (this.isShown || e.isDefaultPrevented()) return - - this.isShown = true - - this.escape() - - this.backdrop(function () { - var transition = $.support.transition && that.$element.hasClass('fade') - - if (!that.$element.parent().length) { - that.$element.appendTo(document.body) //don't move modals dom position - } - - that.$element - .show() - - if (transition) { - that.$element[0].offsetWidth // force reflow - } - - that.$element - .addClass('in') - .attr('aria-hidden', false) - - that.enforceFocus() - - transition ? - that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : - that.$element.focus().trigger('shown') - - }) - } - - , hide: function (e) { - e && e.preventDefault() - - var that = this - - e = $.Event('hide') - - this.$element.trigger(e) - - if (!this.isShown || e.isDefaultPrevented()) return - - this.isShown = false - - this.escape() - - $(document).off('focusin.modal') - - this.$element - .removeClass('in') - .attr('aria-hidden', true) - - $.support.transition && this.$element.hasClass('fade') ? - this.hideWithTransition() : - this.hideModal() - } - - , enforceFocus: function () { - var that = this - $(document).on('focusin.modal', function (e) { - if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { - that.$element.focus() - } - }) - } - - , escape: function () { - var that = this - if (this.isShown && this.options.keyboard) { - this.$element.on('keyup.dismiss.modal', function ( e ) { - e.which == 27 && that.hide() - }) - } else if (!this.isShown) { - this.$element.off('keyup.dismiss.modal') + , toggle: function () { + return this[!this.isShown ? 'show' : 'hide']() } - } - , hideWithTransition: function () { - var that = this - , timeout = setTimeout(function () { - that.$element.off($.support.transition.end) - that.hideModal() - }, 500) + , show: function () { + var that = this + , e = $.Event('show') - this.$element.one($.support.transition.end, function () { - clearTimeout(timeout) - that.hideModal() - }) - } + this.$element.trigger(e) - , hideModal: function (that) { - this.$element - .hide() - .trigger('hidden') + if (this.isShown || e.isDefaultPrevented()) return - this.backdrop() - } + this.isShown = true - , removeBackdrop: function () { - this.$backdrop.remove() - this.$backdrop = null - } + this.escape() - , backdrop: function (callback) { - var that = this - , animate = this.$element.hasClass('fade') ? 'fade' : '' + this.backdrop(function () { + var transition = $.support.transition && that.$element.hasClass('fade') - if (this.isShown && this.options.backdrop) { - var doAnimate = $.support.transition && animate + if (!that.$element.parent().length) { + that.$element.appendTo(document.body) //don't move modals dom position + } - this.$backdrop = $('