From 18eb3cde97c89c62a8ec1875b85bd3670fd3695e Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 6 Jun 2015 23:11:20 -0700 Subject: [PATCH 01/22] updated files --- modules/swagger-codegen/pom.xml | 19 +- .../swagger/codegen/AbstractGenerator.java | 60 - .../wordnik/swagger/codegen/CliOption.java | 23 - .../swagger/codegen/ClientOptInput.java | 104 -- .../wordnik/swagger/codegen/ClientOpts.java | 52 - .../com/wordnik/swagger/codegen/Codegen.java | 143 -- .../swagger/codegen/CodegenConfig.java | 64 - .../wordnik/swagger/codegen/CodegenModel.java | 16 - .../swagger/codegen/CodegenModelFactory.java | 38 - .../swagger/codegen/CodegenModelType.java | 21 - .../swagger/codegen/CodegenOperation.java | 32 - .../swagger/codegen/CodegenParameter.java | 41 - .../swagger/codegen/CodegenProperty.java | 28 - .../swagger/codegen/CodegenResponse.java | 21 - .../swagger/codegen/CodegenSecurity.java | 10 - .../wordnik/swagger/codegen/CodegenType.java | 34 - .../swagger/codegen/DefaultCodegen.java | 1277 ----------------- .../swagger/codegen/DefaultGenerator.java | 487 ------- .../wordnik/swagger/codegen/Generator.java | 11 - .../swagger/codegen/MetaGenerator.java | 185 --- .../swagger/codegen/SupportingFile.java | 13 - .../swagger/codegen/auth/AuthMethod.java | 6 - .../codegen/examples/ExampleGenerator.java | 175 --- .../codegen/examples/XmlExampleGenerator.java | 206 --- .../languages/AkkaScalaClientCodegen.java | 365 ----- .../languages/AndroidClientCodegen.java | 259 ---- .../languages/AsyncScalaClientCodegen.java | 194 --- .../languages/CSharpClientCodegen.java | 192 --- .../codegen/languages/JavaClientCodegen.java | 241 ---- .../codegen/languages/JaxRSServerCodegen.java | 200 --- .../languages/NodeJSServerCodegen.java | 196 --- .../codegen/languages/ObjcClientCodegen.java | 347 ----- .../codegen/languages/PerlClientCodegen.java | 200 --- .../codegen/languages/PhpClientCodegen.java | 184 --- .../languages/Python3ClientCodegen.java | 198 --- .../languages/PythonClientCodegen.java | 215 --- .../codegen/languages/Qt5CPPGenerator.java | 308 ---- .../languages/RetrofitClientCodegen.java | 190 --- .../codegen/languages/RubyClientCodegen.java | 220 --- .../codegen/languages/ScalaClientCodegen.java | 203 --- .../languages/ScalatraServerCodegen.java | 178 --- .../languages/SpringMVCServerCodegen.java | 165 --- .../codegen/languages/StaticDocCodegen.java | 76 - .../languages/StaticHtmlGenerator.java | 97 -- .../codegen/languages/SwaggerGenerator.java | 45 - .../languages/SwaggerYamlGenerator.java | 44 - .../codegen/languages/SwiftGenerator.java | 250 ---- .../codegen/languages/TizenClientCodegen.java | 258 ---- .../src/test/scala/ClientAuthInputTest.scala | 4 +- .../src/test/scala/CodegenTest.scala | 4 +- .../src/test/scala/ExampleGeneratorTest.scala | 14 +- .../test/scala/Java/JavaInheritanceTest.scala | 10 +- .../test/scala/Java/JavaModelEnumTest.scala | 6 +- .../src/test/scala/Java/JavaModelTest.scala | 8 +- .../src/test/scala/Objc/ObjcModelTest.scala | 8 +- .../src/test/scala/SwaggerMigratorTest.scala | 4 +- .../src/test/scala/php/PhpModelTest.scala | 8 +- .../src/test/scala/python/PythonTest.scala | 2 +- .../src/test/scala/scala/ScalaModelTest.scala | 10 +- .../staticDocs/StaticOperationTest.scala | 8 +- 60 files changed, 57 insertions(+), 7920 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/AbstractGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CliOption.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/MetaGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java delete mode 100755 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Python3ClientCodegen.java delete mode 100755 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RetrofitClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SpringMVCServerCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 2db20e67a2d..5debeeb2570 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -1,8 +1,8 @@ - com.wordnik + io.swagger swagger-codegen-project - 2.1.1-M2-SNAPSHOT + 2.1.1 ../.. 4.0.0 @@ -52,7 +52,7 @@ - com.wordnik.swagger.codegen.Codegen + io.swagger.codegen.Codegen @@ -125,7 +125,7 @@ development ${project.url} ${project.version} - com.wordnik + io.swagger @@ -178,7 +178,9 @@ - + + ${scala-version} + org.codehaus.mojo @@ -277,6 +279,7 @@ io.swagger swagger-parser ${swagger-parser-version} + compile io.swagger @@ -334,6 +337,12 @@ ${scala-test-version} test + + org.scala-lang + scala-library + ${scala-version} + test + diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/AbstractGenerator.java deleted file mode 100644 index fa5131dbdc2..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/AbstractGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.samskivert.mustache.*; - -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); - - 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; - } - - 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); - } - - 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); - } - - 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/com/wordnik/swagger/codegen/CliOption.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CliOption.java deleted file mode 100644 index 8ea0b60db26..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CliOption.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.wordnik.swagger.codegen; - -public class CliOption { - private final String opt; - private String description; - - public CliOption(String opt, String description) { - this.opt = opt; - this.description = description; - } - - public String getOpt() { - return opt; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java deleted file mode 100644 index 34d6000e303..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.codegen.ClientOpts; -import com.wordnik.swagger.annotations.*; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.models.auth.AuthorizationValue; - -import java.util.*; -import java.net.URLEncoder; -import java.net.URLDecoder; - -public class ClientOptInput { - private ClientOpts opts; - private Swagger swagger; - private List auths; - protected CodegenConfig config; - - public ClientOptInput swagger(Swagger swagger) { - this.setSwagger(swagger); - return this; - } - public ClientOptInput opts(ClientOpts opts) { - this.setOpts(opts); - return this; - } - - public 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 String getAuth() { - if(auths != null) { - StringBuilder b = new StringBuilder(); - for(AuthorizationValue v : auths) { - try { - if(b.toString().length() > 0) - b.append(","); - b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) - .append(":") - .append(URLEncoder.encode(v.getValue(), "UTF-8")); - } - catch (Exception e) { - // continue - e.printStackTrace(); - } - } - return b.toString(); - } - else - return null; - } - public List getAuthorizationValues() { - return auths; - } - - public CodegenConfig getConfig() { - return config; - } - public void setConfig(CodegenConfig config) { - this.config = config; - } - - public void setOpts(ClientOpts opts) { - this.opts = opts; - } - - public ClientOpts getOpts() { - return opts; - } - - public void setSwagger(Swagger swagger) { - this.swagger = swagger; - } - - @ApiModelProperty(dataType="Object") - public Swagger getSwagger() { - return swagger; - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java deleted file mode 100644 index b8d681cc307..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.codegen.auth.*; - -import java.util.*; - -public class ClientOpts { - 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 getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - - 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/com/wordnik/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java deleted file mode 100644 index c28031a9f27..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.codegen.languages.*; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.models.auth.AuthorizationValue; -import com.wordnik.swagger.util.*; - -import io.swagger.parser.SwaggerParser; - -import org.apache.commons.cli.*; - -import java.io.File; -import java.util.*; - -/** - * @deprecated use instead {@link com.wordnik.swagger.codegen.DefaultGenerator} - * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 - */ -@Deprecated -public class Codegen extends DefaultGenerator { - static Map configs = new HashMap(); - static String configString; - 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(); - } - } - - 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(); - - 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; - - 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()); - 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; - } - 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()); - } - return output; - } - - 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); - } - 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); - } - } - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java deleted file mode 100644 index b112923b6d7..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; - -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); - - Set reservedWords(); - - List supportingFiles(); - - void setOutputDir(String dir); - String getOutputDir(); - - 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/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java deleted file mode 100644 index d1bfc90ba2a..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; - -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; -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java deleted file mode 100644 index b369623f37c..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.wordnik.swagger.codegen; - -import java.util.HashMap; -import java.util.Map; - -public final class CodegenModelFactory { - - 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()); - } - 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); - } - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java deleted file mode 100644 index 62f515b6c69..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.wordnik.swagger.codegen; - -public enum CodegenModelType { - - MODEL(CodegenModel.class), - OPERATION(CodegenOperation.class), - PARAMETER(CodegenParameter.class), - PROPERTY(CodegenProperty.class), - RESPONSE(CodegenResponse.class), - SECURITY(CodegenSecurity.class); - - private final Class defaultImplementation; - - private CodegenModelType(Class defaultImplementation) { - this.defaultImplementation = defaultImplementation; - } - - public Class getDefaultImplementation() { - return defaultImplementation; - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java deleted file mode 100644 index 76055110b92..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.models.*; - -import java.util.*; - -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 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; -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java deleted file mode 100644 index 8dc9991daed..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.wordnik.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; - - /** - * 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; - - return output; - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java deleted file mode 100644 index 921ca90f189..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.wordnik.swagger.codegen; - -import java.util.*; - -public class CodegenProperty { - public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, - name, min, max, defaultValue, baseType, containerType; - - /** maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */ - 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; -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java deleted file mode 100644 index 02627eec1bd..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.wordnik.swagger.codegen; - -import java.util.ArrayList; -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); } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java deleted file mode 100644 index 00d56ea213e..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.wordnik.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; -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java deleted file mode 100644 index 5a39a23fde1..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.fasterxml.jackson.annotation.*; - -import java.util.Map; -import java.util.HashMap; - -public enum CodegenType { - CLIENT, SERVER, DOCUMENTATION, OTHER; - - 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(); - } - - return null; // or fail - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java deleted file mode 100644 index d7788ef8865..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ /dev/null @@ -1,1277 +0,0 @@ -package com.wordnik.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 com.wordnik.swagger.codegen.examples.ExampleGenerator; -import com.wordnik.swagger.models.ArrayModel; -import com.wordnik.swagger.models.ComposedModel; -import com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.ModelImpl; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.RefModel; -import com.wordnik.swagger.models.Response; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.models.auth.ApiKeyAuthDefinition; -import com.wordnik.swagger.models.auth.BasicAuthDefinition; -import com.wordnik.swagger.models.auth.In; -import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.models.parameters.BodyParameter; -import com.wordnik.swagger.models.parameters.CookieParameter; -import com.wordnik.swagger.models.parameters.FormParameter; -import com.wordnik.swagger.models.parameters.HeaderParameter; -import com.wordnik.swagger.models.parameters.Parameter; -import com.wordnik.swagger.models.parameters.PathParameter; -import com.wordnik.swagger.models.parameters.QueryParameter; -import com.wordnik.swagger.models.parameters.SerializableParameter; -import com.wordnik.swagger.models.properties.AbstractNumericProperty; -import com.wordnik.swagger.models.properties.ArrayProperty; -import com.wordnik.swagger.models.properties.BooleanProperty; -import com.wordnik.swagger.models.properties.DateProperty; -import com.wordnik.swagger.models.properties.DateTimeProperty; -import com.wordnik.swagger.models.properties.DecimalProperty; -import com.wordnik.swagger.models.properties.DoubleProperty; -import com.wordnik.swagger.models.properties.FloatProperty; -import com.wordnik.swagger.models.properties.IntegerProperty; -import com.wordnik.swagger.models.properties.LongProperty; -import com.wordnik.swagger.models.properties.MapProperty; -import com.wordnik.swagger.models.properties.Property; -import com.wordnik.swagger.models.properties.PropertyBuilder; -import com.wordnik.swagger.models.properties.RefProperty; -import com.wordnik.swagger.models.properties.StringProperty; -import com.wordnik.swagger.util.Json; - - -public class DefaultCodegen { - 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(); - - public List cliOptions() { - return cliOptions; - } - - public void processOpts(){ - if(additionalProperties.containsKey("templateDir")) { - this.setTemplateDir((String)additionalProperties.get("templateDir")); - } - - 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()); - } - } - } - - 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 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; - } - - 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); - } - } - - private void addImport(CodegenModel m, String type) { - if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { - m.imports.add(type); - } - } - - 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; - } - } - - /* 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); - } - - // 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; - } - - - 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/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java deleted file mode 100644 index d57926b7e3c..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ /dev/null @@ -1,487 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.samskivert.mustache.Mustache; -import com.samskivert.mustache.Template; -import com.wordnik.swagger.models.Contact; -import com.wordnik.swagger.models.Info; -import com.wordnik.swagger.models.License; -import com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.Path; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.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.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -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; - - public Generator opts(ClientOptInput opts) { - this.opts = opts; - - 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!"); - } - 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()); - } - 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()); - } - } - 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"); - } - }) - .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(); - } - 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"); - } - 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); - } - } - - 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; - } - 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); - } - } - } - } - - 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); - } - - 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; - } - - 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/com/wordnik/swagger/codegen/Generator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java deleted file mode 100644 index 0dfbab86a0a..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.models.Swagger; - -import java.io.File; -import java.util.List; - -public interface Generator { - Generator opts(ClientOptInput opts); - List generate(); -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/MetaGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/MetaGenerator.java deleted file mode 100644 index fc5f2d020a1..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/MetaGenerator.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.codegen.languages.*; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.models.auth.AuthorizationValue; -import com.wordnik.swagger.util.*; - -import io.swagger.parser.SwaggerParser; - -import com.samskivert.mustache.*; - -import org.apache.commons.cli.*; -import org.apache.commons.io.FileUtils; - -import java.io.File; -import java.io.Reader; -import java.util.*; - -/** - * @deprecated use instead {@link com.wordnik.swagger.codegen.DefaultGenerator} - * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 - */ -@Deprecated -public class MetaGenerator extends AbstractGenerator { - static Map configs = new HashMap(); - static String configString; - 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(); - } - } - - 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 = "com.wordnik.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 com.wordnik.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", "com.wordnik.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(); - } - } - } - - 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; - } - - static void usage(Options options) { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp( "MetaGenerator. Generator for creating a new template set " + - "and configuration for Codegen. The output will be based on the language you " + - "specify, and includes default templates to include.", options ); - } - - public static CodegenConfig getConfig(String name) { - if(configs.containsKey(name)) { - return configs.get(name); - } - return null; - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java deleted file mode 100644 index 85f08bfa70c..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.wordnik.swagger.codegen; - -public class SupportingFile { - 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; - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java deleted file mode 100644 index 7de102ec350..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.wordnik.swagger.codegen.auth; - -public interface AuthMethod { - String getType(); - void setType(String type); -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java deleted file mode 100644 index 51d10f7e8a6..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.wordnik.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 com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.ModelImpl; -import com.wordnik.swagger.models.properties.ArrayProperty; -import com.wordnik.swagger.models.properties.BooleanProperty; -import com.wordnik.swagger.models.properties.DateProperty; -import com.wordnik.swagger.models.properties.DateTimeProperty; -import com.wordnik.swagger.models.properties.DecimalProperty; -import com.wordnik.swagger.models.properties.DoubleProperty; -import com.wordnik.swagger.models.properties.FileProperty; -import com.wordnik.swagger.models.properties.FloatProperty; -import com.wordnik.swagger.models.properties.IntegerProperty; -import com.wordnik.swagger.models.properties.LongProperty; -import com.wordnik.swagger.models.properties.MapProperty; -import com.wordnik.swagger.models.properties.ObjectProperty; -import com.wordnik.swagger.models.properties.Property; -import com.wordnik.swagger.models.properties.RefProperty; -import com.wordnik.swagger.models.properties.StringProperty; -import com.wordnik.swagger.models.properties.UUIDProperty; -import com.wordnik.swagger.util.Json; - -public class ExampleGenerator { - protected Map 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)); - - 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); - } - } - 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)); - } - } - - return values; - } - - return ""; - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java deleted file mode 100644 index b1896605cdf..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.wordnik.swagger.codegen.examples; - - -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.properties.*; - -import java.text.SimpleDateFormat; -import java.util.*; - -import org.codehaus.plexus.util.StringUtils; - -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 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; - } - 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(); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java deleted file mode 100644 index fff8deb99f4..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ /dev/null @@ -1,365 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.google.common.base.CaseFormat; -import com.samskivert.mustache.Mustache; -import com.samskivert.mustache.Template; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.*; - -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 = "com.wordnik"; - 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; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "akka-scala"; - } - - public String getHelp() { - return "Generates a Scala client library base on Akka/Spray."; - } - - public AkkaScalaClientCodegen() { - super(); - outputFolder = "generated-code/scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "akka-scala"; - apiPackage = mainPackage + ".api"; - modelPackage = mainPackage + ".model"; - - 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") - ); - - 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); - - 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")); - - importMapping.remove("Seq"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - importMapping.put("DateTime", "org.joda.time.DateTime"); - - 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"); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Seq", - "Map") - ); - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "Map"); - } - - @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; - 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); - } - } - 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(); - } - - if (codegenSecurities.isEmpty()) - return null; - return codegenSecurities; - } - - @Override - public String toOperationId(String operationId) { - return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); - } - - 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 toParamName(String name) { return formatIdentifier(name, false); } - - @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); - } - - @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); - } - } - - 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/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java deleted file mode 100644 index 377c8de24d9..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "android"; - } - - public String getHelp() { - return "Generates an Android client library."; - } - - public AndroidClientCodegen() { - super(); - outputFolder = "generated-code/android"; - 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) + ">"; - } - 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); - } - - @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 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")); - } - - 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/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java deleted file mode 100644 index d85fdc8f695..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "com.wordnik"; - 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 String getHelp() { - return "Generates an Asynchronous Scala client library."; - } - - 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"; - - 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") - ); - - 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); - - 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.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - 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) + "]"; - } - 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); - } - - @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 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"; - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java deleted file mode 100644 index abac0db5d9f..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ /dev/null @@ -1,192 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "csharp"; - } - - public String getHelp() { - return "Generates a CSharp client library."; - } - - public CSharpClientCodegen() { - super(); - outputFolder = "generated-code/csharp"; - modelTemplateFiles.put("model.mustache", ".cs"); - apiTemplateFiles.put("api.mustache", ".cs"); - templateDir = "csharp"; - apiPackage = "IO.Swagger.Api"; - modelPackage = "IO.Swagger.Model"; - - 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") - ); - - additionalProperties.put("invokerPackage", invokerPackage); - - 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) + ""; - } - 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/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java deleted file mode 100644 index 6d9966c7fe4..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "java"; - } - - public String getHelp() { - return "Generates a Java client library."; - } - - public JavaClientCodegen() { - super(); - outputFolder = "generated-code/java"; - 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); - } - - 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")); - } - - - - @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); - } - - @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 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/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java deleted file mode 100644 index 4631a804fc7..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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"; - - public CodegenType getTag() { - return CodegenType.SERVER; - } - - public String getName() { - return "jaxrs"; - } - - public String getHelp() { - return "Generates a Java JAXRS Server application."; - } - - public JaxRSServerCodegen() { - super.processOpts(); - - sourceFolder = "src/gen/java"; - - outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" ); - 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); - - - 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) + ">"; - } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getTypeDeclaration(inner); - } - 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(); - } - 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"; - } - } - 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; - } - - @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"; - } - - 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/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java deleted file mode 100644 index 9d516c398f6..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java +++ /dev/null @@ -1,196 +0,0 @@ -package com.wordnik.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 com.wordnik.swagger.codegen.CodegenConfig; -import com.wordnik.swagger.codegen.CodegenOperation; -import com.wordnik.swagger.codegen.CodegenParameter; -import com.wordnik.swagger.codegen.CodegenResponse; -import com.wordnik.swagger.codegen.CodegenType; -import com.wordnik.swagger.codegen.DefaultCodegen; -import com.wordnik.swagger.codegen.SupportingFile; - -public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String apiVersion = "1.0.0"; - protected int serverPort = 8080; - protected String projectName = "swagger-server"; - - public String apiPackage() { - return "controllers"; - } - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see com.wordnik.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.SERVER; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "nodejs"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a nodejs server library using the swagger-tools project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; - } - - public NodeJSServerCodegen() { - super(); - - // set the output folder here - outputFolder = "generated-code/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(); - - /** - * 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"; - } - } - 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/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java deleted file mode 100644 index ab1cf2ec8d7..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ /dev/null @@ -1,347 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { - 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 String getHelp() { - return "Generates an Objective-C client library."; - } - - 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 = ""; - - 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") - ); - - // 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" - )); - - 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"); - - importMapping = new HashMap (); - - 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")); - } - - 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); - } - - @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 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 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 + "*"; - } - } - } - - @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)) { - property.setter = "initWithDictionary"; - } - else { - property.setter = "initWithValues"; - } - } - - @Override - 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 apiFileFolder() { - 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"; - } - - 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_]","_"); - - // 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); - - // 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); - } - - 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"); - - return camelize(operationId, true); - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - 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/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java deleted file mode 100644 index b96b012abba..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PerlClientCodegen.java +++ /dev/null @@ -1,200 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "SwaggerClient"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "perl"; - } - - public String getHelp() { - return "Generates a Perl client library."; - } - - public PerlClientCodegen() { - super(); - modelPackage = File.separatorChar + "Object"; - outputFolder = "generated-code" + File.separatorChar + "perl"; - modelTemplateFiles.put("object.mustache", ".pm"); - apiTemplateFiles.put("api.mustache", ".pm"); - templateDir = "perl"; - - typeMapping.clear(); - languageSpecificPrimitives.clear(); - - 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" - ) - ); - - 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) + "]"; - } - 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; - } - - 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); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // 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/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java deleted file mode 100644 index 2f643724b14..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "php"; - } - - public String getHelp() { - return "Generates a PHP client library."; - } - - public PhpClientCodegen() { - super(); - - invokerPackage = camelize("SwaggerClient"); - - String packagePath = invokerPackage + "-php"; - - modelPackage = packagePath + "/lib/models"; - apiPackage = packagePath + "/lib"; - outputFolder = "generated-code/php"; - modelTemplateFiles.put("model.mustache", ".php"); - apiTemplateFiles.put("api.mustache", ".php"); - templateDir = "php"; - - 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") - ); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - // 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) + "]"; - } - 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/com/wordnik/swagger/codegen/languages/Python3ClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Python3ClientCodegen.java deleted file mode 100755 index 81ba21ebe72..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Python3ClientCodegen.java +++ /dev/null @@ -1,198 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.io.File; -import java.util.*; - -public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig { - String module = "client"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "python3"; - } - - public String getHelp() { - return "Generates a Python3 client library."; - } - - public Python3ClientCodegen() { - super(); - outputFolder = "generated-code/python3"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python3"; - - apiPackage = module; - modelPackage = module + ".models"; - - 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) + "]"; - } - 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; - } - - 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("-", "_"); - - // 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); - - // 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) { - // 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); - } - - @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"; - } - - @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 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/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java deleted file mode 100755 index 7f9a77d3132..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ /dev/null @@ -1,215 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.io.File; -import java.util.*; - -public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String module = "SwaggerPetstore"; - protected String invokerPackage; - protected String eggPackage; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "python"; - } - - public String getHelp() { - return "Generates a Python client library."; - } - - public PythonClientCodegen() { - super(); - - eggPackage = module + "-python"; - - invokerPackage = eggPackage + File.separatorChar + module; - - outputFolder = "generated-code" + File.separatorChar + "python"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python"; - - apiPackage = invokerPackage + File.separatorChar + "apis"; - modelPackage = invokerPackage + File.separatorChar + "models"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - 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")); - - 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) + "]"; - } - 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; - } - - 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("-", "_"); - - // 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)); - - // for reserved word or word starting with number, append _ - if(reservedWords.contains(name) || name.matches("^\\d.*")) - name = escapeReservedWord(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 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) { - // 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)); - } - - @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"; - } - - @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 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/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java deleted file mode 100644 index 35d9bf58bbb..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/Qt5CPPGenerator.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { - protected Set foundationClasses = 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(); - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see com.wordnik.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "qt5cpp"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a qt5 C++ client library."; - } - - public Qt5CPPGenerator() { - super(); - - // set the output folder here - outputFolder = "generated-code/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"); - - modelTemplateFiles.put( - "model-body.mustache", - ".cpp"); - - /** - * 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 - - 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"); - } - - @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\""; - } - - /** - * 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) + ">*"; - } - 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()"; - } - 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"; - } - - - /** - * 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 com.wordnik.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); - } - - @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); - } - } - - @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/com/wordnik/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RetrofitClientCodegen.java deleted file mode 100644 index 6f80f8a5c5e..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RetrofitClientCodegen.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "retrofit"; - } - - public String getHelp() { - return "Generates a Retrofit client library."; - } - - public RetrofitClientCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "retrofit"; - 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") - ); - - 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) + ">"; - } - 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); - } - - @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; - } - } - } - if(operation.returnType == null) { - operation.returnType = "Void"; - } - } - } - return objs; - } -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java deleted file mode 100644 index 3ca7758b1a3..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String gemName = "swagger_client"; - protected String moduleName = null; - protected String libFolder = "lib"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "ruby"; - } - - public String getHelp() { - return "Generates a Ruby client library."; - } - - /** - * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". - */ - public String generateModuleName() { - return camelize(gemName.replaceAll("[^\\w]+", "_")); - } - - public RubyClientCodegen() { - super(); - moduleName = generateModuleName(); - modelPackage = gemName + "/models"; - apiPackage = gemName + "/api"; - outputFolder = "generated-code" + File.separatorChar + "ruby"; - modelTemplateFiles.put("model.mustache", ".rb"); - apiTemplateFiles.put("api.mustache", ".rb"); - templateDir = "ruby"; - - typeMapping.clear(); - languageSpecificPrimitives.clear(); - - 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) + "]"; - } - 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; - } - - public String toDefaultValue(Property p) { - return "null"; - } - - @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(); - - // 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); - - 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) { - // 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); - } - - @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"; - } - - @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); - } - - @Override - public String toModelImport(String name) { - return modelPackage() + "/" + toModelFilename(name); - } - - @Override - public String toApiImport(String name) { - return apiPackage() + "/" + toApiFilename(name); - } - -} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java deleted file mode 100644 index 4695cc3d065..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "com.wordnik"; - 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 String getHelp() { - return "Generates a Scala client library."; - } - - 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"; - - 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") - ); - - 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); - - 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.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - 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) + "]"; - } - 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); - } - - @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 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"; - } - - - @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/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java deleted file mode 100644 index 2434ca10ee1..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; -import com.wordnik.swagger.util.Json; - -import java.util.*; -import java.io.File; - -public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; - - public CodegenType getTag() { - return CodegenType.SERVER; - } - - public String getName() { - return "scalatra"; - } - - public String getHelp() { - return "Generates a Scala server application with Scalatra."; - } - - public ScalatraServerCodegen() { - super(); - outputFolder = "generated-code/scalatra"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scalatra"; - apiPackage = "com.wordnik.client.api"; - modelPackage = "com.wordnik.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") - ); - - defaultIncludes = new HashSet( - Arrays.asList("double", - "Int", - "Long", - "Float", - "Double", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "List", - "Set", - "Map") - ); - - typeMapping.put("integer", "Int"); - typeMapping.put("long", "Long"); - - additionalProperties.put("appName", "Swagger Sample"); - additionalProperties.put("appName", "Swagger Sample"); - additionalProperties.put("appDescription", "A sample swagger server"); - additionalProperties.put("infoUrl", "http://developers.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("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(); - } - 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); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SpringMVCServerCodegen.java deleted file mode 100644 index 252457758d8..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SpringMVCServerCodegen.java +++ /dev/null @@ -1,165 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.Path; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.api"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-spring-mvc-server"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; - protected String title = "Petstore Server"; - - 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(); - outputFolder = "generated-code/javaSpringMVC"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "JavaSpringMVC"; - apiPackage = "io.swagger.api"; - modelPackage = "io.swagger.model"; - configPackage = "io.swagger.configuration"; - - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - additionalProperties.put("title", title); - additionalProperties.put("apiPackage", apiPackage); - additionalProperties.put("configPackage", configPackage); - - 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("swaggerConfig.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerConfig.java")); - supportingFiles.add(new SupportingFile("webApplication.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); - supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); - supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", - (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); - supportingFiles.add(new SupportingFile("swagger.properties", - ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); - } - - @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); - } - 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(); - } - 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"; - } - } - 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; - } -} - diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java deleted file mode 100644 index f6c24d381bd..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "docs"; - - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } - - public String getName() { - return "dynamic-html"; - } - - public String getHelp() { - return "Generates a dynamic HTML site."; - } - - public StaticDocCodegen() { - super(); - outputFolder = "docs"; - modelTemplateFiles.put("model.mustache", ".html"); - apiTemplateFiles.put("operation.mustache", ".html"); - templateDir = "swagger-static"; - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - 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")); - - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + "operations"; - } - - 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/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java deleted file mode 100644 index 7186f24a0e0..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.properties.*; -import com.wordnik.swagger.util.Json; - -import java.util.*; -import java.io.File; - -public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { - private static final String ALL_OPERATIONS = ""; - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/scala"; - - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } - - public String getName() { - return "html"; - } - - public String getHelp() { - return "Generates a static HTML file."; - } - - public StaticHtmlGenerator() { - super(); - outputFolder = "docs"; - templateDir = "htmlDocs"; - - 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) + "]"; - } - 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); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java deleted file mode 100644 index c0560e2a1bc..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.*; -import com.wordnik.swagger.models.Swagger; - -import org.apache.commons.io.FileUtils; - -import java.io.File; - -public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } - - 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); - } - catch(Exception e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java deleted file mode 100644 index 7c65168546f..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.*; -import com.wordnik.swagger.models.Swagger; - -import org.apache.commons.io.FileUtils; - -import java.io.File; - -public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { - public CodegenType getTag() { - return CodegenType.DOCUMENTATION; - } - - 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); - } - catch(Exception e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java deleted file mode 100644 index e763c51e1ac..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.parameters.HeaderParameter; -import com.wordnik.swagger.models.parameters.Parameter; -import com.wordnik.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; - -import javax.annotation.Nullable; -import java.util.*; -import java.io.File; -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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "swift"; - } - - public String getHelp() { - return "Generates a swift client library."; - } - - public SwiftGenerator() { - super(); - outputFolder = "generated-code/swift"; - modelTemplateFiles.put("model.mustache", ".swift"); - apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; - - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; - } - additionalProperties.put("projectName", appName); - - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); - } - - sourceFolder = appName + "/" + sourceFolder; - - 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")); - - 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(); - } - - @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); - } - - @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); - - return builder.toString(); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java deleted file mode 100644 index ab9fa033f1c..00000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; -import java.io.File; - -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(); - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "tizen"; - } - - public String getHelp() { - return "Generates a Samsung Tizen C++ client library."; - } - - public TizenClientCodegen() { - super(); - outputFolder = "generated-code/tizen"; - 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 = ""; - - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "int", - "long") - ); - languageSpecificPrimitives = new HashSet(); - - additionalProperties().put("prefix", PREFIX); - - 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" - )); - - super.typeMapping = 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"); - - 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"); - } - 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); - } - - @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; - } - 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) + ";"; - } - 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()"; - } - 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"; - } - - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder; - } - - @Override - public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder; - } - - @Override - public String toModelFilename(String name) { - return PREFIX + initialCaps(name); - } - - @Override - public String toApiName(String name) { - return PREFIX + initialCaps(name) + "Api"; - } - - public String toApiFilename(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 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); - } - -} diff --git a/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala b/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala index 83c3be06f93..25ca9b882aa 100644 --- a/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala +++ b/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala @@ -1,6 +1,6 @@ -import com.wordnik.swagger.codegen._ +import io.swagger.codegen._ -import com.wordnik.swagger.models.auth.AuthorizationValue +import io.swagger.models.auth.AuthorizationValue import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala index 5ce35825159..bf9e41491d7 100644 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -1,5 +1,5 @@ -import com.wordnik.swagger.codegen.DefaultCodegen -import com.wordnik.swagger.models.properties.Property +import io.swagger.codegen.DefaultCodegen +import io.swagger.models.properties.Property import io.swagger.parser._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala index 09ffbf0e16c..fd362c71cf1 100644 --- a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala +++ b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala @@ -7,13 +7,13 @@ import org.scalatest.FlatSpec import org.scalatest.Matchers import org.scalatest.junit.JUnitRunner -import com.wordnik.swagger.codegen.examples.ExampleGenerator -import com.wordnik.swagger.models.Model -import com.wordnik.swagger.models.ModelImpl -import com.wordnik.swagger.models.Xml -import com.wordnik.swagger.models.properties.ArrayProperty -import com.wordnik.swagger.models.properties.RefProperty -import com.wordnik.swagger.models.properties.StringProperty +import io.swagger.codegen.examples.ExampleGenerator +import io.swagger.models.Model +import io.swagger.models.ModelImpl +import io.swagger.models.Xml +import io.swagger.models.properties.ArrayProperty +import io.swagger.models.properties.RefProperty +import io.swagger.models.properties.StringProperty @RunWith(classOf[JUnitRunner]) class ExampleGeneratorTest extends FlatSpec with Matchers { diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala index 1b6cfc0ecfd..ec729f69b5d 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala @@ -6,11 +6,11 @@ import org.junit.runner.RunWith import org.scalatest.FlatSpec import org.scalatest.Matchers import org.scalatest.junit.JUnitRunner -import com.wordnik.swagger.codegen.languages.JavaClientCodegen -import com.wordnik.swagger.models.ComposedModel -import com.wordnik.swagger.models.ModelImpl -import com.wordnik.swagger.models.RefModel -import com.wordnik.swagger.models.properties.StringProperty +import io.swagger.codegen.languages.JavaClientCodegen +import io.swagger.models.ComposedModel +import io.swagger.models.ModelImpl +import io.swagger.models.RefModel +import io.swagger.models.properties.StringProperty @RunWith(classOf[JUnitRunner]) class JavaInheritanceTest extends FlatSpec with Matchers { diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala index e621b18565d..3873d4db94d 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala @@ -1,8 +1,8 @@ package Java -import com.wordnik.swagger.codegen.languages.JavaClientCodegen -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.JavaClientCodegen +import io.swagger.models._ +import io.swagger.models.properties._ import org.junit.runner.RunWith import org.scalatest.{FlatSpec, Matchers} import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala index f5b26bf78e8..78f32f1d815 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -1,9 +1,9 @@ package Java -import com.wordnik.swagger.codegen.languages.JavaClientCodegen -import com.wordnik.swagger.util.Json -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.JavaClientCodegen +import io.swagger.util.Json +import io.swagger.models._ +import io.swagger.models.properties._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala index 4de884885e4..164f50f926b 100644 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -1,9 +1,9 @@ package Objc -import com.wordnik.swagger.codegen.languages.ObjcClientCodegen -import com.wordnik.swagger.util.Json -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.ObjcClientCodegen +import io.swagger.util.Json +import io.swagger.models._ +import io.swagger.models.properties._ import io.swagger.parser.SwaggerParser diff --git a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala index b05059a218a..6c78fa147c1 100644 --- a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala +++ b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala @@ -1,7 +1,7 @@ -import com.wordnik.swagger.models._ +import io.swagger.models._ import io.swagger.parser._ -import com.wordnik.swagger.util.Json +import io.swagger.util.Json import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala index 1e4926d43d7..0f4e5f9659b 100644 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -1,9 +1,9 @@ package php -import com.wordnik.swagger.codegen.languages.PhpClientCodegen -import com.wordnik.swagger.util.Json -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.PhpClientCodegen +import io.swagger.util.Json +import io.swagger.models._ +import io.swagger.models.properties._ import io.swagger.parser.SwaggerParser diff --git a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala index ec42985586c..94f3f6dda98 100644 --- a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala +++ b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala @@ -1,6 +1,6 @@ package python -import com.wordnik.swagger.codegen.languages.{PythonClientCodegen} +import io.swagger.codegen.languages.{PythonClientCodegen} import io.swagger.parser.SwaggerParser import org.junit.runner.RunWith diff --git a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala index 39d76ca168c..bf155e381e9 100644 --- a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala @@ -1,9 +1,9 @@ -package scala +package Scala -import com.wordnik.swagger.codegen.languages.ScalaClientCodegen -import com.wordnik.swagger.util.Json -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.ScalaClientCodegen +import io.swagger.util.Json +import io.swagger.models._ +import io.swagger.models.properties._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala b/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala index f46201faa5b..43e85e5eb5c 100644 --- a/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala +++ b/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala @@ -1,9 +1,9 @@ package staticDocs -import com.wordnik.swagger.codegen.languages.StaticDocCodegen -import com.wordnik.swagger.util.Json -import com.wordnik.swagger.models._ -import com.wordnik.swagger.models.properties._ +import io.swagger.codegen.languages.StaticDocCodegen +import io.swagger.util.Json +import io.swagger.models._ +import io.swagger.models.properties._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner From 44af46c9b36fed9a2e29cc9c6c31687a10084e0d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 6 Jun 2015 23:11:28 -0700 Subject: [PATCH 02/22] updated files --- .../io/swagger/codegen/AbstractGenerator.java | 60 + .../java/io/swagger/codegen/CliOption.java | 23 + .../io/swagger/codegen/ClientOptInput.java | 104 ++ .../java/io/swagger/codegen/ClientOpts.java | 52 + .../main/java/io/swagger/codegen/Codegen.java | 143 ++ .../io/swagger/codegen/CodegenConfig.java | 64 + .../java/io/swagger/codegen/CodegenModel.java | 16 + .../swagger/codegen/CodegenModelFactory.java | 38 + .../io/swagger/codegen/CodegenModelType.java | 21 + .../io/swagger/codegen/CodegenOperation.java | 32 + .../io/swagger/codegen/CodegenParameter.java | 41 + .../io/swagger/codegen/CodegenProperty.java | 28 + .../io/swagger/codegen/CodegenResponse.java | 21 + .../io/swagger/codegen/CodegenSecurity.java | 10 + .../java/io/swagger/codegen/CodegenType.java | 34 + .../io/swagger/codegen/DefaultCodegen.java | 1277 +++++++++++++++++ .../io/swagger/codegen/DefaultGenerator.java | 487 +++++++ .../java/io/swagger/codegen/Generator.java | 11 + .../io/swagger/codegen/MetaGenerator.java | 185 +++ .../io/swagger/codegen/SupportingFile.java | 13 + .../io/swagger/codegen/auth/AuthMethod.java | 6 + .../codegen/examples/ExampleGenerator.java | 175 +++ .../codegen/examples/XmlExampleGenerator.java | 206 +++ .../languages/AkkaScalaClientCodegen.java | 365 +++++ .../languages/AndroidClientCodegen.java | 259 ++++ .../languages/AsyncScalaClientCodegen.java | 194 +++ .../languages/CSharpClientCodegen.java | 192 +++ .../codegen/languages/JavaClientCodegen.java | 241 ++++ .../codegen/languages/JaxRSServerCodegen.java | 200 +++ .../languages/NodeJSServerCodegen.java | 196 +++ .../codegen/languages/ObjcClientCodegen.java | 347 +++++ .../codegen/languages/PerlClientCodegen.java | 200 +++ .../codegen/languages/PhpClientCodegen.java | 184 +++ .../languages/Python3ClientCodegen.java | 198 +++ .../languages/PythonClientCodegen.java | 215 +++ .../codegen/languages/Qt5CPPGenerator.java | 308 ++++ .../languages/RetrofitClientCodegen.java | 190 +++ .../codegen/languages/RubyClientCodegen.java | 220 +++ .../codegen/languages/ScalaClientCodegen.java | 203 +++ .../languages/ScalatraServerCodegen.java | 178 +++ .../languages/SpringMVCServerCodegen.java | 165 +++ .../codegen/languages/StaticDocCodegen.java | 76 + .../languages/StaticHtmlGenerator.java | 97 ++ .../codegen/languages/SwaggerGenerator.java | 45 + .../languages/SwaggerYamlGenerator.java | 44 + .../codegen/languages/SwiftGenerator.java | 250 ++++ .../codegen/languages/TizenClientCodegen.java | 258 ++++ 47 files changed, 7872 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java create mode 100755 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java create mode 100755 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java 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 new file mode 100644 index 00000000000..3fc7dfb8da2 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -0,0 +1,60 @@ +package io.swagger.codegen; + +import com.samskivert.mustache.*; + +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); + + 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; + } + + 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); + } + + 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); + } + + 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 new file mode 100644 index 00000000000..3f4334507ae --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java @@ -0,0 +1,23 @@ +package io.swagger.codegen; + +public class CliOption { + private final String opt; + private String description; + + public CliOption(String opt, String description) { + this.opt = opt; + this.description = description; + } + + public String getOpt() { + return opt; + } + + public String getDescription() { + return 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 new file mode 100644 index 00000000000..54056583463 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -0,0 +1,104 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.codegen; + +import io.swagger.codegen.ClientOpts; +import io.swagger.annotations.*; +import io.swagger.models.Swagger; +import io.swagger.models.auth.AuthorizationValue; + +import java.util.*; +import java.net.URLEncoder; +import java.net.URLDecoder; + +public class ClientOptInput { + private ClientOpts opts; + private Swagger swagger; + private List auths; + protected CodegenConfig config; + + public ClientOptInput swagger(Swagger swagger) { + this.setSwagger(swagger); + return this; + } + public ClientOptInput opts(ClientOpts opts) { + this.setOpts(opts); + return this; + } + + public 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 String getAuth() { + if(auths != null) { + StringBuilder b = new StringBuilder(); + for(AuthorizationValue v : auths) { + try { + if(b.toString().length() > 0) + b.append(","); + b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) + .append(":") + .append(URLEncoder.encode(v.getValue(), "UTF-8")); + } + catch (Exception e) { + // continue + e.printStackTrace(); + } + } + return b.toString(); + } + else + return null; + } + public List getAuthorizationValues() { + return auths; + } + + public CodegenConfig getConfig() { + return config; + } + public void setConfig(CodegenConfig config) { + this.config = config; + } + + public void setOpts(ClientOpts opts) { + this.opts = opts; + } + + public ClientOpts getOpts() { + return opts; + } + + public void setSwagger(Swagger swagger) { + this.swagger = swagger; + } + + @ApiModelProperty(dataType="Object") + public Swagger getSwagger() { + return 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 new file mode 100644 index 00000000000..465fed820da --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOpts.java @@ -0,0 +1,52 @@ +package io.swagger.codegen; + +import io.swagger.codegen.auth.*; + +import java.util.*; + +public class ClientOpts { + 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 getTarget() { + return target; + } + public void setTarget(String target) { + this.target = target; + } + + 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 new file mode 100644 index 00000000000..8772a8b8ced --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -0,0 +1,143 @@ +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.*; + +import java.io.File; +import java.util.*; + +/** + * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} + * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 + */ +@Deprecated +public class Codegen extends DefaultGenerator { + static Map configs = new HashMap(); + static String configString; + 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(); + } + } + + 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(); + + 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; + + 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()); + 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; + } + 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()); + } + return output; + } + + 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); + } + 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); + } + } + } +} \ 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 new file mode 100644 index 00000000000..4ff582dcb11 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -0,0 +1,64 @@ +package io.swagger.codegen; + +import io.swagger.models.*; +import io.swagger.models.auth.SecuritySchemeDefinition; +import io.swagger.models.properties.*; + +import java.util.*; + +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); + + Set reservedWords(); + + List supportingFiles(); + + void setOutputDir(String dir); + String getOutputDir(); + + 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 new file mode 100644 index 00000000000..0cacc3a56e3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -0,0 +1,16 @@ +package io.swagger.codegen; + +import io.swagger.models.*; +import io.swagger.models.properties.*; + +import java.util.*; + +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; +} \ 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 new file mode 100644 index 00000000000..06dfcfbc86b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelFactory.java @@ -0,0 +1,38 @@ +package io.swagger.codegen; + +import java.util.HashMap; +import java.util.Map; + +public final class CodegenModelFactory { + + 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()); + } + 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); + } + } +} 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 new file mode 100644 index 00000000000..8c082a899cd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModelType.java @@ -0,0 +1,21 @@ +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); + + private final Class defaultImplementation; + + private CodegenModelType(Class defaultImplementation) { + this.defaultImplementation = 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 new file mode 100644 index 00000000000..f7bd875848c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -0,0 +1,32 @@ +package io.swagger.codegen; + +import io.swagger.models.*; + +import java.util.*; + +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 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; +} 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 new file mode 100644 index 00000000000..f19809606d1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -0,0 +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; + + /** + * 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; + + 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 new file mode 100644 index 00000000000..407266add1f --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -0,0 +1,28 @@ +package io.swagger.codegen; + +import java.util.*; + +public class CodegenProperty { + public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, + name, min, max, defaultValue, baseType, containerType; + + /** maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */ + 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; +} 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 new file mode 100644 index 00000000000..514ced65b63 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -0,0 +1,21 @@ +package io.swagger.codegen; + +import java.util.ArrayList; +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); } +} 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 new file mode 100644 index 00000000000..09e1a503191 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -0,0 +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; +} 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 new file mode 100644 index 00000000000..b7c8aad9f1b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenType.java @@ -0,0 +1,34 @@ +package io.swagger.codegen; + +import com.fasterxml.jackson.annotation.*; + +import java.util.Map; +import java.util.HashMap; + +public enum CodegenType { + CLIENT, SERVER, DOCUMENTATION, OTHER; + + 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(); + } + + return null; // or fail + } +} \ 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 new file mode 100644 index 00000000000..e342d07f66f --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -0,0 +1,1277 @@ +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; +import io.swagger.models.ArrayModel; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.RefModel; +import io.swagger.models.Response; +import io.swagger.models.Swagger; +import io.swagger.models.auth.ApiKeyAuthDefinition; +import io.swagger.models.auth.BasicAuthDefinition; +import io.swagger.models.auth.In; +import io.swagger.models.auth.SecuritySchemeDefinition; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.CookieParameter; +import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.HeaderParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.PathParameter; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.parameters.SerializableParameter; +import io.swagger.models.properties.AbstractNumericProperty; +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.PropertyBuilder; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.util.Json; + + +public class DefaultCodegen { + 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(); + + public List cliOptions() { + return cliOptions; + } + + public void processOpts(){ + if(additionalProperties.containsKey("templateDir")) { + this.setTemplateDir((String)additionalProperties.get("templateDir")); + } + + 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()); + } + } + } + + 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 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; + } + + 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); + } + } + + private void addImport(CodegenModel m, String type) { + if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { + m.imports.add(type); + } + } + + 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; + } + } + + /* 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); + } + + // 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; + } + + + 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 new file mode 100644 index 00000000000..1f9da14119d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -0,0 +1,487 @@ +package io.swagger.codegen; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.models.Contact; +import io.swagger.models.Info; +import io.swagger.models.License; +import io.swagger.models.Model; +import io.swagger.models.Operation; +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.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +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; + + public Generator opts(ClientOptInput opts) { + this.opts = opts; + + 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!"); + } + 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()); + } + 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()); + } + } + 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"); + } + }) + .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(); + } + 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"); + } + 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); + } + } + + 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; + } + 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); + } + } + } + } + + 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); + } + + 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; + } + + 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 new file mode 100644 index 00000000000..cf44f46e637 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Generator.java @@ -0,0 +1,11 @@ +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(); +} \ 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 new file mode 100644 index 00000000000..a6fdd93f271 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/MetaGenerator.java @@ -0,0 +1,185 @@ +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 com.samskivert.mustache.*; + +import org.apache.commons.cli.*; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.Reader; +import java.util.*; + +/** + * @deprecated use instead {@link io.swagger.codegen.DefaultGenerator} + * or cli interface from https://github.com/swagger-api/swagger-codegen/pull/547 + */ +@Deprecated +public class MetaGenerator extends AbstractGenerator { + static Map configs = new HashMap(); + static String configString; + 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(); + } + } + + 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)); + } + 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(); + } + } + } + + 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; + } + + static void usage(Options options) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp( "MetaGenerator. Generator for creating a new template set " + + "and configuration for Codegen. The output will be based on the language you " + + "specify, and includes default templates to include.", options ); + } + + public static CodegenConfig getConfig(String name) { + if(configs.containsKey(name)) { + return configs.get(name); + } + return null; + } +} 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 new file mode 100644 index 00000000000..133a6259f24 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -0,0 +1,13 @@ +package io.swagger.codegen; + +public class SupportingFile { + 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; + } +} \ 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 new file mode 100644 index 00000000000..94b43f59888 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthMethod.java @@ -0,0 +1,6 @@ +package io.swagger.codegen.auth; + +public interface AuthMethod { + 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 new file mode 100644 index 00000000000..d6ee8ac642c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -0,0 +1,175 @@ +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; +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.FileProperty; +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.ObjectProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.models.properties.UUIDProperty; +import io.swagger.util.Json; + +public class ExampleGenerator { + protected Map 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)); + + 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); + } + } + 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)); + } + } + + 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 new file mode 100644 index 00000000000..99765195d87 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -0,0 +1,206 @@ +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 org.codehaus.plexus.util.StringUtils; + +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 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; + } + 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(); + } +} \ 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 new file mode 100644 index 00000000000..9300657dc51 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -0,0 +1,365 @@ +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.models.auth.SecuritySchemeDefinition; +import io.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.*; + +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 = "com.wordnik"; + 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; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "akka-scala"; + } + + public String getHelp() { + return "Generates a Scala client library base on Akka/Spray."; + } + + public AkkaScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "akka-scala"; + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; + + 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") + ); + + 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); + + 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")); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + + 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"); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Seq", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + } + + @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; + 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); + } + } + 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(); + } + + if (codegenSecurities.isEmpty()) + return null; + return codegenSecurities; + } + + @Override + public String toOperationId(String operationId) { + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); + } + + 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 toParamName(String name) { return formatIdentifier(name, false); } + + @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); + } + + @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); + } + } + + 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 new file mode 100644 index 00000000000..b1bc4f0b08b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -0,0 +1,259 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "android"; + } + + public String getHelp() { + return "Generates an Android client library."; + } + + public AndroidClientCodegen() { + super(); + outputFolder = "generated-code/android"; + 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) + ">"; + } + 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); + } + + @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 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")); + } + + 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 new file mode 100644 index 00000000000..aa202060f1e --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -0,0 +1,194 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "com.wordnik"; + 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 String getHelp() { + return "Generates an Asynchronous Scala client library."; + } + + 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"; + + 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") + ); + + 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); + + 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.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + 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) + "]"; + } + 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); + } + + @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 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"; + } +} \ 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 new file mode 100644 index 00000000000..3a756ab074e --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -0,0 +1,192 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "csharp"; + } + + public String getHelp() { + return "Generates a CSharp client library."; + } + + public CSharpClientCodegen() { + super(); + outputFolder = "generated-code/csharp"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + templateDir = "csharp"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; + + 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") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + + 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) + ""; + } + 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 new file mode 100644 index 00000000000..b8011d3d459 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -0,0 +1,241 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "java"; + } + + public String getHelp() { + return "Generates a Java client library."; + } + + public JavaClientCodegen() { + super(); + outputFolder = "generated-code/java"; + 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); + } + + 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")); + } + + + + @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); + } + + @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 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/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java new file mode 100644 index 00000000000..0720f6517e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -0,0 +1,200 @@ +package io.swagger.codegen.languages; + +import io.swagger.models.Operation; +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "jaxrs"; + } + + public String getHelp() { + return "Generates a Java JAXRS Server application."; + } + + public JaxRSServerCodegen() { + super.processOpts(); + + sourceFolder = "src/gen/java"; + + outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" ); + 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); + + + 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) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getTypeDeclaration(inner); + } + 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(); + } + 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"; + } + } + 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; + } + + @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"; + } + + 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 new file mode 100644 index 00000000000..eb80937bab7 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -0,0 +1,196 @@ +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; +import io.swagger.codegen.CodegenResponse; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; + +public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + + public String apiPackage() { + return "controllers"; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "nodejs"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a nodejs server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + } + + public NodeJSServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/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(); + + /** + * 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"; + } + } + 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 new file mode 100644 index 00000000000..d8de7597f1c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -0,0 +1,347 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { + 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 String getHelp() { + return "Generates an Objective-C client library."; + } + + 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 = ""; + + 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") + ); + + // 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" + )); + + 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"); + + importMapping = new HashMap (); + + 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")); + } + + 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); + } + + @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 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 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 + "*"; + } + } + } + + @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)) { + property.setter = "initWithDictionary"; + } + else { + property.setter = "initWithValues"; + } + } + + @Override + 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 apiFileFolder() { + 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"; + } + + 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_]","_"); + + // 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); + + // 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); + } + + 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"); + + return camelize(operationId, true); + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + 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 new file mode 100644 index 00000000000..8b4bef52ebe --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -0,0 +1,200 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.Json; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "SwaggerClient"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "perl"; + } + + public String getHelp() { + return "Generates a Perl client library."; + } + + public PerlClientCodegen() { + super(); + modelPackage = File.separatorChar + "Object"; + outputFolder = "generated-code" + File.separatorChar + "perl"; + modelTemplateFiles.put("object.mustache", ".pm"); + apiTemplateFiles.put("api.mustache", ".pm"); + templateDir = "perl"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + 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" + ) + ); + + 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) + "]"; + } + 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; + } + + 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); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // 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 new file mode 100644 index 00000000000..e1bdf1d0d5d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -0,0 +1,184 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.Json; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "php"; + } + + public String getHelp() { + return "Generates a PHP client library."; + } + + public PhpClientCodegen() { + super(); + + invokerPackage = camelize("SwaggerClient"); + + String packagePath = invokerPackage + "-php"; + + modelPackage = packagePath + "/lib/models"; + apiPackage = packagePath + "/lib"; + outputFolder = "generated-code/php"; + modelTemplateFiles.put("model.mustache", ".php"); + apiTemplateFiles.put("api.mustache", ".php"); + templateDir = "php"; + + 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") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + // 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) + "]"; + } + 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 new file mode 100755 index 00000000000..04f3cd6598d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java @@ -0,0 +1,198 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.*; + +public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig { + String module = "client"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "python3"; + } + + public String getHelp() { + return "Generates a Python3 client library."; + } + + public Python3ClientCodegen() { + super(); + outputFolder = "generated-code/python3"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python3"; + + apiPackage = module; + modelPackage = module + ".models"; + + 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) + "]"; + } + 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; + } + + 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("-", "_"); + + // 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); + + // 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) { + // 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); + } + + @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"; + } + + @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 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/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java new file mode 100755 index 00000000000..ba3574d9f67 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -0,0 +1,215 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.io.File; +import java.util.*; + +public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String module = "SwaggerPetstore"; + protected String invokerPackage; + protected String eggPackage; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "python"; + } + + public String getHelp() { + return "Generates a Python client library."; + } + + public PythonClientCodegen() { + super(); + + eggPackage = module + "-python"; + + invokerPackage = eggPackage + File.separatorChar + module; + + outputFolder = "generated-code" + File.separatorChar + "python"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python"; + + apiPackage = invokerPackage + File.separatorChar + "apis"; + modelPackage = invokerPackage + File.separatorChar + "models"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + 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")); + + 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) + "]"; + } + 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; + } + + 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("-", "_"); + + // 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)); + + // for reserved word or word starting with number, append _ + if(reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(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 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) { + // 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)); + } + + @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"; + } + + @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 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/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java new file mode 100644 index 00000000000..2b3962fb528 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -0,0 +1,308 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.Json; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { + protected Set foundationClasses = 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(); + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "qt5cpp"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a qt5 C++ client library."; + } + + public Qt5CPPGenerator() { + super(); + + // set the output folder here + outputFolder = "generated-code/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"); + + modelTemplateFiles.put( + "model-body.mustache", + ".cpp"); + + /** + * 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 + + 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"); + } + + @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\""; + } + + /** + * 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) + ">*"; + } + 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()"; + } + 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"; + } + + + /** + * 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); + } + + @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); + } + } + + @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 new file mode 100644 index 00000000000..1b9bf41aa45 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java @@ -0,0 +1,190 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "retrofit"; + } + + public String getHelp() { + return "Generates a Retrofit client library."; + } + + public RetrofitClientCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "retrofit"; + 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") + ); + + 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) + ">"; + } + 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); + } + + @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; + } + } + } + if(operation.returnType == null) { + operation.returnType = "Void"; + } + } + } + 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 new file mode 100644 index 00000000000..941b4fa64ad --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -0,0 +1,220 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.Json; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String gemName = "swagger_client"; + protected String moduleName = null; + protected String libFolder = "lib"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "ruby"; + } + + public String getHelp() { + return "Generates a Ruby client library."; + } + + /** + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". + */ + public String generateModuleName() { + return camelize(gemName.replaceAll("[^\\w]+", "_")); + } + + public RubyClientCodegen() { + super(); + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; + outputFolder = "generated-code" + File.separatorChar + "ruby"; + modelTemplateFiles.put("model.mustache", ".rb"); + apiTemplateFiles.put("api.mustache", ".rb"); + templateDir = "ruby"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + 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) + "]"; + } + 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; + } + + public String toDefaultValue(Property p) { + return "null"; + } + + @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(); + + // 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); + + 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) { + // 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); + } + + @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"; + } + + @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); + } + + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(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 new file mode 100644 index 00000000000..2acc7c4cd0a --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -0,0 +1,203 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "com.wordnik"; + 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 String getHelp() { + return "Generates a Scala client library."; + } + + 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"; + + 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") + ); + + 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); + + 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.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + 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) + "]"; + } + 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); + } + + @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 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"; + } + + + @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 new file mode 100644 index 00000000000..df2c7e7f0b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -0,0 +1,178 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; +import io.swagger.util.Json; + +import java.util.*; +import java.io.File; + +public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "scalatra"; + } + + public String getHelp() { + return "Generates a Scala server application with Scalatra."; + } + + public ScalatraServerCodegen() { + super(); + outputFolder = "generated-code/scalatra"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "scalatra"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.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") + ); + + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "http://developers.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("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(); + } + 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); + } +} \ 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 new file mode 100644 index 00000000000..4c3a894155b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -0,0 +1,165 @@ +package io.swagger.codegen.languages; + +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 java.util.*; +import java.io.File; + +public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.api"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-spring-mvc-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + protected String title = "Petstore Server"; + + 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(); + outputFolder = "generated-code/javaSpringMVC"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "JavaSpringMVC"; + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + configPackage = "io.swagger.configuration"; + + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("title", title); + additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("configPackage", configPackage); + + 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("swaggerConfig.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerConfig.java")); + supportingFiles.add(new SupportingFile("webApplication.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebApplication.java")); + supportingFiles.add(new SupportingFile("webMvcConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "WebMvcConfiguration.java")); + supportingFiles.add(new SupportingFile("swaggerUiConfiguration.mustache", + (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerUiConfiguration.java")); + supportingFiles.add(new SupportingFile("swagger.properties", + ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + } + + @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); + } + 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(); + } + 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"; + } + } + 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; + } +} + 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 new file mode 100644 index 00000000000..cb403727337 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -0,0 +1,76 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "docs"; + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "dynamic-html"; + } + + public String getHelp() { + return "Generates a dynamic HTML site."; + } + + public StaticDocCodegen() { + super(); + outputFolder = "docs"; + modelTemplateFiles.put("model.mustache", ".html"); + apiTemplateFiles.put("operation.mustache", ".html"); + templateDir = "swagger-static"; + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + 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")); + + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + "operations"; + } + + 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 new file mode 100644 index 00000000000..0b6e269a859 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -0,0 +1,97 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.properties.*; +import io.swagger.util.Json; + +import java.util.*; +import java.io.File; + +public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { + private static final String ALL_OPERATIONS = ""; + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "html"; + } + + public String getHelp() { + return "Generates a static HTML file."; + } + + public StaticHtmlGenerator() { + super(); + outputFolder = "docs"; + templateDir = "htmlDocs"; + + 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) + "]"; + } + 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); + } +} \ 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 new file mode 100644 index 00000000000..525d8f6a9a9 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -0,0 +1,45 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.*; +import io.swagger.models.Swagger; + +import org.apache.commons.io.FileUtils; + +import java.io.File; + +public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + 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); + } + 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 new file mode 100644 index 00000000000..ad25ee69913 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -0,0 +1,44 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.util.*; +import io.swagger.models.Swagger; + +import org.apache.commons.io.FileUtils; + +import java.io.File; + +public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + 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); + } + 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 new file mode 100644 index 00000000000..033781beb36 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java @@ -0,0 +1,250 @@ +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.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 org.apache.commons.lang.StringUtils; + +import javax.annotation.Nullable; +import java.util.*; +import java.io.File; +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"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "swift"; + } + + public String getHelp() { + return "Generates a swift client library."; + } + + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; + + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); + + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); + } + + sourceFolder = appName + "/" + sourceFolder; + + 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")); + + 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(); + } + + @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); + } + + @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); + + return builder.toString(); + } +} \ 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 new file mode 100644 index 00000000000..460befb6609 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -0,0 +1,258 @@ +package io.swagger.codegen.languages; + +import io.swagger.util.Json; +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +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(); + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "tizen"; + } + + public String getHelp() { + return "Generates a Samsung Tizen C++ client library."; + } + + public TizenClientCodegen() { + super(); + outputFolder = "generated-code/tizen"; + 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 = ""; + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long") + ); + languageSpecificPrimitives = new HashSet(); + + additionalProperties().put("prefix", PREFIX); + + 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" + )); + + super.typeMapping = 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"); + + 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"); + } + 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); + } + + @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; + } + 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) + ";"; + } + 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()"; + } + 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"; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); + } + + @Override + public String toApiName(String name) { + return PREFIX + initialCaps(name) + "Api"; + } + + public String toApiFilename(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 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); + } + +} From 0c1657d74435e2f2eb28a6bbede08efa6b34f6a0 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 6 Jun 2015 23:43:34 -0700 Subject: [PATCH 03/22] updated package --- README.md | 4 +- modules/swagger-codegen-cli/pom.xml | 8 +- .../swagger/codegen/SwaggerCodegen.java | 37 -- .../swagger/codegen/cmd/ConfigHelp.java | 49 -- .../wordnik/swagger/codegen/cmd/Generate.java | 156 ------ .../wordnik/swagger/codegen/cmd/Langs.java | 23 - .../com/wordnik/swagger/codegen/cmd/Meta.java | 144 ------ .../src/main/resources/logback.xml | 2 +- .../languages/AkkaScalaClientCodegen.java | 2 +- .../languages/AsyncScalaClientCodegen.java | 2 +- .../codegen/languages/PerlClientCodegen.java | 2 +- .../codegen/languages/PhpClientCodegen.java | 2 +- .../codegen/languages/ScalaClientCodegen.java | 2 +- .../languages/ScalatraServerCodegen.java | 2 +- .../languages/SpringMVCServerCodegen.java | 28 +- .../codegen/languages/StaticDocCodegen.java | 2 +- .../languages/StaticHtmlGenerator.java | 2 +- .../src/main/resources/Java/model.mustache | 2 +- .../src/main/resources/JavaJaxRS/api.mustache | 10 +- .../main/resources/JavaJaxRS/model.mustache | 2 +- .../src/main/resources/JavaJaxRS/web.mustache | 4 +- .../main/resources/JavaSpringMVC/api.mustache | 10 +- .../resources/JavaSpringMVC/model.mustache | 2 +- .../com.wordnik.swagger.codegen.CodegenConfig | 24 - .../resources/android-java/model.mustache | 2 +- .../main/resources/asyncscala/api.mustache | 2 +- .../main/resources/asyncscala/client.mustache | 2 +- .../main/resources/asyncscala/sbt.mustache | 2 +- .../main/resources/codegen/README.mustache | 6 +- .../resources/codegen/generatorClass.mustache | 8 +- .../main/resources/flash/ApiClientEvent.as | 4 +- .../src/main/resources/flash/ApiError.as | 2 +- .../src/main/resources/flash/ApiErrorCodes.as | 2 +- .../src/main/resources/flash/ApiInvoker.as | 8 +- .../src/main/resources/flash/ApiUrlHelper.as | 4 +- .../resources/flash/ApiUserCredentials.as | 2 +- .../src/main/resources/flash/ListWrapper.as | 2 +- .../src/main/resources/flash/Response.as | 2 +- .../src/main/resources/flash/SwaggerApi.as | 4 +- .../src/main/resources/flash/XMLWriter.as | 2 +- .../src/main/resources/flash/api.mustache | 12 +- .../src/main/resources/flash/build.xml | 10 +- .../main/resources/flash/modelList.mustache | 2 +- .../src/main/resources/logback.xml | 2 +- .../main/resources/retrofit/model.mustache | 2 +- .../resources/scalatra/Bootstrap.mustache | 2 +- .../resources/scalatra/ServletApp.mustache | 2 +- .../src/test/scala/SwaggerMigratorTest.scala | 1 - modules/swagger-generator/pom.xml | 27 +- .../wordnik/swagger/generator/Bootstrap.java | 45 -- .../generator/DynamicSwaggerConfig.java | 69 --- .../generator/exception/ApiException.java | 25 - .../exception/BadRequestException.java | 25 - .../exception/NotFoundException.java | 25 - .../swagger/generator/model/ApiResponse.java | 84 ---- .../swagger/generator/model/Generated.java | 36 -- .../generator/model/GeneratorInput.java | 44 -- .../swagger/generator/model/InputOption.java | 65 --- .../swagger/generator/model/ResponseCode.java | 26 - .../swagger/generator/online/Generator.java | 167 ------- .../generator/resource/ExceptionWriter.java | 50 -- .../generator/resource/SwaggerResource.java | 138 ------ .../generator/util/ApiOriginFilter.java | 42 -- .../generator/util/ValidationException.java | 27 - .../generator/util/ValidationMessage.java | 26 - .../swagger/generator/util/ZipUtil.java | 124 ----- .../src/main/resources/logback.xml | 2 +- .../src/main/webapp/WEB-INF/web.xml | 16 +- .../src/test/scala/GeneratorInputTest.scala | 6 +- pom.xml | 4 +- .../client/petstore/android-java/build.gradle | 4 +- .../src/main/csharp/io/swagger/Api/PetApi.cs | 460 +++++++++++++++++- .../main/csharp/io/swagger/Api/StoreApi.cs | 226 ++++++++- .../src/main/csharp/io/swagger/Api/UserApi.cs | 450 ++++++++++++++++- .../csharp/io/swagger/client/ApiClient.cs | 14 +- .../csharp/io/swagger/client/ApiException.cs | 11 + samples/client/petstore/objc/Podfile | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- samples/client/petstore/scala/pom.xml | 2 +- samples/html/index.html | 10 +- .../src/gen/java/io/swagger/api/PetApi.java | 8 - .../src/gen/java/io/swagger/api/StoreApi.java | 4 - .../src/gen/java/io/swagger/api/UserApi.java | 8 - 83 files changed, 1246 insertions(+), 1636 deletions(-) delete mode 100644 modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java delete mode 100644 modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/ConfigHelp.java delete mode 100644 modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java delete mode 100644 modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java delete mode 100644 modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java delete mode 100644 modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java delete mode 100644 modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java diff --git a/README.md b/README.md index 03876e61ed9..ff4d7467ca1 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ Great for creating libraries on your ci server, from the [Swagger Editor](http:/ There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc: ``` -$ ls -1 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ +$ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ AndroidClientCodegen.java AsyncScalaClientCodegen.java CSharpClientCodegen.java @@ -237,7 +237,7 @@ To change, for example, the prefix for the Objective-C generated files, simply s ``` package com.mycompany.swagger.codegen; -import com.wordnik.swagger.codegen.languages.*; +import io.swagger.codegen.languages.*; public class MyObjcCodegen extends ObjcClientCodegen { static { diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 388dd1a8392..8f57c21653f 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -1,9 +1,9 @@ - com.wordnik + io.swagger swagger-codegen-project - 2.1.1-M2-SNAPSHOT + 2.1.1 ../.. 4.0.0 @@ -30,7 +30,7 @@ - com.wordnik.swagger.codegen.SwaggerCodegen + io.swagger.codegen.SwaggerCodegen @@ -74,7 +74,7 @@ - com.wordnik + io.swagger swagger-codegen ${project.version} diff --git a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java deleted file mode 100644 index f2c794776ce..00000000000 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.wordnik.swagger.codegen; - -import com.wordnik.swagger.codegen.cmd.ConfigHelp; -import com.wordnik.swagger.codegen.cmd.Generate; -import com.wordnik.swagger.codegen.cmd.Langs; -import com.wordnik.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 - * - * @since 2.1.3-M1 - */ -public class SwaggerCodegen { - - - public static void main(String[] args) { - Cli.CliBuilder builder = Cli.builder("swagger") - .withDescription("Swagger code generator CLI. More info on swagger.io") - .withDefaultCommand(Langs.class) - .withCommands( - Generate.class, - Meta.class, - Langs.class, - Help.class, - ConfigHelp.class - ); - - builder.build().parse(args).run(); - } -} diff --git a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/ConfigHelp.java deleted file mode 100644 index fbdca12e6e8..00000000000 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/ConfigHelp.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.wordnik.swagger.codegen.cmd; - -import com.wordnik.swagger.codegen.CliOption; -import com.wordnik.swagger.codegen.CodegenConfig; -import io.airlift.airline.Command; -import io.airlift.airline.Option; -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 - */ - 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/com/wordnik/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java deleted file mode 100644 index 3485eb8dd24..00000000000 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.wordnik.swagger.codegen.cmd; - -import com.wordnik.swagger.codegen.CliOption; -import com.wordnik.swagger.codegen.ClientOptInput; -import com.wordnik.swagger.codegen.ClientOpts; -import com.wordnik.swagger.codegen.CodegenConfig; -import com.wordnik.swagger.codegen.DefaultGenerator; -import com.wordnik.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; - -import java.io.File; -import java.util.ServiceLoader; - -import static java.util.ServiceLoader.load; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - -/** - * User: lanwen - * Date: 24.03.15 - * Time: 20:22 - */ - -@Command(name = "generate", description = "Generate code with chosen lang") -public class Generate implements Runnable { - - public static final Logger LOG = LoggerFactory.getLogger(Generate.class); - - public static final String TEMPLATE_DIR_PARAM = "templateDir"; - - @Option(name = {"-v", "--verbose"}, description = "verbose mode") - private boolean verbose; - - @Option(name = {"-l", "--lang"}, title = "language", required = true, - description = "client language to generate (maybe class name in classpath, required)") - private String lang; - - @Option(name = {"-o", "--output"}, title = "output directory", - description = "where to write the generated files (current dir by default)") - private String output = ""; - - @Option(name = {"-i", "--input-spec"}, title = "spec file", required = true, - description = "location of the swagger spec, as URL or file (required)") - private String spec; - - @Option(name = {"-t", "--template-dir"}, title = "template directory", - description = "folder containing the template files") - private String templateDir; - - @Option(name = {"-a", "--auth"}, title = "authorization", - description = "adds authorization headers when fetching the swagger definitions remotely. " + - "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 " + - "the format of name=value,name=value") - private String systemProperties; - - @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; - - @Override - public void run() { - verbosed(verbose); - - setSystemProperties(); - - ClientOptInput input = new ClientOptInput(); - - if (isNotEmpty(auth)) { - input.setAuth(auth); - } - - CodegenConfig config = forName(lang); - config.setOutputDir(new File(output).getAbsolutePath()); - - if (null != templateDir) { - config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); - } - - 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())); - } - } - } - } - - input.setConfig(config); - - Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); - new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); - } - - private void setSystemProperties() { - 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 true parameter, adds system properties which enables debug mode in generator - * @param verbose - if true, enables debug mode - */ - private void verbosed(boolean verbose) { - if (!verbose) { - return; - } - LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + - "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + - "\n - [debugModels] prints models passed to the template engine" + - "\n - [debugOperations] prints operations passed to the template engine" + - "\n - [debugSupportingFiles] prints additional data passed to the template engine"); - - System.setProperty("debugSwagger", ""); - System.setProperty("debugModels", ""); - 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/com/wordnik/swagger/codegen/cmd/Langs.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java deleted file mode 100644 index 7942804d434..00000000000 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.wordnik.swagger.codegen.cmd; - -import ch.lambdaj.collection.LambdaIterable; -import com.wordnik.swagger.codegen.CodegenConfig; -import io.airlift.airline.Command; - -import static ch.lambdaj.Lambda.on; -import static ch.lambdaj.collection.LambdaCollections.with; -import static java.util.ServiceLoader.load; - -/** - * User: lanwen - * Date: 24.03.15 - * Time: 20:25 - */ -@Command(name = "langs", description = "Shows available langs") -public class Langs implements Runnable { - @Override - public void run() { - LambdaIterable langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); - System.out.printf("Available languages: %s%n", langs); - } -} diff --git a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java deleted file mode 100644 index 47843de39ad..00000000000 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.wordnik.swagger.codegen.cmd; - -import ch.lambdaj.function.convert.Converter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.samskivert.mustache.Mustache; -import com.wordnik.swagger.codegen.DefaultGenerator; -import com.wordnik.swagger.codegen.SupportingFile; -import io.airlift.airline.Command; -import io.airlift.airline.Option; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.util.List; -import java.util.Map; - -import static ch.lambdaj.collection.LambdaCollections.with; -import static com.google.common.base.Joiner.on; - -/** - * User: lanwen - * Date: 24.03.15 - * Time: 20:22 - */ - -@Command(name = "meta", description = "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.") -public class Meta implements Runnable { - - private static final Logger LOG = LoggerFactory.getLogger(Meta.class); - - private static final String TEMPLATE_DIR_CLASSPATH = "codegen"; - private static final String MUSTACHE_EXTENSION = ".mustache"; - - @Option(name = {"-o", "--output"}, title = "output directory", - description = "where to write the generated files (current dir by default)") - private String outputFolder = ""; - - @Option(name = {"-n", "--name"}, title = "name", - description = "the human-readable name of the generator") - private String name = "default"; - - @Option(name = {"-p", "--package"}, title = "package", - description = "the package to put the main class into (defaults to com.wordnik.swagger.codegen)") - private String targetPackage = "com.wordnik.swagger.codegen"; - - @Override - public void run() { - final File targetDir = new File(outputFolder); - LOG.info("writing to folder [{}]", targetDir.getAbsolutePath()); - - String mainClass = StringUtils.capitalize(name) + "Generator"; - - List supportingFiles = ImmutableList.of( - new SupportingFile("pom.mustache", "", "pom.xml"), - new SupportingFile("generatorClass.mustache", - on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")), - new SupportingFile("README.mustache", "", "README.md"), - new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"), - new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"), - new SupportingFile("services.mustache", - "src/main/resources/META-INF/services", "com.wordnik.swagger.codegen.CodegenConfig") - ); - - Map data = new ImmutableMap.Builder() - .put("generatorPackage", targetPackage) - .put("generatorClass", mainClass) - .put("name", name) - .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass).build(); - - - with(supportingFiles).convert(processFiles(targetDir, data)); - } - - /** - * Converter method to process supporting files: execute with mustache, - * or simply copy to destination directory - * @param targetDir - destination directory - * @param data - map with additional params needed to process templates - * @return converter object to pass to lambdaj - */ - private Converter processFiles(final File targetDir, final Map data) { - return new Converter() { - private DefaultGenerator generator = new DefaultGenerator(); - - @Override - public File convert(SupportingFile support) { - try { - File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); - File outputFile = new File(destinationFolder, support.destinationFilename); - - String template = generator - .readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); - String formatted = template; - - if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { - LOG.info("writing file to {}", outputFile.getAbsolutePath()); - formatted = Mustache.compiler().withLoader(loader(generator)) - .defaultValue("") - .compile(template) - .execute(data); - } else { - LOG.info("copying file to {}", outputFile.getAbsolutePath()); - } - - FileUtils.writeStringToFile(outputFile, formatted); - return outputFile; - - } catch (IOException e) { - throw new RuntimeException("Can't generate project", e); - } - } - }; - } - - /** - * Creates mustache loader for template using classpath loader - * @param generator - class with reader getter - * @return loader for template - */ - private Mustache.TemplateLoader loader(final DefaultGenerator generator) { - return new Mustache.TemplateLoader() { - public Reader getTemplate(String name) { - return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH - + File.separator + name.concat(MUSTACHE_EXTENSION)); - } - }; - } - - /** - * Converts package name to path on file system - * @param packageName - package name to convert - * @return relative path - */ - private String asPath(String packageName) { - return packageName.replace(".", File.separator); - } -} diff --git a/modules/swagger-codegen-cli/src/main/resources/logback.xml b/modules/swagger-codegen-cli/src/main/resources/logback.xml index 4e86443d8d3..273b46980db 100644 --- a/modules/swagger-codegen-cli/src/main/resources/logback.xml +++ b/modules/swagger-codegen-cli/src/main/resources/logback.xml @@ -5,7 +5,7 @@ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + 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 9300657dc51..fd53c6db3e2 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 @@ -22,7 +22,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon protected String mainPackage = "io.swagger.client"; protected String invokerPackage = mainPackage + ".core"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; 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 aa202060f1e..5e06d3fd3f5 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 @@ -8,7 +8,7 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-async-scala-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; 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 8b4bef52ebe..4e381b112f7 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 @@ -9,7 +9,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "SwaggerClient"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; 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 e1bdf1d0d5d..b82419c450f 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 @@ -9,7 +9,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; 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 2acc7c4cd0a..1d1dc579d78 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 @@ -8,7 +8,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-scala-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; 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 df2c7e7f0b5..aadbf9a7231 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 @@ -9,7 +9,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; 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 4c3a894155b..9120315ab3a 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 @@ -32,7 +32,7 @@ public String getHelp() { } public SpringMVCServerCodegen() { - super(); + super.processOpts(); outputFolder = "generated-code/javaSpringMVC"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); @@ -50,6 +50,22 @@ public SpringMVCServerCodegen() { additionalProperties.put("apiPackage", apiPackage); additionalProperties.put("configPackage", configPackage); + 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")); @@ -73,16 +89,6 @@ public SpringMVCServerCodegen() { supportingFiles.add(new SupportingFile("swagger.properties", ("src.main.resources").replace(".", java.io.File.separator), "swagger.properties")); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); } @Override 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 cb403727337..b751b62147f 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 @@ -8,7 +8,7 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "docs"; 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 0b6e269a859..96d004fe5e1 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 @@ -11,7 +11,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { private static final String ALL_OPERATIONS = ""; protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; + protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/scala"; diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index b6135636597..0e12f514c48 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -3,7 +3,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index a0afd38f634..3216b60d516 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -4,7 +4,7 @@ import {{modelPackage}}.*; import {{package}}.{{classname}}Service; import {{package}}.factories.{{classname}}ServiceFactory; -import com.wordnik.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; @@ -25,7 +25,7 @@ import javax.ws.rs.*; @Path("/{{baseName}}") {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} -@com.wordnik.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") +@io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") {{#operations}} public class {{classname}} { @@ -36,9 +36,9 @@ public class {{classname}} { {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}} - @com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + @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}}, diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index 98901e392bc..300d5e61dd9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -3,7 +3,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache index 752615b76b7..ae6f6d4d692 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache @@ -8,7 +8,7 @@ com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages - com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;{{apiPackage}} + io.swagger.jaxrs.json;io.swagger.jaxrs.listing;{{apiPackage}} com.sun.jersey.spi.container.ContainerRequestFilters @@ -23,7 +23,7 @@ DefaultJaxrsConfig - com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig + io.swagger.jaxrs.config.DefaultJaxrsConfig api.version 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index 007a4a75ccf..d6a24b69311 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -5,11 +5,11 @@ import {{modelPackage}}.*; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.Api; -import com.wordnik.swagger.annotations.ApiOperation; -import com.wordnik.swagger.annotations.ApiParam; -import com.wordnik.swagger.annotations.ApiResponse; -import com.wordnik.swagger.annotations.ApiResponses; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index 98901e392bc..300d5e61dd9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -3,7 +3,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig deleted file mode 100644 index 4dec8a51df5..00000000000 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig +++ /dev/null @@ -1,24 +0,0 @@ -com.wordnik.swagger.codegen.languages.AndroidClientCodegen -com.wordnik.swagger.codegen.languages.AsyncScalaClientCodegen -com.wordnik.swagger.codegen.languages.CSharpClientCodegen -com.wordnik.swagger.codegen.languages.JavaClientCodegen -com.wordnik.swagger.codegen.languages.JaxRSServerCodegen -com.wordnik.swagger.codegen.languages.NodeJSServerCodegen -com.wordnik.swagger.codegen.languages.ObjcClientCodegen -com.wordnik.swagger.codegen.languages.PerlClientCodegen -com.wordnik.swagger.codegen.languages.PhpClientCodegen -com.wordnik.swagger.codegen.languages.PythonClientCodegen -com.wordnik.swagger.codegen.languages.Python3ClientCodegen -com.wordnik.swagger.codegen.languages.Qt5CPPGenerator -com.wordnik.swagger.codegen.languages.RetrofitClientCodegen -com.wordnik.swagger.codegen.languages.RubyClientCodegen -com.wordnik.swagger.codegen.languages.ScalaClientCodegen -com.wordnik.swagger.codegen.languages.ScalatraServerCodegen -com.wordnik.swagger.codegen.languages.SpringMVCServerCodegen -com.wordnik.swagger.codegen.languages.StaticDocCodegen -com.wordnik.swagger.codegen.languages.StaticHtmlGenerator -com.wordnik.swagger.codegen.languages.SwaggerGenerator -com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator -com.wordnik.swagger.codegen.languages.SwiftGenerator -com.wordnik.swagger.codegen.languages.TizenClientCodegen -com.wordnik.swagger.codegen.languages.AkkaScalaClientCodegen 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 0090e74d0dc..6c805a832e4 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/model.mustache @@ -3,7 +3,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index 603676e22bc..cd12ae18806 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -2,7 +2,7 @@ package {{package}} {{#imports}}import {{import}} {{/imports}} -import com.wordnik.swagger.client._ +import io.swagger.client._ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache index ea7efa354cb..7d2093f8609 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache @@ -4,7 +4,7 @@ package {{invokerPackage}} {{/imports}} import {{apiPackage}}._ -import com.wordnik.swagger.client._ +import io.swagger.client._ import java.io.Closeable diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache index b96e132d8a7..aef5e1f389a 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache @@ -3,7 +3,7 @@ organization := "{{package}}" name := "{{projectName}}-client" libraryDependencies ++= Seq( - "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5", + "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", diff --git a/modules/swagger-codegen/src/main/resources/codegen/README.mustache b/modules/swagger-codegen/src/main/resources/codegen/README.mustache index d40b9b35813..a434038ec41 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/README.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/README.mustache @@ -26,7 +26,7 @@ At this point, you've likely generated a client setup. It will include somethin |----- {{name}} // template files |----- META-INF |------ services -|------- com.wordnik.swagger.codegen.CodegenConfig +|------- io.swagger.codegen.CodegenConfig ``` You _will_ need to make changes in at least the following: @@ -46,7 +46,7 @@ mvn package In your generator project. A single jar file will be produced in `target`. You can now use that with codegen: ``` -java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar com.wordnik.swagger.codegen.Codegen -l {{name}} -o ./test +java -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test ``` Now your templates are available to the client generator and you can write output values @@ -67,7 +67,7 @@ the object you have available during client generation: # -DdebugOperations prints operations passed to the template engine # -DdebugSupportingFiles prints additional data passed to the template engine -java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar com.wordnik.swagger.codegen.Codegen -l {{name}} -o ./test +java -DdebugOperations -cp /path/to/swagger-codegen-distribution:/path/to/your/jar io.swagger.codegen.Codegen -l {{name}} -o ./test ``` Will, for example, output the debug info for operations. You can use this info diff --git a/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache index 53b3a60ad1b..788ef78834b 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/generatorClass.mustache @@ -1,7 +1,7 @@ package {{generatorPackage}}; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.properties.*; +import io.swagger.codegen.*; +import io.swagger.models.properties.*; import java.util.*; import java.io.File; @@ -16,7 +16,7 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig * Configures the type of generator. * * @return the CodegenType for this generator - * @see com.wordnik.swagger.codegen.CodegenType + * @see io.swagger.codegen.CodegenType */ public CodegenType getTag() { return CodegenType.CLIENT; @@ -173,7 +173,7 @@ public class {{generatorClass}} extends DefaultCodegen implements CodegenConfig * 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 com.wordnik.swagger.models.properties.Property + * @see io.swagger.models.properties.Property */ @Override public String getSwaggerType(Property p) { diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as b/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as index 313da09ea78..d64cd304d49 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as @@ -1,5 +1,5 @@ -package com.wordnik.swagger.event { -import com.wordnik.swagger.event.Response; +package io.swagger.event { +import io.swagger.event.Response; import flash.events.Event; diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiError.as b/modules/swagger-codegen/src/main/resources/flash/ApiError.as index 13d09415829..c8ac95a5c59 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiError.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiError.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.exception +package io.swagger.exception { public class ApiError extends Error { diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as b/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as index abe12178361..e5ea46480aa 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.exception +package io.swagger.exception { public class ApiErrorCodes { diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as b/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as index 40ad41af65f..897b95a4f6e 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as @@ -1,11 +1,11 @@ -package com.wordnik.swagger.common +package io.swagger.common { import asaxb.xml.bind.ASAXBContext; import asaxb.xml.bind.Unmarshaller; -import com.wordnik.swagger.event.ApiClientEvent; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.ApiUserCredentials; +import io.swagger.event.ApiClientEvent; +import io.swagger.event.Response; +import io.swagger.common.ApiUserCredentials; import flash.events.EventDispatcher; import flash.utils.Dictionary; diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as b/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as index affa1eb0ff9..4333c6c7e4c 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as @@ -1,5 +1,5 @@ -package com.wordnik.swagger.common { -import com.wordnik.swagger.common.ApiUserCredentials; +package io.swagger.common { +import io.swagger.common.ApiUserCredentials; /** * @private diff --git a/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as b/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as index a7536c213e2..118d917a247 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as +++ b/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.common { +package io.swagger.common { /** * Api account credentials. diff --git a/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as b/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as index 1ea2ebead00..b22890ad1d1 100644 --- a/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as +++ b/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.common +package io.swagger.common { public interface ListWrapper { diff --git a/modules/swagger-codegen/src/main/resources/flash/Response.as b/modules/swagger-codegen/src/main/resources/flash/Response.as index 56cceb61959..a43b7980a38 100644 --- a/modules/swagger-codegen/src/main/resources/flash/Response.as +++ b/modules/swagger-codegen/src/main/resources/flash/Response.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.event { +package io.swagger.event { /** * Response contains info on the result of an API invocation. diff --git a/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as b/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as index a78f3105cb1..059de642a74 100644 --- a/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as +++ b/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as @@ -1,6 +1,6 @@ -package com.wordnik.swagger.common +package io.swagger.common { - import com.wordnik.swagger.common.ApiUserCredentials; + import io.swagger.common.ApiUserCredentials; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; diff --git a/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as b/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as index 067f49e6301..0b08066775b 100644 --- a/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as +++ b/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.common +package io.swagger.common { public class XMLWriter { diff --git a/modules/swagger-codegen/src/main/resources/flash/api.mustache b/modules/swagger-codegen/src/main/resources/flash/api.mustache index 647ec763a24..b1f11e92438 100644 --- a/modules/swagger-codegen/src/main/resources/flash/api.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/api.mustache @@ -1,11 +1,11 @@ package {{package}} { -import com.wordnik.swagger.common.ApiInvoker; -import com.wordnik.swagger.exception.ApiErrorCodes; -import com.wordnik.swagger.exception.ApiError; -import com.wordnik.swagger.common.ApiUserCredentials; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.SwaggerApi; +import io.swagger.common.ApiInvoker; +import io.swagger.exception.ApiErrorCodes; +import io.swagger.exception.ApiError; +import io.swagger.common.ApiUserCredentials; +import io.swagger.event.Response; +import io.swagger.common.SwaggerApi; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/flash/build.xml b/modules/swagger-codegen/src/main/resources/flash/build.xml index 6861dd464ec..4f021b0b8b2 100644 --- a/modules/swagger-codegen/src/main/resources/flash/build.xml +++ b/modules/swagger-codegen/src/main/resources/flash/build.xml @@ -62,11 +62,11 @@ - - - - - + + + + + diff --git a/modules/swagger-codegen/src/main/resources/flash/modelList.mustache b/modules/swagger-codegen/src/main/resources/flash/modelList.mustache index b0c3bd73f83..7741902bcaa 100644 --- a/modules/swagger-codegen/src/main/resources/flash/modelList.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/modelList.mustache @@ -1,6 +1,6 @@ package {{package}} { -import com.wordnik.swagger.common.ListWrapper; +import io.swagger.common.ListWrapper; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/logback.xml b/modules/swagger-codegen/src/main/resources/logback.xml index c7d0db9d3a2..bcfc95e538d 100644 --- a/modules/swagger-codegen/src/main/resources/logback.xml +++ b/modules/swagger-codegen/src/main/resources/logback.xml @@ -5,7 +5,7 @@ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + diff --git a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache b/modules/swagger-codegen/src/main/resources/retrofit/model.mustache index f4446d5a1ef..85213ed4c95 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/model.mustache @@ -3,7 +3,7 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache index 64c0b07eb28..5121079424f 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache @@ -1,6 +1,6 @@ import {{apiPackage}}._ import akka.actor.ActorSystem -import com.wordnik.swagger.app.{ResourcesApp, SwaggerApp} +import io.swagger.app.{ResourcesApp, SwaggerApp} import javax.servlet.ServletContext import org.scalatra.LifeCycle diff --git a/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache index f6e53468ec9..423b8644712 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache @@ -1,4 +1,4 @@ -package com.wordnik.swagger.app +package io.swagger.app import _root_.akka.actor.ActorSystem diff --git a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala index 6c78fa147c1..2fce3c45e45 100644 --- a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala +++ b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala @@ -17,6 +17,5 @@ class SwaggerMigratorTest extends FlatSpec with Matchers { it should "read a 1.2 spec" in { val loader = new SwaggerParser() val swagger = loader.read("src/test/resources/1_2/petstore-1.2/api-docs") - Json.prettyPrint(swagger) } } \ No newline at end of file diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index e5b7b2c341f..2bbbffed0ee 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - com.wordnik + io.swagger swagger-codegen-project - 2.1.1-M2-SNAPSHOT + 2.1.1 ../.. swagger-generator @@ -130,12 +130,12 @@ - com.wordnik + io.swagger swagger-jersey2-jaxrs ${swagger-core-version} - com.wordnik + io.swagger swagger-codegen ${project.parent.version} @@ -149,18 +149,7 @@ logback-core ${logback-version} - - org.scalatest - scalatest_2.10 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - + javax.servlet servlet-api @@ -213,6 +202,12 @@ ${scala-test-version} test + + junit + junit + ${junit-version} + test + org.scala-lang scala-library diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java deleted file mode 100644 index 7035b60d1f7..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator; - -import com.wordnik.swagger.models.*; - -import javax.servlet.http.HttpServlet; -import javax.servlet.ServletContext; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; - -public class Bootstrap extends HttpServlet { - public void init(ServletConfig config) throws ServletException { - ServletContext context = config.getServletContext(); - - DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); - bc.setBasePath("/api"); - bc.setTitle("Swagger Generator"); - bc.setDescription("This is an online swagger codegen server. You can find out more " + - "at https://github.com/swagger-api/swagger-codegen or on irc.freenode.net, #swagger." + - "http://helloreverb.com/terms/"); - bc.setTermsOfServiceUrl("http://helloreverb.com/terms/"); - bc.setContact("apiteam@swagger.io"); - bc.setLicense("Apache 2.0"); - bc.setVersion("1.0.0"); - bc.setHost("generator.swagger.io"); - bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); - bc.setResourcePackage("com.wordnik.swagger.generator.resource"); - bc.setScan(true); - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java deleted file mode 100644 index 60983c230ac..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.wordnik.swagger.generator; - -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.parameters.*; -import com.wordnik.swagger.models.properties.*; -import com.wordnik.swagger.codegen.*; - -import com.wordnik.swagger.util.Json; - -import com.wordnik.swagger.jaxrs.config.BeanConfig; - -import java.util.*; - -public class DynamicSwaggerConfig extends BeanConfig { - static List clients = new ArrayList(); - static List servers = new ArrayList(); - static { - List extensions = Codegen.getExtensions(); - for(CodegenConfig config : extensions) { - if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { - clients.add(config.getName()); - } - else if(config.getTag().equals(CodegenType.SERVER)) { - servers.add(config.getName()); - } - } - } - - @Override - public Swagger configure(Swagger swagger) { - Path clientPath = swagger.getPaths().get("/gen/clients/{language}"); - // update the path description based on what clients are available via SPI - if(clientPath != null) { - Operation post = clientPath.getPost(); - Parameter framework = post.getParameters().get(0); - if(framework instanceof PathParameter) { - PathParameter param = (PathParameter) framework; - StringBuilder b = new StringBuilder(); - for(String client : clients) { - if(b.toString().length() > 0) - b.append(", "); - b.append(client); - } - param.setDescription("available clients: " + b.toString()); - } - } - - Path serverPath = swagger.getPaths().get("/gen/servers/{framework}"); - // update the path description based on what servers are available via SPI - if(serverPath != null) { - Operation post = serverPath.getPost(); - Parameter framework = post.getParameters().get(0); - if(framework instanceof PathParameter) { - PathParameter param = (PathParameter) framework; - StringBuilder b = new StringBuilder(); - for(String server : servers) { - if(b.toString().length() > 0) - b.append(", "); - b.append(server); - } - param.setDescription("available clients: " + b.toString()); - } - } - - return swagger.info(getInfo()) - .host(getHost()) - .basePath("/api"); - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java deleted file mode 100644 index 1383c791aac..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.exception; - -public class ApiException extends Exception{ - private int code; - public ApiException (int code, String msg) { - super(msg); - this.code = code; - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java deleted file mode 100644 index c0883b30eda..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.exception; - -public class BadRequestException extends ApiException { - private int code; - public BadRequestException (int code, String msg) { - super(code, msg); - this.code = code; - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java deleted file mode 100644 index e9a302b2f1e..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.exception; - -public class NotFoundException extends ApiException { - private int code; - public NotFoundException (int code, String msg) { - super(code, msg); - this.code = code; - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java deleted file mode 100644 index 1dfc431b073..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.model; - -import javax.xml.bind.annotation.XmlTransient; - -@javax.xml.bind.annotation.XmlRootElement -public class ApiResponse { - 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 ApiResponse(){} - - public ApiResponse(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-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java deleted file mode 100644 index 6436498ac3f..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.model; - -public class Generated { - private String filename; - private String friendlyName; - - public String getFilename() { - return filename; - } - public void setFilename(String filename) { - this.filename = filename; - } - - public String getFriendlyName() { - return friendlyName; - } - public void setFriendlyName(String friendlyName) { - this.friendlyName = friendlyName; - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java deleted file mode 100644 index 9c5a2aa15ce..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.wordnik.swagger.generator.model; - -import com.wordnik.swagger.annotations.ApiModelProperty; -import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; - -import com.fasterxml.jackson.databind.*; - -import java.util.*; - -public class GeneratorInput { - private JsonNode spec; - private Map options; - private String swaggerUrl; - private SecuritySchemeDefinition auth; - - @ApiModelProperty(dataType="Object") - public JsonNode getSpec() { - return spec; - } - public void setSpec(JsonNode spec) { - this.spec = spec; - } - - public Map getOptions() { - return options; - } - public void setOptions(Map options) { - this.options = options; - } - - public String getSwaggerUrl() { - return swaggerUrl; - } - public void setSwaggerUrl(String url) { - this.swaggerUrl = url; - } - - public SecuritySchemeDefinition getSecurityDefinition() { - return auth; - } - public void setSecurityDefinition(SecuritySchemeDefinition auth) { - this.auth = auth; - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java deleted file mode 100644 index deee8e23c69..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.model; - -public class InputOption { - private String name; - private String description; - private Boolean required; - private String defaultValue; - - public InputOption() {} - - public InputOption(String name, String description, String defaultValue, Boolean required) { - this.name = name; - this.description = description; - this.defaultValue = defaultValue; - this.required = required; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setRequired(Boolean required) { - this.required = required; - } - - public Boolean getRequired() { - return required; - } - - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - public String getDefaultValue() { - return defaultValue; - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java deleted file mode 100644 index 77271a6c72f..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.wordnik.swagger.generator.model; - -public class ResponseCode { - private String code; - private String link; - public ResponseCode() {} - - public ResponseCode(String code, String link) { - setCode(code); - setLink(link); - } - - public String getCode() { - return code; - } - public void setCode(String code) { - this.code = code; - } - - public String getLink() { - return link; - } - public void setLink(String link) { - this.link = link; - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java deleted file mode 100644 index 7a161b970bc..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.wordnik.swagger.generator.online; - -import io.swagger.parser.SwaggerParser; - -import com.wordnik.swagger.generator.exception.*; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.generator.model.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.generator.util.ZipUtil; - -import com.fasterxml.jackson.databind.JsonNode; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.List; -import java.util.ArrayList; - -public class Generator { - static Logger LOGGER = LoggerFactory.getLogger(Generator.class); - - public static String generateClient(String language, GeneratorInput opts) throws ApiException { - Swagger swagger; - LOGGER.debug("generate client for " + language); - if(opts == null) { - throw new BadRequestException(400, "No options were supplied"); - } - JsonNode node = opts.getSpec(); - if(node == null) { - if(opts.getSwaggerUrl() != null) { - swagger = new SwaggerParser().read(opts.getSwaggerUrl()); - } - else - throw new BadRequestException(400, "No swagger specification was supplied"); - } - else { - swagger = new SwaggerParser().read(node); - } - if(swagger == null) { - throw new BadRequestException(400, "The swagger specification supplied was not valid"); - } - - ClientOptInput clientOptInput = new ClientOptInput(); - ClientOpts clientOpts = new ClientOpts(); - String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-client"; - String outputFilename = outputFolder + "-bundle.zip"; - - clientOptInput - .opts(clientOpts) - .swagger(swagger); - - CodegenConfig codegenConfig = Codegen.getConfig(language); - if(codegenConfig == null) { - throw new BadRequestException(400, "Unsupported target " + language + " supplied"); - } - - codegenConfig.setOutputDir(outputFolder); - - Json.prettyPrint(clientOpts); - - clientOptInput.setConfig(codegenConfig); - - try{ - List files = new Codegen().opts(clientOptInput).generate(); - if(files.size() > 0) { - List filesToAdd = new ArrayList(); - System.out.println("adding to " + outputFolder); - filesToAdd.add(new File(outputFolder)); - ZipUtil zip = new ZipUtil(); - zip.compressFiles(filesToAdd, outputFilename); - } - else { - throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); - } - } - catch (Exception e) { - throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); - } - return outputFilename; - } - - public static String generateServer(String language, GeneratorInput opts) throws ApiException { - LOGGER.debug("generate server for " + language); - Swagger swagger; - if(opts == null) { - throw new BadRequestException(400, "No options were supplied"); - } - if(opts == null) { - throw new BadRequestException(400, "No options were supplied"); - } - JsonNode node = opts.getSpec(); - if(node == null) { - if(opts.getSwaggerUrl() != null) { - swagger = new SwaggerParser().read(opts.getSwaggerUrl()); - } - else - throw new BadRequestException(400, "No swagger specification was supplied"); - } - else { - swagger = new SwaggerParser().read(node); - } - if(swagger == null) { - throw new BadRequestException(400, "The swagger specification supplied was not valid"); - } - - ClientOptInput clientOptInput = new ClientOptInput(); - ClientOpts clientOpts = new ClientOpts(); - String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-server"; - String outputFilename = outputFolder + "-bundle.zip"; - - clientOptInput - .opts(clientOpts) - .swagger(swagger); - - CodegenConfig codegenConfig = Codegen.getConfig(language); - if(codegenConfig == null) { - throw new BadRequestException(400, "Unsupported target " + language + " supplied"); - } - - codegenConfig.setOutputDir(outputFolder); - - Json.prettyPrint(clientOpts); - - clientOptInput.setConfig(codegenConfig); - - try{ - List files = new Codegen().opts(clientOptInput).generate(); - if(files.size() > 0) { - List filesToAdd = new ArrayList(); - filesToAdd.add(new File(outputFolder)); - ZipUtil zip = new ZipUtil(); - zip.compressFiles(filesToAdd, outputFilename); - } - else { - throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); - } - } - catch (Exception e) { - throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); - } - return outputFilename; - } - - public static InputOption clientOptions(String language) { - return null; - } - - public static InputOption serverOptions(String language) { - return null; - } - - protected static File getTmpFolder() { - try { - File outputFolder = File.createTempFile("codegen-", "-tmp"); - outputFolder.delete(); - outputFolder.mkdir(); - outputFolder.deleteOnExit(); - return outputFolder; - } - catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java deleted file mode 100644 index f052c79f311..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.wordnik.swagger.generator.resource; - -import com.wordnik.swagger.generator.util.ValidationException; - -import com.wordnik.swagger.generator.exception.ApiException; -import com.wordnik.swagger.generator.exception.BadRequestException; -import com.wordnik.swagger.generator.exception.NotFoundException; -import com.wordnik.swagger.generator.model.ApiResponse; - -import javax.ws.rs.ext.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -@Provider -public class ExceptionWriter implements ExceptionMapper { - public Response toResponse(Exception exception) { - if (exception instanceof javax.ws.rs.WebApplicationException) { - javax.ws.rs.WebApplicationException e = (javax.ws.rs.WebApplicationException) exception; - return Response - .status(e.getResponse().getStatus()) - .entity(new ApiResponse(e.getResponse().getStatus(), - exception.getMessage())).build(); - } else if (exception instanceof com.fasterxml.jackson.core.JsonParseException) { - return Response.status(400) - .entity(new ApiResponse(400, "bad input")).build(); - } else if (exception instanceof ValidationException) { - ValidationException e = (ValidationException) exception; - return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); - } else if (exception instanceof NotFoundException) { - return Response - .status(Status.NOT_FOUND) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); - } else if (exception instanceof BadRequestException) { - return Response - .status(Status.BAD_REQUEST) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); - } else if (exception instanceof ApiException) { - return Response - .status(Status.BAD_REQUEST) - .entity(new ApiResponse(ApiResponse.ERROR, exception - .getMessage())).build(); - } else { - return Response.status(500) - .entity(new ApiResponse(500, "something bad happened")) - .build(); - } - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java deleted file mode 100644 index 4dba39bfb9a..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.wordnik.swagger.generator.resource; - -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.generator.util.*; -import com.wordnik.swagger.annotations.*; -import com.wordnik.swagger.generator.model.*; -import com.wordnik.swagger.generator.exception.BadRequestException; -import com.wordnik.swagger.generator.online.Generator; - -import java.io.File; -import java.util.*; - -import javax.ws.rs.*; -import javax.ws.rs.core.*; - -@Path("/gen") -@Api(value = "/gen", description = "Resource for generating swagger components") -public class SwaggerResource { - private static Map fileMap = new HashMap(); - - static List clients = new ArrayList(); - static List servers = new ArrayList(); - static { - List extensions = Codegen.getExtensions(); - for(CodegenConfig config : extensions) { - if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { - clients.add(config.getName()); - } - else if(config.getTag().equals(CodegenType.SERVER)) { - servers.add(config.getName()); - } - } - } - - @GET - @Path("/download/{fileId}") - @Produces({MediaType.APPLICATION_OCTET_STREAM}) - @ApiOperation(value = "Downloads a pre-generated file", - response = String.class, - tags = {"clients", "servers"}) - public Response downloadFile(@PathParam("fileId") String fileId) throws Exception { - Generated g = fileMap.get(fileId); - System.out.println("looking for fileId " + fileId); - System.out.println("got filename " + g.getFilename()); - if(g.getFilename() != null) { - byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(new java.io.File(g.getFilename())); - - return Response.ok(bytes, "application/zip") - .header("Content-Disposition","attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") - .header("Accept-Range", "bytes") - .header("Content-Length", bytes.length) - .build(); - } - else { - return Response.status(404).build(); - } - } - - @POST - @Path("/clients/{language}") - @ApiOperation( - value = "Generates a client library based on the config", - response = ResponseCode.class, - tags = "clients") - public Response generateClient( - @ApiParam(value = "The target language for the client library", allowableValues = "android,java,php,objc,docs", required = true) @PathParam("language") String language, - @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { - - String filename = Generator.generateClient(language, opts); - - if(filename != null) { - String code = String.valueOf(System.currentTimeMillis()); - Generated g = new Generated(); - g.setFilename(filename); - g.setFriendlyName(language + "-client"); - fileMap.put(code, g); - System.out.println(code + ", " + filename); - String link = "http://generator.swagger.io/api/gen/download/" + code; - return Response.ok().entity(new ResponseCode(code, link)).build(); - } - else { - return Response.status(500).build(); - } - } - - @GET - @Path("/clients") - @ApiOperation(value = "Gets languages supported by the client generator", - response = String.class, - responseContainer = "List", - tags = "clients") - public Response clientOptions() { - String[] languages = new String[clients.size()]; - languages = clients.toArray(languages); - return Response.ok().entity(languages).build(); - } - - @GET - @Path("/servers") - @ApiOperation(value = "Gets languages supported by the server generator", - response = String.class, - responseContainer = "List", - tags = "servers") - public Response serverOptions() { - String[] languages = new String[servers.size()]; - languages = servers.toArray(languages); - return Response.ok().entity(languages).build(); - } - - @POST - @Path("/servers/{framework}") - @ApiOperation(value = "Generates a server library for the supplied server framework", - response = ResponseCode.class, - tags = "servers") - public Response generateServerForLanguage( - @ApiParam(value = "framework", allowableValues = "jaxrs,nodejs", required = true) @PathParam("framework") String framework, - @ApiParam(value = "parameters", required = true) GeneratorInput opts) - throws Exception { - if(framework == null) - throw new BadRequestException(400, "Framework is required"); - String filename = Generator.generateServer(framework, opts); - System.out.println("generated name: " + filename); - - if(filename != null) { - String code = String.valueOf(System.currentTimeMillis()); - Generated g = new Generated(); - g.setFilename(filename); - g.setFriendlyName(framework + "-server"); - fileMap.put(code, g); - System.out.println(code + ", " + filename); - String link = "http://generator.swagger.io/api/gen/download/" + code; - return Response.ok().entity(new ResponseCode(code, link)).build(); - } - else { - return Response.status(500).build(); - } - } -} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java deleted file mode 100644 index b9d279d20a8..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.util; - -import java.io.IOException; - -import javax.servlet.*; -import javax.servlet.http.HttpServletResponse; - -public class ApiOriginFilter implements javax.servlet.Filter { - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - HttpServletResponse res = (HttpServletResponse) response; - res.addHeader("Access-Control-Allow-Origin", "*"); - res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - res.addHeader("Access-Control-Allow-Headers", "Content-Type"); - chain.doFilter(request, response); - } - - @Override - public void destroy() { - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java deleted file mode 100644 index 19747367ca0..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.wordnik.swagger.generator.util; - -import java.util.List; - -public class ValidationException extends Exception { - private int code; - private String msg; - private List errors; - - public ValidationException(String msg) { - super(msg); - } - - public int getCode() { - return code; - } - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return msg; - } - public void setMessage(String msg) { - this.msg = msg; - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java deleted file mode 100644 index b64633de2bd..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.wordnik.swagger.generator.util; - -public class ValidationMessage { - private String path, message, severity; - - public String getPath() { - return path; - } - public void setPath(String path) { - this.path = path; - } - - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - public String getSeverity() { - return severity; - } - public void setSeverity(String severity) { - this.severity = severity; - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java deleted file mode 100644 index 1d090bf96d3..00000000000 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - -package com.wordnik.swagger.generator.util; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -/** -* This utility compresses a list of files to standard ZIP format file. -* It is able to compresses all sub files and sub directories, recursively. -* @author Ha Minh Nam -* -*/ -public class ZipUtil { - /** - * A constants for buffer size used to read/write data - */ - private static final int BUFFER_SIZE = 4096; - - /** - * Compresses a collection of files to a destination zip file - * @param listFiles A collection of files and directories - * @param destZipFile The path of the destination zip file - * @throws FileNotFoundException - * @throws IOException - */ - public void compressFiles(List listFiles, String destZipFile) throws FileNotFoundException, IOException { - - ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); - - for (File file : listFiles) { - if (file.isDirectory()) { - addFolderToZip(file, file.getName(), zos); - } else { - addFileToZip(file, zos); - } - } - - zos.flush(); - zos.close(); - } - - /** - * Adds a directory to the current zip output stream - * @param folder the directory to be added - * @param parentFolder the path of parent directory - * @param zos the current zip output stream - * @throws FileNotFoundException - * @throws IOException - */ - private void addFolderToZip(File folder, String parentFolder, - ZipOutputStream zos) throws FileNotFoundException, IOException { - for (File file : folder.listFiles()) { - if (file.isDirectory()) { - addFolderToZip(file, parentFolder + "/" + file.getName(), zos); - continue; - } - - zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); - - BufferedInputStream bis = new BufferedInputStream( - new FileInputStream(file)); - - long bytesRead = 0; - byte[] bytesIn = new byte[BUFFER_SIZE]; - int read = 0; - - while ((read = bis.read(bytesIn)) != -1) { - zos.write(bytesIn, 0, read); - bytesRead += read; - } - - zos.closeEntry(); - - } - } - - /** - * Adds a file to the current zip output stream - * @param file the file to be added - * @param zos the current zip output stream - * @throws FileNotFoundException - * @throws IOException - */ - private void addFileToZip(File file, ZipOutputStream zos) - throws FileNotFoundException, IOException { - zos.putNextEntry(new ZipEntry(file.getName())); - - BufferedInputStream bis = new BufferedInputStream(new FileInputStream( - file)); - - long bytesRead = 0; - byte[] bytesIn = new byte[BUFFER_SIZE]; - int read = 0; - - while ((read = bis.read(bytesIn)) != -1) { - zos.write(bytesIn, 0, read); - bytesRead += read; - } - - zos.closeEntry(); - } -} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/resources/logback.xml b/modules/swagger-generator/src/main/resources/logback.xml index f263bf8bde0..df76cd17b52 100644 --- a/modules/swagger-generator/src/main/resources/logback.xml +++ b/modules/swagger-generator/src/main/resources/logback.xml @@ -5,7 +5,7 @@ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + diff --git a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml index 7b363b797ed..882dc5fb1ea 100644 --- a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml +++ b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml @@ -9,17 +9,17 @@ jersey.config.server.provider.packages - com.wordnik.swagger.jaxrs.json, - com.wordnik.swagger.generator.resource + io.swagger.jaxrs.json, + io.swagger.generator.resource jersey.config.server.provider.classnames - com.wordnik.swagger.online.ExceptionWriter, - com.wordnik.swagger.jersey.listing.ApiListingResourceJSON, - com.wordnik.swagger.jersey.listing.JerseyApiDeclarationProvider, - com.wordnik.swagger.jersey.listing.JerseyResourceListingProvider + io.swagger.online.ExceptionWriter, + io.swagger.jersey.listing.ApiListingResourceJSON, + io.swagger.jersey.listing.JerseyApiDeclarationProvider, + io.swagger.jersey.listing.JerseyResourceListingProvider @@ -36,11 +36,11 @@ ApiOriginFilter - com.wordnik.swagger.generator.util.ApiOriginFilter + io.swagger.generator.util.ApiOriginFilter Bootstrap - com.wordnik.swagger.generator.Bootstrap + io.swagger.generator.Bootstrap 2 diff --git a/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala b/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala index 43e0f234800..f9820d96fa6 100644 --- a/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala +++ b/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala @@ -1,6 +1,6 @@ -import com.wordnik.swagger.generator.online._ -import com.wordnik.swagger.generator.model._ -import com.wordnik.swagger.util.Json +import io.swagger.generator.online._ +import io.swagger.generator.model._ +import io.swagger.util.Json import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/pom.xml b/pom.xml index c8d223cfb2c..610f6baa2e1 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.1-M2-SNAPSHOT + 2.1.1 https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -463,7 +463,7 @@ 1.0.7 - 2.10.4 + 2.11.1 2.3.4 1.5.2-M2 2.1.4 diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 26a00d90da8..16ecd1b4d49 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -56,10 +56,10 @@ dependencies { 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:$httpcore_version") { + compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } - compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } testCompile "junit:junit:$junit_version" diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 1f7ddccfb26..8596800f536 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -1,15 +1,134 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { + + public interface IPetApi { + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + void UpdatePet (Pet Body); + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + Task UpdatePetAsync (Pet Body); + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + void AddPet (Pet Body); + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + Task AddPetAsync (Pet Body); + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// List + List FindPetsByStatus (List Status); + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// List + Task> FindPetsByStatusAsync (List Status); + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// List + List FindPetsByTags (List Tags); + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// List + Task> FindPetsByTagsAsync (List Tags); + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Pet + Pet GetPetById (long? PetId); + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Pet + Task GetPetByIdAsync (long? PetId); + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated/// Updated name of the pet/// Updated status of the pet + /// + void UpdatePetWithForm (string PetId, string Name, string Status); + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated/// Updated name of the pet/// Updated status of the pet + /// + Task UpdatePetWithFormAsync (string PetId, string Name, string Status); + + /// + /// Deletes a pet + /// + /// /// Pet id to delete + /// + void DeletePet (string ApiKey, long? PetId); + + /// + /// Deletes a pet + /// + /// /// Pet id to delete + /// + Task DeletePetAsync (string ApiKey, long? PetId); + + /// + /// uploads an image + /// + /// ID of pet to update/// Additional data to pass to server/// file to upload + /// + void UploadFile (long? PetId, string AdditionalMetadata, string File); + + /// + /// uploads an image + /// + /// ID of pet to update/// Additional data to pass to server/// file to upload + /// + Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File); + + } + /// /// Represents a collection of functions to interact with the API endpoints /// - public class PetApi { + public class PetApi : IPetApi { + /// /// Initializes a new instance of the class. /// @@ -88,7 +207,44 @@ public void UpdatePet (Pet Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); + } + + return; + } + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + public async Task UpdatePetAsync (Pet Body) { + + + + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); } return; @@ -126,7 +282,44 @@ public void AddPet (Pet Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); + } + + return; + } + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + public async Task AddPetAsync (Pet Body) { + + + + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); } return; @@ -164,10 +357,46 @@ public List FindPetsByStatus (List Status) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); } return (List) apiClient.Deserialize(response.Content, typeof(List)); } + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// List + public async Task> FindPetsByStatusAsync (List Status) { + + + + var path = "/pet/findByStatus"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); + } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + } /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. @@ -201,10 +430,46 @@ public List FindPetsByTags (List Tags) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); } return (List) apiClient.Deserialize(response.Content, typeof(List)); } + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// List + public async Task> FindPetsByTagsAsync (List Tags) { + + + + var path = "/pet/findByTags"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); + } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); + } /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions @@ -241,17 +506,54 @@ public Pet GetPetById (long? PetId) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); } return (Pet) apiClient.Deserialize(response.Content, typeof(Pet)); } + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Pet + public async Task GetPetByIdAsync (long? PetId) { + + + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + 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[] { "api_key", "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); + } + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); + } /// /// Updates a pet in the store with form data /// - /// ID of pet that needs to be updated - /// Updated name of the pet - /// Updated status of the pet + /// ID of pet that needs to be updated/// Updated name of the pet/// Updated status of the pet /// public void UpdatePetWithForm (string PetId, string Name, string Status) { @@ -285,7 +587,49 @@ public void UpdatePetWithForm (string PetId, string Name, string Status) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); + } + + return; + } + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated/// Updated name of the pet/// Updated status of the pet + /// + public async Task UpdatePetWithFormAsync (string PetId, string Name, string Status) { + + + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + if (Name != null) formParams.Add("name", apiClient.ParameterToString(Name)); // form parameter + if (Status != null) formParams.Add("status", apiClient.ParameterToString(Status)); // form parameter + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); } return; @@ -294,8 +638,7 @@ public void UpdatePetWithForm (string PetId, string Name, string Status) { /// /// Deletes a pet /// - /// - /// Pet id to delete + /// /// Pet id to delete /// public void DeletePet (string ApiKey, long? PetId) { @@ -328,7 +671,48 @@ public void DeletePet (string ApiKey, long? PetId) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); + } + + return; + } + + /// + /// Deletes a pet + /// + /// /// Pet id to delete + /// + public async Task DeletePetAsync (string ApiKey, long? PetId) { + + + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + if (ApiKey != null) headerParams.Add("api_key", apiClient.ParameterToString(ApiKey)); // header parameter + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); } return; @@ -337,9 +721,7 @@ public void DeletePet (string ApiKey, long? PetId) { /// /// uploads an image /// - /// ID of pet to update - /// Additional data to pass to server - /// file to upload + /// ID of pet to update/// Additional data to pass to server/// file to upload /// public void UploadFile (long? PetId, string AdditionalMetadata, string File) { @@ -373,12 +755,54 @@ public void UploadFile (long? PetId, string AdditionalMetadata, string File) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); + } + + return; + } + + /// + /// uploads an image + /// + /// ID of pet to update/// Additional data to pass to server/// file to upload + /// + public async Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File) { + + + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); + + + var path = "/pet/{petId}/uploadImage"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + if (AdditionalMetadata != null) formParams.Add("additionalMetadata", apiClient.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) fileParams.Add("file", File); + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); } return; } - } + } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index a789b3502a0..8cd175a6227 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -1,15 +1,78 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { + + public interface IStoreApi { + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + + /// Dictionary + Dictionary GetInventory (); + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + + /// Dictionary + Task> GetInventoryAsync (); + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Order + Order PlaceOrder (Order Body); + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Order + Task PlaceOrderAsync (Order Body); + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// Order + Order GetOrderById (string OrderId); + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// Order + Task GetOrderByIdAsync (string OrderId); + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + void DeleteOrder (string OrderId); + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + Task DeleteOrderAsync (string OrderId); + + } + /// /// Represents a collection of functions to interact with the API endpoints /// - public class StoreApi { + public class StoreApi : IStoreApi { + /// /// Initializes a new instance of the class. /// @@ -59,6 +122,7 @@ public String GetBasePath(String basePath) { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// + /// Dictionary public Dictionary GetInventory () { @@ -86,10 +150,45 @@ public String GetBasePath(String basePath) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); } return (Dictionary) apiClient.Deserialize(response.Content, typeof(Dictionary)); } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + + /// Dictionary + public async Task> GetInventoryAsync () { + + + + var path = "/store/inventory"; + path = path.Replace("{format}", "json"); + + + 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[] { "api_key" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); + } + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); + } /// /// Place an order for a pet @@ -123,10 +222,46 @@ public Order PlaceOrder (Order Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); } return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Order + public async Task PlaceOrderAsync (Order Body) { + + + + var path = "/store/order"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); + } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + } /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -163,10 +298,49 @@ public Order GetOrderById (string OrderId) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); } return (Order) apiClient.Deserialize(response.Content, typeof(Order)); } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// Order + public async Task GetOrderByIdAsync (string OrderId) { + + + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); + + + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + + 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[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); + } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); + } /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -203,12 +377,52 @@ public void DeleteOrder (string OrderId) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); + } + + return; + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + public async Task DeleteOrderAsync (string OrderId) { + + + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); + + + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); + + + 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[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); } return; } - } + } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 35de41c2257..154ad67240c 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -1,15 +1,134 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { + + public interface IUserApi { + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + void CreateUser (User Body); + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + Task CreateUserAsync (User Body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + void CreateUsersWithArrayInput (List Body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + Task CreateUsersWithArrayInputAsync (List Body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + void CreateUsersWithListInput (List Body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + Task CreateUsersWithListInputAsync (List Body); + + /// + /// Logs user into the system + /// + /// The user name for login/// The password for login in clear text + /// string + string LoginUser (string Username, string Password); + + /// + /// Logs user into the system + /// + /// The user name for login/// The password for login in clear text + /// string + Task LoginUserAsync (string Username, string Password); + + /// + /// Logs out current logged in user session + /// + + /// + void LogoutUser (); + + /// + /// Logs out current logged in user session + /// + + /// + Task LogoutUserAsync (); + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// User + User GetUserByName (string Username); + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// User + Task GetUserByNameAsync (string Username); + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted/// Updated user object + /// + void UpdateUser (string Username, User Body); + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted/// Updated user object + /// + Task UpdateUserAsync (string Username, User Body); + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + void DeleteUser (string Username); + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + Task DeleteUserAsync (string Username); + + } + /// /// Represents a collection of functions to interact with the API endpoints /// - public class UserApi { + public class UserApi : IUserApi { + /// /// Initializes a new instance of the class. /// @@ -88,7 +207,44 @@ public void CreateUser (User Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); + } + + return; + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + public async Task CreateUserAsync (User Body) { + + + + var path = "/user"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); } return; @@ -126,7 +282,44 @@ public void CreateUsersWithArrayInput (List Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); + } + + return; + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + public async Task CreateUsersWithArrayInputAsync (List Body) { + + + + var path = "/user/createWithArray"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); } return; @@ -164,7 +357,44 @@ public void CreateUsersWithListInput (List Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); + } + + return; + } + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + public async Task CreateUsersWithListInputAsync (List Body) { + + + + var path = "/user/createWithList"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); } return; @@ -173,8 +403,7 @@ public void CreateUsersWithListInput (List Body) { /// /// Logs user into the system /// - /// The user name for login - /// The password for login in clear text + /// The user name for login/// The password for login in clear text /// string public string LoginUser (string Username, string Password) { @@ -204,14 +433,52 @@ public string LoginUser (string Username, string Password) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); } return (string) apiClient.Deserialize(response.Content, typeof(string)); } + + /// + /// Logs user into the system + /// + /// The user name for login/// The password for login in clear text + /// string + public async Task LoginUserAsync (string Username, string Password) { + + + + var path = "/user/login"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter + if (Password != null) queryParams.Add("password", apiClient.ParameterToString(Password)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); + } + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); + } /// /// Logs out current logged in user session /// + /// public void LogoutUser () { @@ -239,7 +506,43 @@ public void LogoutUser () { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); + } + + return; + } + + /// + /// Logs out current logged in user session + /// + + /// + public async Task LogoutUserAsync () { + + + + var path = "/user/logout"; + path = path.Replace("{format}", "json"); + + + 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[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); } return; @@ -280,16 +583,54 @@ public User GetUserByName (string Username) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); } return (User) apiClient.Deserialize(response.Content, typeof(User)); } + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// User + public async Task GetUserByNameAsync (string Username) { + + + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + 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[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); + } + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); + } /// /// Updated user This can only be done by the logged in user. /// - /// name that need to be deleted - /// Updated user object + /// name that need to be deleted/// Updated user object /// public void UpdateUser (string Username, User Body) { @@ -322,7 +663,48 @@ public void UpdateUser (string Username, User Body) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); + } + + return; + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted/// Updated user object + /// + public async Task UpdateUserAsync (string Username, User Body) { + + + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = apiClient.Serialize(Body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); } return; @@ -363,12 +745,52 @@ public void DeleteUser (string Username) { IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); + } + + return; + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + public async Task DeleteUserAsync (string Username) { + + + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); + + + 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[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); } return; } - } + } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs index 39d59f063f2..b001a38845c 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiClient.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Net; using System.Text; +using System.Threading.Tasks; using Newtonsoft.Json; using RestSharp; @@ -36,7 +37,16 @@ public ApiClient(String basePath="http://petstore.swagger.io/v2") { private Dictionary defaultHeaderMap = new Dictionary(); - public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + 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); @@ -67,7 +77,7 @@ public Object CallApi(String Path, RestSharp.Method Method, DictionaryThe 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; } + /// /// Initializes a new instance of the class. /// @@ -26,6 +32,11 @@ 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; + } + } } diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index 9a1ad058940..61b00df61ad 100644 --- a/samples/client/petstore/objc/Podfile +++ b/samples/client/petstore/objc/Podfile @@ -1,5 +1,5 @@ platform :ios, '6.0' -xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' +xcodeproj 'swaggerClient/swaggerClient.xcodeproj' pod 'AFNetworking', '~> 2.1' pod 'JSONModel', '~> 1.0' pod 'ISO8601' diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java index 66a02367c90..3ae04239744 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import com.wordnik.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index b6dd4493a0b..74bb2feed86 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - com.wordnik + io.swagger swagger-scala-client jar swagger-scala-client diff --git a/samples/html/index.html b/samples/html/index.html index 3cfd67d8d59..e595d3ea40d 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -301,7 +301,7 @@

Example data

Example data

Content-Type: application/xml
-
not implemented com.wordnik.swagger.models.properties.MapProperty@3e
+
not implemented io.swagger.models.properties.MapProperty@3e

@@ -332,7 +332,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-23T15:56:49.441+0000" + "shipDate" : "2015-06-07T06:42:05.171+0000" }

Example data

@@ -341,7 +341,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-23T08:56:49.444Z</shipDate> + <shipDate>2015-06-06T23:42:05.174Z</shipDate> <status>string</status> <complete>true</complete> </Order> @@ -375,7 +375,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-23T15:56:49.445+0000" + "shipDate" : "2015-06-07T06:42:05.175+0000" }

Example data

@@ -384,7 +384,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-23T08:56:49.445Z</shipDate> + <shipDate>2015-06-06T23:42:05.176Z</shipDate> <status>string</status> <complete>true</complete> </Order> diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index d5fd9c48e07..e67773ed634 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -44,7 +44,6 @@ public class PetApi { public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - // do some magic! return delegate.updatePet(body); } @POST @@ -57,7 +56,6 @@ public Response updatePet(@ApiParam(value = "Pet object that needs to be added t public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - // do some magic! return delegate.addPet(body); } @GET @@ -72,7 +70,6 @@ public Response addPet(@ApiParam(value = "Pet object that needs to be added to t public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { - // do some magic! return delegate.findPetsByStatus(status); } @GET @@ -87,7 +84,6 @@ public Response findPetsByStatus(@ApiParam(value = "Status values that need to b public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) throws NotFoundException { - // do some magic! return delegate.findPetsByTags(tags); } @GET @@ -104,7 +100,6 @@ public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryPara public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) throws NotFoundException { - // do some magic! return delegate.getPetById(petId); } @POST @@ -119,7 +114,6 @@ public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) throws NotFoundException { - // do some magic! return delegate.updatePetWithForm(petId,name,status); } @DELETE @@ -133,7 +127,6 @@ public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String apiKey, @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) throws NotFoundException { - // do some magic! return delegate.deletePet(apiKey,petId); } @POST @@ -149,7 +142,6 @@ public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true @ApiParam(value = "file to upload") @FormDataParam("file") InputStream inputStream, @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail) throws NotFoundException { - // do some magic! return delegate.uploadFile(petId,additionalMetadata,fileDetail); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index 7c8dff02ffa..790d4c4c3f6 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -40,7 +40,6 @@ public class StoreApi { public Response getInventory() throws NotFoundException { - // do some magic! return delegate.getInventory(); } @POST @@ -55,7 +54,6 @@ public Response getInventory() public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { - // do some magic! return delegate.placeOrder(body); } @GET @@ -72,7 +70,6 @@ public Response placeOrder(@ApiParam(value = "order placed for purchasing the pe public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - // do some magic! return delegate.getOrderById(orderId); } @DELETE @@ -87,7 +84,6 @@ public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetch public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - // do some magic! return delegate.deleteOrder(orderId); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index f0c5493f848..979476c41c6 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -40,7 +40,6 @@ public class UserApi { public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { - // do some magic! return delegate.createUser(body); } @POST @@ -53,7 +52,6 @@ public Response createUser(@ApiParam(value = "Created user object" ) User body) public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - // do some magic! return delegate.createUsersWithArrayInput(body); } @POST @@ -66,7 +64,6 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - // do some magic! return delegate.createUsersWithListInput(body); } @GET @@ -82,7 +79,6 @@ public Response createUsersWithListInput(@ApiParam(value = "List of user object" public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) throws NotFoundException { - // do some magic! return delegate.loginUser(username,password); } @GET @@ -95,7 +91,6 @@ public Response loginUser(@ApiParam(value = "The user name for login") @QueryPar public Response logoutUser() throws NotFoundException { - // do some magic! return delegate.logoutUser(); } @GET @@ -112,7 +107,6 @@ public Response logoutUser() public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) throws NotFoundException { - // do some magic! return delegate.getUserByName(username); } @PUT @@ -128,7 +122,6 @@ public Response getUserByName(@ApiParam(value = "The name that needs to be fetch public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, @ApiParam(value = "Updated user object" ) User body) throws NotFoundException { - // do some magic! return delegate.updateUser(username,body); } @DELETE @@ -143,7 +136,6 @@ public Response updateUser(@ApiParam(value = "name that need to be deleted",requ public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) throws NotFoundException { - // do some magic! return delegate.deleteUser(username); } } From 1df3ed44870db1906a5f1c97a19fd11b23bb7db3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 6 Jun 2015 23:44:20 -0700 Subject: [PATCH 04/22] repackaged --- .../io/swagger/codegen/SwaggerCodegen.java | 37 ++++ .../io/swagger/codegen/cmd/ConfigHelp.java | 49 +++++ .../java/io/swagger/codegen/cmd/Generate.java | 156 ++++++++++++++++ .../java/io/swagger/codegen/cmd/Langs.java | 23 +++ .../java/io/swagger/codegen/cmd/Meta.java | 144 +++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 24 +++ .../java/io/swagger/generator/Bootstrap.java | 45 +++++ .../generator/DynamicSwaggerConfig.java | 69 ++++++++ .../generator/exception/ApiException.java | 25 +++ .../exception/BadRequestException.java | 25 +++ .../exception/NotFoundException.java | 25 +++ .../swagger/generator/model/ApiResponse.java | 84 +++++++++ .../io/swagger/generator/model/Generated.java | 36 ++++ .../generator/model/GeneratorInput.java | 44 +++++ .../swagger/generator/model/InputOption.java | 65 +++++++ .../swagger/generator/model/ResponseCode.java | 26 +++ .../swagger/generator/online/Generator.java | 167 ++++++++++++++++++ .../generator/resource/ExceptionWriter.java | 50 ++++++ .../generator/resource/SwaggerResource.java | 138 +++++++++++++++ .../generator/util/ApiOriginFilter.java | 42 +++++ .../generator/util/ValidationException.java | 27 +++ .../generator/util/ValidationMessage.java | 26 +++ .../io/swagger/generator/util/ZipUtil.java | 124 +++++++++++++ 23 files changed, 1451 insertions(+) create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java create mode 100644 modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java create mode 100644 modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java create mode 100644 modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java 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 new file mode 100644 index 00000000000..62f0b5cb7e2 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/SwaggerCodegen.java @@ -0,0 +1,37 @@ +package io.swagger.codegen; + +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 + * + * @since 2.1.3-M1 + */ +public class SwaggerCodegen { + + + public static void main(String[] args) { + Cli.CliBuilder builder = Cli.builder("swagger") + .withDescription("Swagger code generator CLI. More info on swagger.io") + .withDefaultCommand(Langs.class) + .withCommands( + Generate.class, + Meta.class, + Langs.class, + Help.class, + ConfigHelp.class + ); + + builder.build().parse(args).run(); + } +} 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 new file mode 100644 index 00000000000..54fbfac6e7a --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -0,0 +1,49 @@ +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 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 + */ + 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/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java new file mode 100644 index 00000000000..497cba64511 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -0,0 +1,156 @@ +package io.swagger.codegen.cmd; + +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; + +import java.io.File; +import java.util.ServiceLoader; + +import static java.util.ServiceLoader.load; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:22 + */ + +@Command(name = "generate", description = "Generate code with chosen lang") +public class Generate implements Runnable { + + public static final Logger LOG = LoggerFactory.getLogger(Generate.class); + + public static final String TEMPLATE_DIR_PARAM = "templateDir"; + + @Option(name = {"-v", "--verbose"}, description = "verbose mode") + private boolean verbose; + + @Option(name = {"-l", "--lang"}, title = "language", required = true, + description = "client language to generate (maybe class name in classpath, required)") + private String lang; + + @Option(name = {"-o", "--output"}, title = "output directory", + description = "where to write the generated files (current dir by default)") + private String output = ""; + + @Option(name = {"-i", "--input-spec"}, title = "spec file", required = true, + description = "location of the swagger spec, as URL or file (required)") + private String spec; + + @Option(name = {"-t", "--template-dir"}, title = "template directory", + description = "folder containing the template files") + private String templateDir; + + @Option(name = {"-a", "--auth"}, title = "authorization", + description = "adds authorization headers when fetching the swagger definitions remotely. " + + "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 " + + "the format of name=value,name=value") + private String systemProperties; + + @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; + + @Override + public void run() { + verbosed(verbose); + + setSystemProperties(); + + ClientOptInput input = new ClientOptInput(); + + if (isNotEmpty(auth)) { + input.setAuth(auth); + } + + CodegenConfig config = forName(lang); + config.setOutputDir(new File(output).getAbsolutePath()); + + if (null != templateDir) { + config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); + } + + 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())); + } + } + } + } + + input.setConfig(config); + + Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); + new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); + } + + private void setSystemProperties() { + 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 true parameter, adds system properties which enables debug mode in generator + * @param verbose - if true, enables debug mode + */ + private void verbosed(boolean verbose) { + if (!verbose) { + return; + } + LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + + "\n - [debugModels] prints models passed to the template engine" + + "\n - [debugOperations] prints operations passed to the template engine" + + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); + + System.setProperty("debugSwagger", ""); + System.setProperty("debugModels", ""); + 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 new file mode 100644 index 00000000000..5627b6c7ac8 --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Langs.java @@ -0,0 +1,23 @@ +package io.swagger.codegen.cmd; + +import ch.lambdaj.collection.LambdaIterable; +import io.swagger.codegen.CodegenConfig; +import io.airlift.airline.Command; + +import static ch.lambdaj.Lambda.on; +import static ch.lambdaj.collection.LambdaCollections.with; +import static java.util.ServiceLoader.load; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:25 + */ +@Command(name = "langs", description = "Shows available langs") +public class Langs implements Runnable { + @Override + public void run() { + LambdaIterable langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); + System.out.printf("Available languages: %s%n", langs); + } +} 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 new file mode 100644 index 00000000000..4a875b7199e --- /dev/null +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Meta.java @@ -0,0 +1,144 @@ +package io.swagger.codegen.cmd; + +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 org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.List; +import java.util.Map; + +import static ch.lambdaj.collection.LambdaCollections.with; +import static com.google.common.base.Joiner.on; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:22 + */ + +@Command(name = "meta", description = "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.") +public class Meta implements Runnable { + + private static final Logger LOG = LoggerFactory.getLogger(Meta.class); + + private static final String TEMPLATE_DIR_CLASSPATH = "codegen"; + private static final String MUSTACHE_EXTENSION = ".mustache"; + + @Option(name = {"-o", "--output"}, title = "output directory", + description = "where to write the generated files (current dir by default)") + private String outputFolder = ""; + + @Option(name = {"-n", "--name"}, title = "name", + description = "the human-readable name of the generator") + private String name = "default"; + + @Option(name = {"-p", "--package"}, title = "package", + description = "the package to put the main class into (defaults to io.swagger.codegen)") + private String targetPackage = "io.swagger.codegen"; + + @Override + public void run() { + final File targetDir = new File(outputFolder); + LOG.info("writing to folder [{}]", targetDir.getAbsolutePath()); + + String mainClass = StringUtils.capitalize(name) + "Generator"; + + List supportingFiles = ImmutableList.of( + new SupportingFile("pom.mustache", "", "pom.xml"), + new SupportingFile("generatorClass.mustache", + on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")), + new SupportingFile("README.mustache", "", "README.md"), + new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"), + new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"), + new SupportingFile("services.mustache", + "src/main/resources/META-INF/services", "io.swagger.codegen.CodegenConfig") + ); + + Map data = new ImmutableMap.Builder() + .put("generatorPackage", targetPackage) + .put("generatorClass", mainClass) + .put("name", name) + .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass).build(); + + + with(supportingFiles).convert(processFiles(targetDir, data)); + } + + /** + * Converter method to process supporting files: execute with mustache, + * or simply copy to destination directory + * @param targetDir - destination directory + * @param data - map with additional params needed to process templates + * @return converter object to pass to lambdaj + */ + private Converter processFiles(final File targetDir, final Map data) { + return new Converter() { + private DefaultGenerator generator = new DefaultGenerator(); + + @Override + public File convert(SupportingFile support) { + try { + File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); + File outputFile = new File(destinationFolder, support.destinationFilename); + + String template = generator + .readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); + String formatted = template; + + if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { + LOG.info("writing file to {}", outputFile.getAbsolutePath()); + formatted = Mustache.compiler().withLoader(loader(generator)) + .defaultValue("") + .compile(template) + .execute(data); + } else { + LOG.info("copying file to {}", outputFile.getAbsolutePath()); + } + + FileUtils.writeStringToFile(outputFile, formatted); + return outputFile; + + } catch (IOException e) { + throw new RuntimeException("Can't generate project", e); + } + } + }; + } + + /** + * Creates mustache loader for template using classpath loader + * @param generator - class with reader getter + * @return loader for template + */ + private Mustache.TemplateLoader loader(final DefaultGenerator generator) { + return new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + + File.separator + name.concat(MUSTACHE_EXTENSION)); + } + }; + } + + /** + * Converts package name to path on file system + * @param packageName - package name to convert + * @return relative path + */ + private String asPath(String packageName) { + return packageName.replace(".", File.separator); + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig new file mode 100644 index 00000000000..8bbdbc8d140 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -0,0 +1,24 @@ +io.swagger.codegen.languages.AndroidClientCodegen +io.swagger.codegen.languages.AsyncScalaClientCodegen +io.swagger.codegen.languages.CSharpClientCodegen +io.swagger.codegen.languages.JavaClientCodegen +io.swagger.codegen.languages.JaxRSServerCodegen +io.swagger.codegen.languages.NodeJSServerCodegen +io.swagger.codegen.languages.ObjcClientCodegen +io.swagger.codegen.languages.PerlClientCodegen +io.swagger.codegen.languages.PhpClientCodegen +io.swagger.codegen.languages.PythonClientCodegen +io.swagger.codegen.languages.Python3ClientCodegen +io.swagger.codegen.languages.Qt5CPPGenerator +io.swagger.codegen.languages.RetrofitClientCodegen +io.swagger.codegen.languages.RubyClientCodegen +io.swagger.codegen.languages.ScalaClientCodegen +io.swagger.codegen.languages.ScalatraServerCodegen +io.swagger.codegen.languages.SpringMVCServerCodegen +io.swagger.codegen.languages.StaticDocCodegen +io.swagger.codegen.languages.StaticHtmlGenerator +io.swagger.codegen.languages.SwaggerGenerator +io.swagger.codegen.languages.SwaggerYamlGenerator +io.swagger.codegen.languages.SwiftGenerator +io.swagger.codegen.languages.TizenClientCodegen +io.swagger.codegen.languages.AkkaScalaClientCodegen diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java new file mode 100644 index 00000000000..8a5d0bcb324 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -0,0 +1,45 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator; + +import io.swagger.models.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + public void init(ServletConfig config) throws ServletException { + ServletContext context = config.getServletContext(); + + DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); + bc.setBasePath("/api"); + bc.setTitle("Swagger Generator"); + bc.setDescription("This is an online swagger codegen server. You can find out more " + + "at https://github.com/swagger-api/swagger-codegen or on irc.freenode.net, #swagger." + + "http://helloreverb.com/terms/"); + bc.setTermsOfServiceUrl("http://helloreverb.com/terms/"); + bc.setContact("apiteam@swagger.io"); + bc.setLicense("Apache 2.0"); + bc.setVersion("1.0.0"); + bc.setHost("generator.swagger.io"); + bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); + bc.setResourcePackage("io.swagger.generator.resource"); + bc.setScan(true); + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java new file mode 100644 index 00000000000..5cdc75ed9f5 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java @@ -0,0 +1,69 @@ +package io.swagger.generator; + +import io.swagger.models.*; +import io.swagger.models.parameters.*; +import io.swagger.models.properties.*; +import io.swagger.codegen.*; + +import io.swagger.util.Json; + +import io.swagger.jaxrs.config.BeanConfig; + +import java.util.*; + +public class DynamicSwaggerConfig extends BeanConfig { + static List clients = new ArrayList(); + static List servers = new ArrayList(); + static { + List extensions = Codegen.getExtensions(); + for(CodegenConfig config : extensions) { + if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + clients.add(config.getName()); + } + else if(config.getTag().equals(CodegenType.SERVER)) { + servers.add(config.getName()); + } + } + } + + @Override + public Swagger configure(Swagger swagger) { + Path clientPath = swagger.getPaths().get("/gen/clients/{language}"); + // update the path description based on what clients are available via SPI + if(clientPath != null) { + Operation post = clientPath.getPost(); + Parameter framework = post.getParameters().get(0); + if(framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + StringBuilder b = new StringBuilder(); + for(String client : clients) { + if(b.toString().length() > 0) + b.append(", "); + b.append(client); + } + param.setDescription("available clients: " + b.toString()); + } + } + + Path serverPath = swagger.getPaths().get("/gen/servers/{framework}"); + // update the path description based on what servers are available via SPI + if(serverPath != null) { + Operation post = serverPath.getPost(); + Parameter framework = post.getParameters().get(0); + if(framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + StringBuilder b = new StringBuilder(); + for(String server : servers) { + if(b.toString().length() > 0) + b.append(", "); + b.append(server); + } + param.setDescription("available clients: " + b.toString()); + } + } + + return swagger.info(getInfo()) + .host(getHost()) + .basePath("/api"); + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java new file mode 100644 index 00000000000..1ed3e84af41 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.exception; + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java new file mode 100644 index 00000000000..70db17379e6 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.exception; + +public class BadRequestException extends ApiException { + private int code; + public BadRequestException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java new file mode 100644 index 00000000000..119a7307437 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -0,0 +1,25 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.exception; + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java new file mode 100644 index 00000000000..88661f45bf5 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -0,0 +1,84 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.model; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponse { + 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 ApiResponse(){} + + public ApiResponse(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-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java new file mode 100644 index 00000000000..95786cf8b76 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -0,0 +1,36 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.model; + +public class Generated { + private String filename; + private String friendlyName; + + public String getFilename() { + return filename; + } + public void setFilename(String filename) { + this.filename = filename; + } + + public String getFriendlyName() { + return friendlyName; + } + public void setFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java new file mode 100644 index 00000000000..8adb1f3ecf0 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java @@ -0,0 +1,44 @@ +package io.swagger.generator.model; + +import io.swagger.annotations.ApiModelProperty; +import io.swagger.models.auth.SecuritySchemeDefinition; + +import com.fasterxml.jackson.databind.*; + +import java.util.*; + +public class GeneratorInput { + private JsonNode spec; + private Map options; + private String swaggerUrl; + private SecuritySchemeDefinition auth; + + @ApiModelProperty(dataType="Object") + public JsonNode getSpec() { + return spec; + } + public void setSpec(JsonNode spec) { + this.spec = spec; + } + + public Map getOptions() { + return options; + } + public void setOptions(Map options) { + this.options = options; + } + + public String getSwaggerUrl() { + return swaggerUrl; + } + public void setSwaggerUrl(String url) { + this.swaggerUrl = url; + } + + public SecuritySchemeDefinition getSecurityDefinition() { + return auth; + } + public void setSecurityDefinition(SecuritySchemeDefinition auth) { + this.auth = auth; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java new file mode 100644 index 00000000000..6ed89a654e6 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -0,0 +1,65 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.model; + +public class InputOption { + private String name; + private String description; + private Boolean required; + private String defaultValue; + + public InputOption() {} + + public InputOption(String name, String description, String defaultValue, Boolean required) { + this.name = name; + this.description = description; + this.defaultValue = defaultValue; + this.required = required; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public Boolean getRequired() { + return required; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDefaultValue() { + return defaultValue; + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java new file mode 100644 index 00000000000..50da05250d9 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java @@ -0,0 +1,26 @@ +package io.swagger.generator.model; + +public class ResponseCode { + private String code; + private String link; + public ResponseCode() {} + + public ResponseCode(String code, String link) { + setCode(code); + setLink(link); + } + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + + public String getLink() { + return link; + } + public void setLink(String link) { + this.link = link; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java new file mode 100644 index 00000000000..fd0abb37d6d --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -0,0 +1,167 @@ +package io.swagger.generator.online; + +import io.swagger.parser.SwaggerParser; + +import io.swagger.generator.exception.*; +import io.swagger.codegen.*; +import io.swagger.models.Swagger; +import io.swagger.generator.model.*; +import io.swagger.util.Json; +import io.swagger.generator.util.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.List; +import java.util.ArrayList; + +public class Generator { + static Logger LOGGER = LoggerFactory.getLogger(Generator.class); + + public static String generateClient(String language, GeneratorInput opts) throws ApiException { + Swagger swagger; + LOGGER.debug("generate client for " + language); + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + JsonNode node = opts.getSpec(); + if(node == null) { + if(opts.getSwaggerUrl() != null) { + swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + } + else + throw new BadRequestException(400, "No swagger specification was supplied"); + } + else { + swagger = new SwaggerParser().read(node); + } + if(swagger == null) { + throw new BadRequestException(400, "The swagger specification supplied was not valid"); + } + + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-client"; + String outputFilename = outputFolder + "-bundle.zip"; + + clientOptInput + .opts(clientOpts) + .swagger(swagger); + + CodegenConfig codegenConfig = Codegen.getConfig(language); + if(codegenConfig == null) { + throw new BadRequestException(400, "Unsupported target " + language + " supplied"); + } + + codegenConfig.setOutputDir(outputFolder); + + Json.prettyPrint(clientOpts); + + clientOptInput.setConfig(codegenConfig); + + try{ + List files = new Codegen().opts(clientOptInput).generate(); + if(files.size() > 0) { + List filesToAdd = new ArrayList(); + System.out.println("adding to " + outputFolder); + filesToAdd.add(new File(outputFolder)); + ZipUtil zip = new ZipUtil(); + zip.compressFiles(filesToAdd, outputFilename); + } + else { + throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); + } + } + catch (Exception e) { + throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); + } + return outputFilename; + } + + public static String generateServer(String language, GeneratorInput opts) throws ApiException { + LOGGER.debug("generate server for " + language); + Swagger swagger; + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + JsonNode node = opts.getSpec(); + if(node == null) { + if(opts.getSwaggerUrl() != null) { + swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + } + else + throw new BadRequestException(400, "No swagger specification was supplied"); + } + else { + swagger = new SwaggerParser().read(node); + } + if(swagger == null) { + throw new BadRequestException(400, "The swagger specification supplied was not valid"); + } + + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-server"; + String outputFilename = outputFolder + "-bundle.zip"; + + clientOptInput + .opts(clientOpts) + .swagger(swagger); + + CodegenConfig codegenConfig = Codegen.getConfig(language); + if(codegenConfig == null) { + throw new BadRequestException(400, "Unsupported target " + language + " supplied"); + } + + codegenConfig.setOutputDir(outputFolder); + + Json.prettyPrint(clientOpts); + + clientOptInput.setConfig(codegenConfig); + + try{ + List files = new Codegen().opts(clientOptInput).generate(); + if(files.size() > 0) { + List filesToAdd = new ArrayList(); + filesToAdd.add(new File(outputFolder)); + ZipUtil zip = new ZipUtil(); + zip.compressFiles(filesToAdd, outputFilename); + } + else { + throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); + } + } + catch (Exception e) { + throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); + } + return outputFilename; + } + + public static InputOption clientOptions(String language) { + return null; + } + + public static InputOption serverOptions(String language) { + return null; + } + + protected static File getTmpFolder() { + try { + File outputFolder = File.createTempFile("codegen-", "-tmp"); + outputFolder.delete(); + outputFolder.mkdir(); + outputFolder.deleteOnExit(); + return outputFolder; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java new file mode 100644 index 00000000000..2f680a7db07 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/ExceptionWriter.java @@ -0,0 +1,50 @@ +package io.swagger.generator.resource; + +import io.swagger.generator.util.ValidationException; + +import io.swagger.generator.exception.ApiException; +import io.swagger.generator.exception.BadRequestException; +import io.swagger.generator.exception.NotFoundException; +import io.swagger.generator.model.ApiResponse; + +import javax.ws.rs.ext.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +@Provider +public class ExceptionWriter implements ExceptionMapper { + public Response toResponse(Exception exception) { + if (exception instanceof javax.ws.rs.WebApplicationException) { + javax.ws.rs.WebApplicationException e = (javax.ws.rs.WebApplicationException) exception; + return Response + .status(e.getResponse().getStatus()) + .entity(new ApiResponse(e.getResponse().getStatus(), + exception.getMessage())).build(); + } else if (exception instanceof com.fasterxml.jackson.core.JsonParseException) { + return Response.status(400) + .entity(new ApiResponse(400, "bad input")).build(); + } else if (exception instanceof ValidationException) { + ValidationException e = (ValidationException) exception; + return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); + } else if (exception instanceof NotFoundException) { + return Response + .status(Status.NOT_FOUND) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof BadRequestException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof ApiException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else { + return Response.status(500) + .entity(new ApiResponse(500, "something bad happened")) + .build(); + } + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java new file mode 100644 index 00000000000..e591efb1b37 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -0,0 +1,138 @@ +package io.swagger.generator.resource; + +import io.swagger.codegen.*; +import io.swagger.generator.util.*; +import io.swagger.annotations.*; +import io.swagger.generator.model.*; +import io.swagger.generator.exception.BadRequestException; +import io.swagger.generator.online.Generator; + +import java.io.File; +import java.util.*; + +import javax.ws.rs.*; +import javax.ws.rs.core.*; + +@Path("/gen") +@Api(value = "/gen", description = "Resource for generating swagger components") +public class SwaggerResource { + private static Map fileMap = new HashMap(); + + static List clients = new ArrayList(); + static List servers = new ArrayList(); + static { + List extensions = Codegen.getExtensions(); + for(CodegenConfig config : extensions) { + if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + clients.add(config.getName()); + } + else if(config.getTag().equals(CodegenType.SERVER)) { + servers.add(config.getName()); + } + } + } + + @GET + @Path("/download/{fileId}") + @Produces({MediaType.APPLICATION_OCTET_STREAM}) + @ApiOperation(value = "Downloads a pre-generated file", + response = String.class, + tags = {"clients", "servers"}) + public Response downloadFile(@PathParam("fileId") String fileId) throws Exception { + Generated g = fileMap.get(fileId); + System.out.println("looking for fileId " + fileId); + System.out.println("got filename " + g.getFilename()); + if(g.getFilename() != null) { + byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(new java.io.File(g.getFilename())); + + return Response.ok(bytes, "application/zip") + .header("Content-Disposition","attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") + .header("Accept-Range", "bytes") + .header("Content-Length", bytes.length) + .build(); + } + else { + return Response.status(404).build(); + } + } + + @POST + @Path("/clients/{language}") + @ApiOperation( + value = "Generates a client library based on the config", + response = ResponseCode.class, + tags = "clients") + public Response generateClient( + @ApiParam(value = "The target language for the client library", allowableValues = "android,java,php,objc,docs", required = true) @PathParam("language") String language, + @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { + + String filename = Generator.generateClient(language, opts); + + if(filename != null) { + String code = String.valueOf(System.currentTimeMillis()); + Generated g = new Generated(); + g.setFilename(filename); + g.setFriendlyName(language + "-client"); + fileMap.put(code, g); + System.out.println(code + ", " + filename); + String link = "http://generator.swagger.io/api/gen/download/" + code; + return Response.ok().entity(new ResponseCode(code, link)).build(); + } + else { + return Response.status(500).build(); + } + } + + @GET + @Path("/clients") + @ApiOperation(value = "Gets languages supported by the client generator", + response = String.class, + responseContainer = "List", + tags = "clients") + public Response clientOptions() { + String[] languages = new String[clients.size()]; + languages = clients.toArray(languages); + return Response.ok().entity(languages).build(); + } + + @GET + @Path("/servers") + @ApiOperation(value = "Gets languages supported by the server generator", + response = String.class, + responseContainer = "List", + tags = "servers") + public Response serverOptions() { + String[] languages = new String[servers.size()]; + languages = servers.toArray(languages); + return Response.ok().entity(languages).build(); + } + + @POST + @Path("/servers/{framework}") + @ApiOperation(value = "Generates a server library for the supplied server framework", + response = ResponseCode.class, + tags = "servers") + public Response generateServerForLanguage( + @ApiParam(value = "framework", allowableValues = "jaxrs,nodejs", required = true) @PathParam("framework") String framework, + @ApiParam(value = "parameters", required = true) GeneratorInput opts) + throws Exception { + if(framework == null) + throw new BadRequestException(400, "Framework is required"); + String filename = Generator.generateServer(framework, opts); + System.out.println("generated name: " + filename); + + if(filename != null) { + String code = String.valueOf(System.currentTimeMillis()); + Generated g = new Generated(); + g.setFilename(filename); + g.setFriendlyName(framework + "-server"); + fileMap.put(code, g); + System.out.println(code + ", " + filename); + String link = "http://generator.swagger.io/api/gen/download/" + code; + return Response.ok().entity(new ResponseCode(code, link)).build(); + } + else { + return Response.status(500).build(); + } + } +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java new file mode 100644 index 00000000000..8b59594211d --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -0,0 +1,42 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.util; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java new file mode 100644 index 00000000000..46931e6ff6c --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationException.java @@ -0,0 +1,27 @@ +package io.swagger.generator.util; + +import java.util.List; + +public class ValidationException extends Exception { + private int code; + private String msg; + private List errors; + + public ValidationException(String msg) { + super(msg); + } + + public int getCode() { + return code; + } + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return msg; + } + public void setMessage(String msg) { + this.msg = msg; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java new file mode 100644 index 00000000000..b4a71d77ef4 --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ValidationMessage.java @@ -0,0 +1,26 @@ +package io.swagger.generator.util; + +public class ValidationMessage { + private String path, message, severity; + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + public String getSeverity() { + return severity; + } + public void setSeverity(String severity) { + this.severity = severity; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java new file mode 100644 index 00000000000..54f0291195b --- /dev/null +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -0,0 +1,124 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 + * + * 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. + */ + +package io.swagger.generator.util; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** +* This utility compresses a list of files to standard ZIP format file. +* It is able to compresses all sub files and sub directories, recursively. +* @author Ha Minh Nam +* +*/ +public class ZipUtil { + /** + * A constants for buffer size used to read/write data + */ + private static final int BUFFER_SIZE = 4096; + + /** + * Compresses a collection of files to a destination zip file + * @param listFiles A collection of files and directories + * @param destZipFile The path of the destination zip file + * @throws FileNotFoundException + * @throws IOException + */ + public void compressFiles(List listFiles, String destZipFile) throws FileNotFoundException, IOException { + + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); + + for (File file : listFiles) { + if (file.isDirectory()) { + addFolderToZip(file, file.getName(), zos); + } else { + addFileToZip(file, zos); + } + } + + zos.flush(); + zos.close(); + } + + /** + * Adds a directory to the current zip output stream + * @param folder the directory to be added + * @param parentFolder the path of parent directory + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private void addFolderToZip(File folder, String parentFolder, + ZipOutputStream zos) throws FileNotFoundException, IOException { + for (File file : folder.listFiles()) { + if (file.isDirectory()) { + addFolderToZip(file, parentFolder + "/" + file.getName(), zos); + continue; + } + + zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); + + BufferedInputStream bis = new BufferedInputStream( + new FileInputStream(file)); + + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + + zos.closeEntry(); + + } + } + + /** + * Adds a file to the current zip output stream + * @param file the file to be added + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private void addFileToZip(File file, ZipOutputStream zos) + throws FileNotFoundException, IOException { + zos.putNextEntry(new ZipEntry(file.getName())); + + BufferedInputStream bis = new BufferedInputStream(new FileInputStream( + file)); + + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + + zos.closeEntry(); + } +} \ No newline at end of file From 8c340d52a4dad542dd0aa7aedcd9395400cf9873 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 6 Jun 2015 23:58:36 -0700 Subject: [PATCH 05/22] updated packages --- .../src/main/resources/Java/pom.mustache | 4 +- .../src/main/resources/JavaJaxRS/pom.mustache | 4 +- .../main/resources/JavaSpringMVC/pom.mustache | 2 +- .../main/resources/akka-scala/pom.mustache | 2 +- .../resources/android-java/build.mustache | 4 +- .../main/resources/android-java/pom.mustache | 4 +- .../src/main/resources/retrofit/pom.mustache | 4 +- .../src/main/resources/scala/pom.mustache | 4 +- .../client/petstore/android-java/build.gradle | 4 +- samples/client/petstore/android-java/pom.xml | 4 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- samples/client/petstore/java/pom.xml | 4 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- samples/client/petstore/objc/pom.xml | 2 +- samples/client/petstore/retrofit/pom.xml | 4 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- samples/client/petstore/scala/pom.xml | 4 +- samples/html/index.html | 8 +-- samples/server/petstore/jaxrs/pom.xml | 4 +- .../src/gen/java/io/swagger/api/PetApi.java | 64 +++++++++---------- .../src/gen/java/io/swagger/api/StoreApi.java | 36 +++++------ .../src/gen/java/io/swagger/api/UserApi.java | 62 +++++++++--------- .../gen/java/io/swagger/model/Category.java | 2 +- .../src/gen/java/io/swagger/model/Order.java | 2 +- .../src/gen/java/io/swagger/model/Pet.java | 2 +- .../src/gen/java/io/swagger/model/Tag.java | 2 +- .../src/gen/java/io/swagger/model/User.java | 2 +- .../jaxrs/src/main/webapp/WEB-INF/web.xml | 4 +- samples/server/petstore/spring-mvc/pom.xml | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 10 +-- .../main/java/io/swagger/api/StoreApi.java | 10 +-- .../src/main/java/io/swagger/api/UserApi.java | 10 +-- .../main/java/io/swagger/model/Category.java | 2 +- .../src/main/java/io/swagger/model/Order.java | 2 +- .../src/main/java/io/swagger/model/Pet.java | 2 +- .../src/main/java/io/swagger/model/Tag.java | 2 +- .../src/main/java/io/swagger/model/User.java | 2 +- 49 files changed, 155 insertions(+), 155 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 9f4c858a8a0..df01c6ba14d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -157,7 +157,7 @@ - 1.5.3-M1 + 1.5.0 1.18 2.4.2 2.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 64cfdc0af23..708ca6cac4d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -85,7 +85,7 @@ - com.wordnik + io.swagger swagger-jersey-jaxrs ${swagger-core-version} @@ -148,7 +148,7 @@ - 1.5.2-M2 + 1.5.0 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index fc15f492fdf..fc6a7e55738 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -215,7 +215,7 @@ - 1.5.3-M1-SNAPSHOT + 1.5.0 9.2.9.v20150224 2.1.0-M2 1.13 diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index 0d65c135957..f264f38279e 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -217,7 +217,7 @@ 2.3.9 1.2 2.2 - 1.5.0-M1 + 1.5.0 1.0.0 4.8.1 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 66fcef2a371..367890f3298 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -49,14 +49,14 @@ android { ext { - swagger_annotations_version = "1.5.3-M1" + swagger_annotations_version = "1.5.0" gson_version = "2.3.1" httpclient_version = "4.3.3" junit_version = "4.8.1" } dependencies { - compile "com.wordnik:swagger-annotations:$swagger_annotations_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" 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 807df48234d..9dfa63c25c8 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -145,7 +145,7 @@ - 1.5.1-M1 + 1.5.0 2.3.1 4.8.1 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache index fd631871054..bf3a40c3c25 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -134,7 +134,7 @@ - 1.5.3-M1 + 1.5.0 2.3.1 1.9.0 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache index 1163b7d381a..2d8a1257eb4 100644 --- a/modules/swagger-codegen/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -177,7 +177,7 @@ ${scala-version} - com.wordnik + io.swagger swagger-core ${swagger-core-version} @@ -209,7 +209,7 @@ 1.2 2.2 1.7 - 1.5.0-M1 + 1.5.0 1.0.5 1.0.0 2.4.2 diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 16ecd1b4d49..028b56beae6 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -45,14 +45,14 @@ android { ext { - swagger_annotations_version = "1.5.3-M1" + swagger_annotations_version = "1.5.0" gson_version = "2.3.1" httpclient_version = "4.3.3" junit_version = "4.8.1" } dependencies { - compile "com.wordnik:swagger-annotations:$swagger_annotations_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" diff --git a/samples/client/petstore/android-java/pom.xml b/samples/client/petstore/android-java/pom.xml index fd961c04d0a..df929fe5286 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/pom.xml @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -145,7 +145,7 @@ - 1.5.1-M1 + 1.5.0 2.3.1 4.8.1 1.0.0 diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java index 6a001ed16ea..44c71e8a620 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java index 613864b8e32..f3f42db615c 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java @@ -2,7 +2,7 @@ import java.util.Date; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 93ec8bd9a42..90a840e6e42 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -4,7 +4,7 @@ import io.swagger.client.model.Tag; import java.util.*; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java index fb8d9822e96..7c9651b1ba8 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java index 9a46e0a904d..dc022697eb0 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 82e70d8105b..7b134c85222 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/pom.xml @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -157,7 +157,7 @@ - 1.5.3-M1 + 1.5.0 1.18 2.4.2 2.3 diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java index ad67267a2f6..d43f6a9758f 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java index b9f7d1dc897..25864d8c9cc 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java @@ -2,7 +2,7 @@ import java.util.Date; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index d685a8c1cbf..cf7ace02309 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -4,7 +4,7 @@ import io.swagger.client.model.Tag; import java.util.*; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java index b9dddc92f1b..63a2ca3b739 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java index 9811a7741f9..0ace5b7e30a 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/objc/pom.xml b/samples/client/petstore/objc/pom.xml index 42e116ac170..bf209a7db96 100644 --- a/samples/client/petstore/objc/pom.xml +++ b/samples/client/petstore/objc/pom.xml @@ -1,6 +1,6 @@ 4.0.0 - com.wordnik + io.swagger ObjcPetstoreClientTests pom 1.0-SNAPSHOT diff --git a/samples/client/petstore/retrofit/pom.xml b/samples/client/petstore/retrofit/pom.xml index 4a95855cac9..7177c69dcc9 100644 --- a/samples/client/petstore/retrofit/pom.xml +++ b/samples/client/petstore/retrofit/pom.xml @@ -108,7 +108,7 @@ - com.wordnik + io.swagger swagger-annotations ${swagger-annotations-version} @@ -134,7 +134,7 @@ - 1.5.3-M1 + 1.5.0 2.3.1 1.9.0 1.0.0 diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java index 8ba10d629dc..7f89bcf57a0 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java index d7d0b2d9282..6be69df18c9 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -2,7 +2,7 @@ import java.util.Date; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java index 3ae04239744..b6935a7c1e3 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -4,7 +4,7 @@ import io.swagger.client.model.Tag; import java.util.*; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java index e6ddd4c92cd..c1a317bc45c 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java index f42f77b9773..3beca5c5e86 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java @@ -1,7 +1,7 @@ package io.swagger.client.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index 74bb2feed86..7e56a41c890 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -177,7 +177,7 @@ ${scala-version} - com.wordnik + io.swagger swagger-core ${swagger-core-version} @@ -209,7 +209,7 @@ 1.2 2.2 1.7 - 1.5.0-M1 + 1.5.0 1.0.5 1.0.0 2.4.2 diff --git a/samples/html/index.html b/samples/html/index.html index e595d3ea40d..caaa4152984 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -332,7 +332,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-07T06:42:05.171+0000" + "shipDate" : "2015-06-07T06:51:26.728+0000" }

Example data

@@ -341,7 +341,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-06-06T23:42:05.174Z</shipDate> + <shipDate>2015-06-06T23:51:26.731Z</shipDate> <status>string</status> <complete>true</complete> </Order> @@ -375,7 +375,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-07T06:42:05.175+0000" + "shipDate" : "2015-06-07T06:51:26.732+0000" }

Example data

@@ -384,7 +384,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-06-06T23:42:05.176Z</shipDate> + <shipDate>2015-06-06T23:51:26.732Z</shipDate> <status>string</status> <complete>true</complete> </Order> diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index 825dec0f766..cac2f6daf79 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -85,7 +85,7 @@ - com.wordnik + io.swagger swagger-jersey-jaxrs ${swagger-core-version} @@ -148,7 +148,7 @@ - 1.5.2-M2 + 1.5.0 9.2.9.v20150224 1.13 1.6.3 diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index e67773ed634..055fa75c80b 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -4,7 +4,7 @@ import io.swagger.api.PetApiService; import io.swagger.api.factories.PetApiServiceFactory; -import com.wordnik.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; @@ -25,7 +25,7 @@ @Path("/pet") -@com.wordnik.swagger.annotations.Api(value = "/pet", description = "the pet API") +@io.swagger.annotations.Api(value = "/pet", description = "the pet API") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @@ -34,13 +34,13 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Validation exception"), + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception"), - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { @@ -50,9 +50,9 @@ public Response updatePet(@ApiParam(value = "Pet object that needs to be added t @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { @@ -62,11 +62,11 @@ public Response addPet(@ApiParam(value = "Pet object that needs to be added to t @Path("/findByStatus") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { @@ -76,11 +76,11 @@ public Response findPetsByStatus(@ApiParam(value = "Status values that need to b @Path("/findByTags") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) throws NotFoundException { @@ -90,13 +90,13 @@ public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryPara @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) throws NotFoundException { @@ -106,9 +106,9 @@ public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input") }) public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, @@ -120,9 +120,9 @@ public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value") }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value") }) public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String apiKey, @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) @@ -133,9 +133,9 @@ public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index 790d4c4c3f6..f5215862ba7 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -4,7 +4,7 @@ import io.swagger.api.StoreApiService; import io.swagger.api.factories.StoreApiServiceFactory; -import com.wordnik.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; @@ -25,7 +25,7 @@ @Path("/store") -@com.wordnik.swagger.annotations.Api(value = "/store", description = "the store API") +@io.swagger.annotations.Api(value = "/store", description = "the store API") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @@ -34,9 +34,9 @@ public class StoreApi { @Path("/inventory") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) public Response getInventory() throws NotFoundException { @@ -46,11 +46,11 @@ public Response getInventory() @Path("/order") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { @@ -60,13 +60,13 @@ public Response placeOrder(@ApiParam(value = "order placed for purchasing the pe @Path("/order/{orderId}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { @@ -76,11 +76,11 @@ public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetch @Path("/order/{orderId}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index 979476c41c6..f904b77746b 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -4,7 +4,7 @@ import io.swagger.api.UserApiService; import io.swagger.api.factories.UserApiServiceFactory; -import com.wordnik.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiParam; import com.sun.jersey.multipart.FormDataParam; @@ -25,7 +25,7 @@ @Path("/user") -@com.wordnik.swagger.annotations.Api(value = "/user", description = "the user API") +@io.swagger.annotations.Api(value = "/user", description = "the user API") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @@ -34,9 +34,9 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { @@ -46,9 +46,9 @@ public Response createUser(@ApiParam(value = "Created user object" ) User body) @Path("/createWithArray") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -58,9 +58,9 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @Path("/createWithList") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -70,11 +70,11 @@ public Response createUsersWithListInput(@ApiParam(value = "List of user object" @Path("/login") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) @@ -85,9 +85,9 @@ public Response loginUser(@ApiParam(value = "The user name for login") @QueryPar @Path("/logout") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response logoutUser() throws NotFoundException { @@ -97,13 +97,13 @@ public Response logoutUser() @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) throws NotFoundException { @@ -113,11 +113,11 @@ public Response getUserByName(@ApiParam(value = "The name that needs to be fetch @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied") }) public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, @ApiParam(value = "Updated user object" ) User body) @@ -128,11 +128,11 @@ public Response updateUser(@ApiParam(value = "name that need to be deleted",requ @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @com.wordnik.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { - @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found"), - @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index 98cc0b4d273..56f86f70737 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index cff15e3bd2a..4d0c133e936 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -2,7 +2,7 @@ import java.util.Date; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index e8503c6bd31..3b89931c47b 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -4,7 +4,7 @@ import io.swagger.model.Tag; import java.util.*; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index d99a24f8cc1..99dd07c00f7 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index 24d707e921f..d5f43a4c25e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml index 0dde6168d62..80df1cd180d 100644 --- a/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml +++ b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml @@ -8,7 +8,7 @@ com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages - com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;io.swagger.api + io.swagger.jaxrs.json;io.swagger.jaxrs.listing;io.swagger.api com.sun.jersey.spi.container.ContainerRequestFilters @@ -23,7 +23,7 @@ DefaultJaxrsConfig - com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig + io.swagger.jaxrs.config.DefaultJaxrsConfig api.version 1.0.0 diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 5f6ab531f10..71cdd259658 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -215,7 +215,7 @@ - 1.5.3-M1-SNAPSHOT + 1.5.0 9.2.9.v20150224 2.1.0-M2 1.13 diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index a39a8e70970..6264ec78567 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -5,11 +5,11 @@ import io.swagger.model.Pet; import java.io.File; -import com.wordnik.swagger.annotations.Api; -import com.wordnik.swagger.annotations.ApiOperation; -import com.wordnik.swagger.annotations.ApiParam; -import com.wordnik.swagger.annotations.ApiResponse; -import com.wordnik.swagger.annotations.ApiResponses; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index ba6e233ce9c..c81693887db 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -5,11 +5,11 @@ import java.util.Map; import io.swagger.model.Order; -import com.wordnik.swagger.annotations.Api; -import com.wordnik.swagger.annotations.ApiOperation; -import com.wordnik.swagger.annotations.ApiParam; -import com.wordnik.swagger.annotations.ApiResponse; -import com.wordnik.swagger.annotations.ApiResponses; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 15b170e90a7..35227db7c67 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -5,11 +5,11 @@ import io.swagger.model.User; import java.util.*; -import com.wordnik.swagger.annotations.Api; -import com.wordnik.swagger.annotations.ApiOperation; -import com.wordnik.swagger.annotations.ApiParam; -import com.wordnik.swagger.annotations.ApiResponse; -import com.wordnik.swagger.annotations.ApiResponses; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index 98cc0b4d273..56f86f70737 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index cff15e3bd2a..4d0c133e936 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -2,7 +2,7 @@ import java.util.Date; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index e8503c6bd31..3b89931c47b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -4,7 +4,7 @@ import io.swagger.model.Tag; import java.util.*; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index d99a24f8cc1..99dd07c00f7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 24d707e921f..d5f43a4c25e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -1,7 +1,7 @@ package io.swagger.model; -import com.wordnik.swagger.annotations.*; +import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; From 6c5781012888c476a8910fa73394bc2888af9441 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 7 Jun 2015 00:08:01 -0700 Subject: [PATCH 06/22] rebuilt --- .../java/io/swagger/codegen/ClientOptInput.java | 16 ---------------- .../codegen/languages/PhpClientCodegen.java | 2 +- .../codegen/languages/ScalatraServerCodegen.java | 2 +- .../codegen/languages/StaticDocCodegen.java | 2 +- .../codegen/languages/StaticHtmlGenerator.java | 2 +- .../src/main/resources/Java/pom.mustache | 6 +++--- .../src/main/resources/JavaJaxRS/README.mustache | 6 +++--- .../main/resources/JavaSpringMVC/pom.mustache | 2 +- .../src/main/resources/akka-scala/pom.mustache | 2 +- .../src/main/resources/android-java/pom.mustache | 6 +++--- .../src/main/resources/codegen/pom.mustache | 2 +- .../src/main/resources/nodejs/README.mustache | 2 +- .../src/main/resources/retrofit/pom.mustache | 6 +++--- .../ruby/swagger_client.gemspec.mustache | 4 ++-- .../src/main/resources/scalatra/README.mustache | 6 +++--- .../src/main/resources/scalatra/build.sbt | 2 +- .../src/main/resources/swagger-static/pom.xml | 6 +++--- .../src/main/resources/validator/index.mustache | 12 ++++++------ samples/client/petstore/android-java/pom.xml | 6 +++--- .../petstore/flash/FlashPetstoreCodegen.scala | 2 +- samples/client/petstore/java/pom.xml | 6 +++--- samples/client/petstore/retrofit/pom.xml | 6 +++--- .../client/petstore/ruby/swagger_client.gemspec | 4 ++-- samples/html/index.html | 8 ++++---- samples/server/petstore/jaxrs/README.md | 6 +++--- samples/server/petstore/spring-mvc/pom.xml | 2 +- 26 files changed, 55 insertions(+), 71 deletions(-) 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 54056583463..c1d21f48035 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,19 +1,3 @@ -/** - * Copyright 2015 Reverb, Inc. - * - * 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 - * - * 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. - */ - package io.swagger.codegen; import io.swagger.codegen.ClientOpts; 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 b82419c450f..340e58ab106 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 @@ -8,7 +8,7 @@ import java.io.File; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; + protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; 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 aadbf9a7231..7758d9a19e8 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 @@ -8,7 +8,7 @@ import java.io.File; public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; + protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; 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 b751b62147f..3d1a8f6b62c 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 @@ -7,7 +7,7 @@ import java.io.File; public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; + protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; 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 96d004fe5e1..6a1c530b837 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 @@ -10,7 +10,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { private static final String ALL_OPERATIONS = ""; - protected String invokerPackage = "com.wordnik.client"; + protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index df01c6ba14d..592edeec051 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -7,9 +7,9 @@ {{artifactId}} {{artifactVersion}} - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache index f8a560b776f..3ffa01fb257 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache @@ -1,10 +1,10 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +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. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index fc6a7e55738..3b068adffdf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -110,7 +110,7 @@ - com.wordnik + io.swagger swagger-jersey-jaxrs ${swagger-core-version} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache index f264f38279e..eb24f77c072 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -162,7 +162,7 @@ ${scala-version} - com.wordnik + io.swagger swagger-core ${swagger-core-version} 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 9dfa63c25c8..05388db4e11 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache @@ -7,9 +7,9 @@ {{artifactId}} {{artifactVersion}} - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 diff --git a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache index f827a2f56b6..ad480b9b331 100644 --- a/modules/swagger-codegen/src/main/resources/codegen/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/codegen/pom.mustache @@ -88,7 +88,7 @@ - com.wordnik + io.swagger swagger-codegen ${swagger-codegen-version} provided diff --git a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache index a8da1d0a9ea..edeea0005c0 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache @@ -5,7 +5,7 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/README.md) +[README](https://github.com/swagger-api/swagger-codegen/README.md) ### Running the server To run the server, follow these simple steps: diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache index bf3a40c3c25..7d999db86ca 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache @@ -7,9 +7,9 @@ {{artifactId}} {{artifactVersion}} - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 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 9f84d88d4e1..8ae4bfa1a49 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 @@ -7,8 +7,8 @@ Gem::Specification.new do |s| s.version = {{moduleName}}::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" + 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" diff --git a/modules/swagger-codegen/src/main/resources/scalatra/README.mustache b/modules/swagger-codegen/src/main/resources/scalatra/README.mustache index f8a560b776f..3ffa01fb257 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/README.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/README.mustache @@ -1,10 +1,10 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +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. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ 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 afe84c2c7f0..00575312d85 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt +++ b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt @@ -8,7 +8,7 @@ assemblySettings scalariformSettings -organization := "com.wordnik" +organization := "io.swagger" seq(webSettings :_*) diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/pom.xml b/modules/swagger-codegen/src/main/resources/swagger-static/pom.xml index eb3bed8e7b9..9c882323816 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/pom.xml +++ b/modules/swagger-codegen/src/main/resources/swagger-static/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.wordnik - wordnik-swagger-demo + io.swagger + swagger-demo jar - wordnik-swagger-demo + swagger-demo 1.0.0-SNAPSHOT 2.2.0 diff --git a/modules/swagger-codegen/src/main/resources/validator/index.mustache b/modules/swagger-codegen/src/main/resources/validator/index.mustache index 24ac8de38ef..2f4c45b32dc 100644 --- a/modules/swagger-codegen/src/main/resources/validator/index.mustache +++ b/modules/swagger-codegen/src/main/resources/validator/index.mustache @@ -70,7 +70,7 @@ clear: none; float: left; padding: 20px 0 20px 60px; - background: transparent url('http://swagger.wordnik.com/images/logo.png') no-repeat left center; + background: transparent url('http://swagger.io/images/logo.png') no-repeat left center; color: white; text-decoration: none; } @@ -207,13 +207,13 @@ diff --git a/samples/client/petstore/android-java/pom.xml b/samples/client/petstore/android-java/pom.xml index df929fe5286..639000ecc6d 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/pom.xml @@ -7,9 +7,9 @@ swagger-android-client 1.0.0 - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 diff --git a/samples/client/petstore/flash/FlashPetstoreCodegen.scala b/samples/client/petstore/flash/FlashPetstoreCodegen.scala index 0198674a2eb..e1f996b9487 100644 --- a/samples/client/petstore/flash/FlashPetstoreCodegen.scala +++ b/samples/client/petstore/flash/FlashPetstoreCodegen.scala @@ -19,7 +19,7 @@ import com.wordnik.swagger.codegen.BasicFlashCodegen object FlashPetstoreCodegen extends BasicFlashCodegen { def main(args: Array[String]) = generateClient(args) - override def packageName = "com.wordnik.client" + override def packageName = "io.swagger.client" override def destinationRoot = "samples/client/petstore/flash" diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 7b134c85222..058733e08fc 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/pom.xml @@ -7,9 +7,9 @@ swagger-java-client 1.0.0 - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 diff --git a/samples/client/petstore/retrofit/pom.xml b/samples/client/petstore/retrofit/pom.xml index 7177c69dcc9..45463b449bd 100644 --- a/samples/client/petstore/retrofit/pom.xml +++ b/samples/client/petstore/retrofit/pom.xml @@ -7,9 +7,9 @@ swagger-java-client 1.0.0 - scm:git:git@github.com:wordnik/swagger-mustache.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen + 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 diff --git a/samples/client/petstore/ruby/swagger_client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec index 6ec2484e05c..c0d507b3c5b 100644 --- a/samples/client/petstore/ruby/swagger_client.gemspec +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -7,8 +7,8 @@ Gem::Specification.new do |s| s.version = SwaggerClient::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" + 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" diff --git a/samples/html/index.html b/samples/html/index.html index caaa4152984..6dd837bc3ee 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -332,7 +332,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-07T06:51:26.728+0000" + "shipDate" : "2015-06-07T07:07:24.098+0000" }

Example data

@@ -341,7 +341,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-06-06T23:51:26.731Z</shipDate> + <shipDate>2015-06-07T00:07:24.100Z</shipDate> <status>string</status> <complete>true</complete> </Order> @@ -375,7 +375,7 @@

Example data

"complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-06-07T06:51:26.732+0000" + "shipDate" : "2015-06-07T07:07:24.102+0000" }

Example data

@@ -384,7 +384,7 @@

Example data

<id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-06-06T23:51:26.732Z</shipDate> + <shipDate>2015-06-07T00:07:24.102Z</shipDate> <status>string</status> <complete>true</complete> </Order> diff --git a/samples/server/petstore/jaxrs/README.md b/samples/server/petstore/jaxrs/README.md index f8a560b776f..3ffa01fb257 100644 --- a/samples/server/petstore/jaxrs/README.md +++ b/samples/server/petstore/jaxrs/README.md @@ -1,10 +1,10 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +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. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 71cdd259658..30cd3a41484 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -110,7 +110,7 @@ - com.wordnik + io.swagger swagger-jersey-jaxrs ${swagger-core-version} From 1a3967820672d70a23860e205972b173e7d399df Mon Sep 17 00:00:00 2001 From: Ron Date: Sun, 7 Jun 2015 11:05:00 -0400 Subject: [PATCH 07/22] Refactoring --- pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 610f6baa2e1..55342b2db26 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 5 4.0.0 - com.wordnik + io.swagger swagger-codegen-project pom swagger-codegen-project @@ -137,7 +137,7 @@ development ${project.url} ${project.version} - com.wordnik + io.swagger @@ -462,10 +462,10 @@ - 1.0.7 + 1.0.8-SNAPSHOT 2.11.1 2.3.4 - 1.5.2-M2 + 1.5.0 2.1.4 2.3 1.2 From 96107193e9a575d3818198f989b07778c60808de Mon Sep 17 00:00:00 2001 From: Ron Date: Sun, 7 Jun 2015 11:18:49 -0400 Subject: [PATCH 08/22] updated reverb references --- .../io/swagger/codegen/languages/ScalatraServerCodegen.java | 4 ++-- .../swagger-codegen/src/main/resources/perl/api.mustache | 2 +- .../src/main/resources/php/APIClient.mustache | 2 +- .../src/main/resources/php/ApiException.mustache | 2 +- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- .../src/main/resources/php/configuration.mustache | 2 +- .../swagger-codegen/src/main/resources/php/model.mustache | 2 +- .../swagger-codegen/src/main/resources/python/api.mustache | 2 +- .../src/main/resources/python/model.mustache | 2 +- .../swagger-codegen/src/main/resources/python3/api.mustache | 2 +- .../src/main/resources/python3/model.mustache | 2 +- .../src/test/resources/1_2/petstore-1.2/api-docs | 2 +- .../swagger-codegen/src/test/resources/2_0/petstore.json | 2 +- .../src/test/resources/2_0/petstore.json.orig | 2 +- .../src/test/resources/2_0/postBodyTest.json | 2 +- .../src/test/resources/2_0/requiredTest.json | 2 +- .../src/test/resources/2_0/responseSelectionTest.json | 2 +- .../src/main/java/io/swagger/generator/Bootstrap.java | 6 +++--- .../java/io/swagger/generator/exception/ApiException.java | 2 +- .../io/swagger/generator/exception/BadRequestException.java | 2 +- .../io/swagger/generator/exception/NotFoundException.java | 2 +- .../main/java/io/swagger/generator/model/ApiResponse.java | 2 +- .../src/main/java/io/swagger/generator/model/Generated.java | 2 +- .../main/java/io/swagger/generator/model/InputOption.java | 2 +- .../java/io/swagger/generator/util/ApiOriginFilter.java | 2 +- .../src/main/java/io/swagger/generator/util/ZipUtil.java | 2 +- .../objc/PetstoreClient/PetstoreClient/AppDelegate.h | 2 +- .../objc/PetstoreClient/PetstoreClient/AppDelegate.m | 2 +- .../objc/PetstoreClient/PetstoreClient/ViewController.h | 2 +- .../objc/PetstoreClient/PetstoreClient/ViewController.m | 2 +- .../petstore/objc/PetstoreClient/PetstoreClient/main.m | 2 +- .../client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm | 2 +- .../client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm | 2 +- .../client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm | 2 +- .../client/petstore/php/SwaggerClient-php/lib/APIClient.php | 2 +- .../petstore/php/SwaggerClient-php/lib/ApiException.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Configuration.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/PetApi.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/StoreApi.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/UserApi.php | 2 +- .../petstore/php/SwaggerClient-php/lib/models/Category.php | 2 +- .../petstore/php/SwaggerClient-php/lib/models/Order.php | 2 +- .../petstore/php/SwaggerClient-php/lib/models/Pet.php | 2 +- .../petstore/php/SwaggerClient-php/lib/models/Tag.php | 2 +- .../petstore/php/SwaggerClient-php/lib/models/User.php | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py | 2 +- .../SwaggerPetstore/apis/store_api.py | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py | 2 +- .../SwaggerPetstore/models/category.py | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/models/order.py | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/models/pet.py | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/models/tag.py | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/models/user.py | 2 +- samples/client/petstore/python3/client/models/category.py | 2 +- samples/client/petstore/python3/client/models/order.py | 2 +- samples/client/petstore/python3/client/models/pet.py | 2 +- samples/client/petstore/python3/client/models/tag.py | 2 +- samples/client/petstore/python3/client/models/user.py | 2 +- samples/client/petstore/python3/client/pet_api.py | 2 +- samples/client/petstore/python3/client/store_api.py | 2 +- samples/client/petstore/python3/client/user_api.py | 2 +- samples/client/wordnik-api-php/wordnik/AccountApi.php | 2 +- .../petstore/scalatra/src/main/scala/ServletApp.scala | 4 ++-- samples/yaml/api-docs.yml | 2 +- 64 files changed, 68 insertions(+), 68 deletions(-) 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 7758d9a19e8..30b96ca5aa7 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 @@ -72,8 +72,8 @@ public ScalatraServerCodegen() { additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); - additionalProperties.put("infoUrl", "http://developers.helloreverb.com"); - additionalProperties.put("infoEmail", "hello@helloreverb.com"); + 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); diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 5adb50344de..c67139ee33d 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -1,5 +1,5 @@ # -# Copyright 2015 Reverb Technologies, Inc. +# 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. diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 476d3b625c2..6356143f914 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -1,6 +1,6 @@ http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample,\n you can use the api key \"special-key\" to test the authorization filters", - "termsOfServiceUrl": "http://helloreverb.com/terms/", + "termsOfServiceUrl": "http://swagger.io/terms/", "contact": "apiteam@wordnik.com", "license": "Apache 2.0", "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html" diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 30c53134633..0dce7023772 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -4,7 +4,7 @@ "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0", "title": "Swagger Petstore", - "termsOfService": "http://helloreverb.com/terms/", + "termsOfService": "http://swagger.io/terms/", "contact": { "email": "apiteam@wordnik.com" }, diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig b/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig index b4678fc3ab9..c03d1860d24 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig @@ -4,7 +4,7 @@ "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0", "title": "Swagger Petstore", - "termsOfService": "http://helloreverb.com/terms/", + "termsOfService": "http://swagger.io/terms/", "contact": { "email": "apiteam@wordnik.com" }, diff --git a/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json index e2a917c6744..6f52139e9a4 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json @@ -4,7 +4,7 @@ "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0", "title": "Swagger Petstore", - "termsOfService": "http://helloreverb.com/terms/", + "termsOfService": "http://swagger.io/terms/", "contact": { "name": "apiteam@wordnik.com" }, diff --git a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json index 88106746d29..fb48df82bfc 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json @@ -4,7 +4,7 @@ "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0", "title": "Swagger Petstore", - "termsOfService": "http://helloreverb.com/terms/", + "termsOfService": "http://swagger.io/terms/", "contact": { "email": "apiteam@wordnik.com" }, diff --git a/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json b/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json index f698c96425a..42aa615c344 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json @@ -4,7 +4,7 @@ "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0", "title": "Swagger Petstore", - "termsOfService": "http://helloreverb.com/terms/", + "termsOfService": "http://swagger.io/terms/", "contact": { "email": "apiteam@wordnik.com" }, diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index 8a5d0bcb324..d98c1783b4b 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. @@ -32,8 +32,8 @@ public void init(ServletConfig config) throws ServletException { bc.setTitle("Swagger Generator"); bc.setDescription("This is an online swagger codegen server. You can find out more " + "at https://github.com/swagger-api/swagger-codegen or on irc.freenode.net, #swagger." + - "http://helloreverb.com/terms/"); - bc.setTermsOfServiceUrl("http://helloreverb.com/terms/"); + "http://swagger.io/terms/"); + bc.setTermsOfServiceUrl("http://swagger.io/terms/"); bc.setContact("apiteam@swagger.io"); bc.setLicense("Apache 2.0"); bc.setVersion("1.0.0"); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java index 1ed3e84af41..1160c9a36c1 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 70db17379e6..7a0409cc8b7 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java index 119a7307437..dede63787b2 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java index 88661f45bf5..48235abe878 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java index 95786cf8b76..9a02438afeb 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java index 6ed89a654e6..d67a2d38f03 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java index 8b59594211d..e4720cd4e7f 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java index 54f0291195b..11acf6b0ed2 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 Reverb, Inc. + * 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. diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h index c6172fd5fcc..622ab1d3916 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h @@ -3,7 +3,7 @@ // PetstoreClient // // Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. +// Copyright (c) 2015 SmartBear Software. All rights reserved. // #import diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m index c0013e2cbed..a63c7d1ad89 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m @@ -3,7 +3,7 @@ // PetstoreClient // // Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. +// Copyright (c) 2015 SmartBear Software. All rights reserved. // #import "AppDelegate.h" diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h index 4df89c445de..f6e0cde9cd6 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h @@ -3,7 +3,7 @@ // PetstoreClient // // Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. +// Copyright (c) 2015 SmartBear Software. All rights reserved. // #import diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m index d56bc037206..fd15f391f49 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m @@ -3,7 +3,7 @@ // PetstoreClient // // Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. +// Copyright (c) 2015 SmartBear Software. All rights reserved. // #import "ViewController.h" diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m index 644c21bf165..d351099cbe1 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m @@ -3,7 +3,7 @@ // PetstoreClient // // Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. +// Copyright (c) 2015 SmartBear Software. All rights reserved. // #import diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 44bc1567a3d..0a926625b74 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 Reverb Technologies, Inc. +# 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. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 6e22d4dbcc0..c27d241cb76 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 Reverb Technologies, Inc. +# 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. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 5b2fc0a0000..ffb9d4b732b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 Reverb Technologies, Inc. +# 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. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 229709562ef..b8357f9b479 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -1,6 +1,6 @@ http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters""", + """This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://webchat.freenode.net/?channels=swagger). For this sample, you can use the api key `special-key` to test the authorization filters""", """""", - """hello@helloreverb.com""", + """apiteam@swagger.io""", """Apache 2.0""", """http://www.apache.org/licenses/LICENSE-2.0.html""") } \ No newline at end of file diff --git a/samples/yaml/api-docs.yml b/samples/yaml/api-docs.yml index 8ce50cd44b8..68c159a35d6 100644 --- a/samples/yaml/api-docs.yml +++ b/samples/yaml/api-docs.yml @@ -31,7 +31,7 @@ authorizations: info: title: Swagger Sample App description: "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.wordnik.com or on irc.freenode.net, #swagger." - termsOfServiceUrl: "http://helloreverb.com/terms/" + termsOfServiceUrl: "http://swagger.io/terms/" contact: "apiteam@wordnik.com" license: Apache 2.0 licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.html" \ No newline at end of file From 22d7db2cb4579e40eabe73f9f9482fe4bd4fa264 Mon Sep 17 00:00:00 2001 From: Ron Date: Sun, 7 Jun 2015 11:46:11 -0400 Subject: [PATCH 09/22] url changes --- .../src/test/resources/1_2/petstore-1.2/api-docs | 8 ++++---- .../swagger-codegen/src/test/resources/2_0/petstore.json | 2 +- .../src/test/resources/2_0/petstore.json.orig | 2 +- .../src/test/resources/2_0/postBodyTest.json | 2 +- .../src/test/resources/2_0/requiredTest.json | 2 +- .../src/test/resources/2_0/responseSelectionTest.json | 2 +- .../petstore/python/SwaggerPetstore-python/setup.py | 2 +- samples/html/index.html | 2 +- .../main/java/io/swagger/configuration/SwaggerConfig.java | 2 +- samples/yaml/api-docs.yml | 2 +- 10 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs index 753cec8bfa5..7207d603310 100644 --- a/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs +++ b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs @@ -31,18 +31,18 @@ "grantTypes": { "implicit": { "loginEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/dialog" + "url": "http://petstore.swagger.io/api/oauth/dialog" }, "tokenName": "access_token" }, "authorization_code": { "tokenRequestEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/requestToken", + "url": "http://petstore.swagger.io/api/oauth/requestToken", "clientIdName": "client_id", "clientSecretName": "client_secret" }, "tokenEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/token", + "url": "http://petstore.swagger.io/api/oauth/token", "tokenName": "access_code" } } @@ -53,7 +53,7 @@ "title": "Swagger Sample App", "description": "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample,\n you can use the api key \"special-key\" to test the authorization filters", "termsOfServiceUrl": "http://swagger.io/terms/", - "contact": "apiteam@wordnik.com", + "contact": "apiteam@swagger.io", "license": "Apache 2.0", "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html" } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 0dce7023772..66762d74b2b 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -6,7 +6,7 @@ "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { - "email": "apiteam@wordnik.com" + "email": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig b/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig index c03d1860d24..7422817fea7 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json.orig @@ -6,7 +6,7 @@ "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { - "email": "apiteam@wordnik.com" + "email": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", diff --git a/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json index 6f52139e9a4..89f1bf4f81c 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json @@ -6,7 +6,7 @@ "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { - "name": "apiteam@wordnik.com" + "name": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", diff --git a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json index fb48df82bfc..2939a50535a 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json @@ -6,7 +6,7 @@ "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { - "email": "apiteam@wordnik.com" + "email": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", diff --git a/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json b/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json index 42aa615c344..29d5b75d3d9 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json +++ b/modules/swagger-codegen/src/test/resources/2_0/responseSelectionTest.json @@ -6,7 +6,7 @@ "title": "Swagger Petstore", "termsOfService": "http://swagger.io/terms/", "contact": { - "email": "apiteam@wordnik.com" + "email": "apiteam@swagger.io" }, "license": { "name": "Apache 2.0", diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.py b/samples/client/petstore/python/SwaggerPetstore-python/setup.py index 50a6ffeb00c..fbd738be680 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.py @@ -18,7 +18,7 @@ name="SwaggerPetstore", version="1.0.0", description="Swagger Petstore", - author_email="apiteam@wordnik.com", + author_email="apiteam@swagger.io", url="", keywords=["Swagger", "Swagger Petstore"], install_requires=REQUIRES, diff --git a/samples/html/index.html b/samples/html/index.html index 6dd837bc3ee..068b0523f4e 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -7,7 +7,7 @@

Swagger Petstore

This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters for
-
Contact Info: apiteam@wordnik.com
+
Contact Info: apiteam@swagger.io
Version: 1.0.0
Apache 2.0
http://www.apache.org/licenses/LICENSE-2.0.html
diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index fb7361aa3f0..7b2de09cdd6 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -26,7 +26,7 @@ ApiInfo apiInfo() { "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "1.0.0", "", - "apiteam@wordnik.com", + "apiteam@swagger.io", "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0.html" ); return apiInfo; diff --git a/samples/yaml/api-docs.yml b/samples/yaml/api-docs.yml index 68c159a35d6..d381f272532 100644 --- a/samples/yaml/api-docs.yml +++ b/samples/yaml/api-docs.yml @@ -32,6 +32,6 @@ info: title: Swagger Sample App description: "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.wordnik.com or on irc.freenode.net, #swagger." termsOfServiceUrl: "http://swagger.io/terms/" - contact: "apiteam@wordnik.com" + contact: "apiteam@swagger.io" license: Apache 2.0 licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.html" \ No newline at end of file From 1c2d0656b07829ad6786df40851262fc4c1c429e Mon Sep 17 00:00:00 2001 From: Ron Date: Sun, 7 Jun 2015 11:56:08 -0400 Subject: [PATCH 10/22] Code reformatting --- modules/swagger-codegen-cli/pom.xml | 17 +- .../io/swagger/codegen/SwaggerCodegen.java | 6 +- .../io/swagger/codegen/cmd/ConfigHelp.java | 33 +- .../java/io/swagger/codegen/cmd/Generate.java | 72 +- .../java/io/swagger/codegen/cmd/Langs.java | 2 +- .../java/io/swagger/codegen/cmd/Meta.java | 9 +- .../src/main/resources/logback.xml | 20 +- modules/swagger-codegen/pom.xml | 699 +-- .../src/main/java/config/Config.java | 51 +- .../src/main/java/config/ConfigParser.java | 55 +- .../io/swagger/codegen/AbstractGenerator.java | 105 +- .../java/io/swagger/codegen/CliOption.java | 30 +- .../io/swagger/codegen/ClientOptInput.java | 140 +- .../java/io/swagger/codegen/ClientOpts.java | 97 +- .../main/java/io/swagger/codegen/Codegen.java | 231 +- .../io/swagger/codegen/CodegenConfig.java | 155 +- .../java/io/swagger/codegen/CodegenModel.java | 22 +- .../swagger/codegen/CodegenModelFactory.java | 53 +- .../io/swagger/codegen/CodegenModelType.java | 26 +- .../io/swagger/codegen/CodegenOperation.java | 53 +- .../io/swagger/codegen/CodegenParameter.java | 68 +- .../io/swagger/codegen/CodegenProperty.java | 51 +- .../io/swagger/codegen/CodegenResponse.java | 29 +- .../io/swagger/codegen/CodegenSecurity.java | 12 +- .../java/io/swagger/codegen/CodegenType.java | 52 +- .../io/swagger/codegen/DefaultCodegen.java | 2667 +++++---- .../io/swagger/codegen/DefaultGenerator.java | 847 ++- .../java/io/swagger/codegen/Generator.java | 7 +- .../io/swagger/codegen/MetaGenerator.java | 337 +- .../io/swagger/codegen/SupportingFile.java | 16 +- .../io/swagger/codegen/auth/AuthMethod.java | 5 +- .../codegen/examples/ExampleGenerator.java | 255 +- .../codegen/examples/XmlExampleGenerator.java | 384 +- .../languages/AkkaScalaClientCodegen.java | 678 ++- .../languages/AndroidClientCodegen.java | 474 +- .../languages/AsyncScalaClientCodegen.java | 371 +- .../languages/CSharpClientCodegen.java | 371 +- .../codegen/languages/JavaClientCodegen.java | 442 +- .../codegen/languages/JaxRSServerCodegen.java | 358 +- .../languages/NodeJSServerCodegen.java | 334 +- .../codegen/languages/ObjcClientCodegen.java | 652 ++- .../codegen/languages/PerlClientCodegen.java | 388 +- .../codegen/languages/PhpClientCodegen.java | 350 +- .../languages/Python3ClientCodegen.java | 390 +- .../languages/PythonClientCodegen.java | 424 +- .../codegen/languages/Qt5CPPGenerator.java | 564 +- .../languages/RetrofitClientCodegen.java | 362 +- .../codegen/languages/RubyClientCodegen.java | 433 +- .../codegen/languages/ScalaClientCodegen.java | 382 +- .../languages/ScalatraServerCodegen.java | 335 +- .../languages/SpringMVCServerCodegen.java | 99 +- .../codegen/languages/StaticDocCodegen.java | 119 +- .../languages/StaticHtmlGenerator.java | 157 +- .../codegen/languages/SwaggerGenerator.java | 69 +- .../languages/SwaggerYamlGenerator.java | 67 +- .../codegen/languages/SwiftGenerator.java | 457 +- .../codegen/languages/TizenClientCodegen.java | 497 +- .../main/resources/Groovy/ApiUtils.mustache | 76 +- .../src/main/resources/Groovy/api.mustache | 53 +- .../resources/Groovy/build.gradle.mustache | 24 +- .../src/main/resources/Groovy/model.mustache | 22 +- .../main/resources/Java/ApiClient.mustache | 930 +-- .../resources/Java/Configuration.mustache | 30 +- .../src/main/resources/Java/JsonUtil.mustache | 20 +- .../main/resources/Java/StringUtil.mustache | 70 +- .../src/main/resources/Java/api.mustache | 178 +- .../main/resources/Java/apiException.mustache | 82 +- .../resources/Java/auth/ApiKeyAuth.mustache | 100 +- .../Java/auth/Authentication.mustache | 6 +- .../Java/auth/HttpBasicAuth.mustache | 58 +- .../main/resources/Java/auth/OAuth.mustache | 10 +- .../src/main/resources/Java/model.mustache | 64 +- .../src/main/resources/Java/pom.mustache | 325 +- .../resources/JavaJaxRS/ApiException.mustache | 10 +- .../JavaJaxRS/ApiOriginFilter.mustache | 30 +- .../JavaJaxRS/ApiResponseMessage.mustache | 108 +- .../JavaJaxRS/NotFoundException.mustache | 10 +- .../main/resources/JavaJaxRS/README.mustache | 2 +- .../src/main/resources/JavaJaxRS/api.mustache | 40 +- .../resources/JavaJaxRS/apiService.mustache | 12 +- .../JavaJaxRS/apiServiceFactory.mustache | 10 +- .../JavaJaxRS/apiServiceImpl.mustache | 20 +- .../resources/JavaJaxRS/formParams.mustache | 2 +- .../main/resources/JavaJaxRS/model.mustache | 64 +- .../src/main/resources/JavaJaxRS/pom.mustache | 316 +- .../src/main/resources/JavaJaxRS/web.mustache | 96 +- .../main/resources/JavaSpringMVC/api.mustache | 38 +- .../JavaSpringMVC/apiException.mustache | 10 +- .../JavaSpringMVC/apiOriginFilter.mustache | 30 +- .../JavaSpringMVC/apiResponseMessage.mustache | 108 +- .../JavaSpringMVC/formParams.mustache | 2 +- .../resources/JavaSpringMVC/model.mustache | 64 +- .../JavaSpringMVC/notFoundException.mustache | 10 +- .../main/resources/JavaSpringMVC/pom.mustache | 453 +- .../JavaSpringMVC/swaggerConfig.mustache | 32 +- .../swaggerUiConfiguration.mustache | 66 +- .../JavaSpringMVC/webApplication.mustache | 24 +- .../webMvcConfiguration.mustache | 8 +- .../main/resources/akka-scala/api.mustache | 58 +- .../resources/akka-scala/apiInvoker.mustache | 551 +- .../resources/akka-scala/apiRequest.mustache | 56 +- .../resources/akka-scala/apiSettings.mustache | 28 +- .../akka-scala/enumsSerializers.mustache | 43 +- .../resources/akka-scala/javadoc.mustache | 18 +- .../main/resources/akka-scala/model.mustache | 36 +- .../resources/akka-scala/reference.mustache | 28 +- .../resources/akka-scala/requests.mustache | 186 +- .../main/resources/android-java/api.mustache | 166 +- .../android-java/apiException.mustache | 44 +- .../android-java/apiInvoker.mustache | 675 +-- .../resources/android-java/build.mustache | 118 +- .../resources/android-java/httpPatch.mustache | 16 +- .../resources/android-java/jsonUtil.mustache | 83 +- .../resources/android-java/manifest.mustache | 2 +- .../resources/android-java/model.mustache | 66 +- .../main/resources/android-java/pom.mustache | 301 +- .../main/resources/asyncscala/api.mustache | 50 +- .../main/resources/asyncscala/client.mustache | 20 +- .../main/resources/asyncscala/model.mustache | 12 +- .../main/resources/asyncscala/sbt.mustache | 12 +- .../main/resources/codegen/README.mustache | 2 +- .../resources/codegen/generatorClass.mustache | 342 +- .../src/main/resources/codegen/pom.mustache | 199 +- .../main/resources/csharp/ApiClient.mustache | 443 +- .../resources/csharp/ApiException.mustache | 79 +- .../resources/csharp/Configuration.mustache | 75 +- .../src/main/resources/csharp/api.mustache | 324 +- .../src/main/resources/csharp/model.mustache | 78 +- .../resources/flash/AirExecutorApp-app.xml | 222 +- .../main/resources/flash/ApiClientEvent.as | 17 +- .../src/main/resources/flash/ApiError.as | 15 +- .../src/main/resources/flash/ApiErrorCodes.as | 64 +- .../src/main/resources/flash/ApiInvoker.as | 289 - .../src/main/resources/flash/ApiUrlHelper.as | 12 +- .../resources/flash/ApiUserCredentials.as | 66 +- .../src/main/resources/flash/ListWrapper.as | 14 +- .../src/main/resources/flash/Response.as | 51 +- .../src/main/resources/flash/SwaggerApi.as | 134 +- .../src/main/resources/flash/XMLWriter.as | 50 +- .../src/main/resources/flash/api.mustache | 32 +- .../src/main/resources/flash/facetValue.as | 8 +- .../src/main/resources/flash/model.mustache | 52 +- .../main/resources/flash/modelList.mustache | 12 +- .../resources/htmlDocs/bodyParam.mustache | 6 +- .../resources/htmlDocs/formParam.mustache | 6 +- .../resources/htmlDocs/headerParam.mustache | 6 +- .../main/resources/htmlDocs/index.mustache | 131 +- .../resources/htmlDocs/pathParam.mustache | 6 +- .../resources/htmlDocs/queryParam.mustache | 6 +- .../resources/htmlDocs/style.css.mustache | 138 +- .../src/main/resources/logback.xml | 20 +- .../main/resources/nodejs/controller.mustache | 28 +- .../src/main/resources/nodejs/index.mustache | 32 +- .../main/resources/nodejs/package.mustache | 26 +- .../main/resources/nodejs/service.mustache | 24 +- .../main/resources/nodejs/swagger.mustache | 76 +- .../objc/SWGConfiguration-body.mustache | 96 +- .../objc/SWGConfiguration-header.mustache | 47 +- .../src/main/resources/objc/api-body.mustache | 322 +- .../main/resources/objc/api-header.mustache | 63 +- .../apiBodyResponseWithContainer.mustache | 74 +- .../objc/apiNonPrimitiveResponse.mustache | 44 +- .../objc/apiPrimitiveResponse.mustache | 68 +- .../main/resources/objc/model-body.mustache | 40 +- .../main/resources/objc/model-header.mustache | 27 +- .../main/resources/objc/voidResponse.mustache | 30 +- .../main/resources/perl/ApiClient.mustache | 342 +- .../main/resources/perl/BaseObject.mustache | 78 +- .../src/main/resources/perl/api.mustache | 154 +- .../src/main/resources/perl/object.mustache | 100 +- .../src/main/resources/php/APIClient.mustache | 758 +-- .../main/resources/php/ApiException.mustache | 36 +- .../src/main/resources/php/api.mustache | 180 +- .../src/main/resources/php/composer.mustache | 60 +- .../src/main/resources/php/model.mustache | 48 +- .../src/main/resources/python/README.mustache | 6 +- .../src/main/resources/python/api.mustache | 66 +- .../main/resources/python/api_client.mustache | 548 +- .../resources/python/configuration.mustache | 52 +- .../src/main/resources/python/model.mustache | 52 +- .../src/main/resources/python/rest.mustache | 436 +- .../src/main/resources/python/setup.mustache | 26 +- .../main/resources/python3/__init__.mustache | 4 +- .../src/main/resources/python3/api.mustache | 52 +- .../src/main/resources/python3/model.mustache | 40 +- .../main/resources/python3/swagger.mustache | 412 +- .../main/resources/qt5cpp/api-body.mustache | 358 +- .../main/resources/qt5cpp/api-header.mustache | 22 +- .../resources/qt5cpp/helpers-body.mustache | 309 +- .../resources/qt5cpp/helpers-header.mustache | 13 +- .../main/resources/qt5cpp/model-body.mustache | 165 +- .../resources/qt5cpp/model-header.mustache | 41 +- .../src/main/resources/qt5cpp/model.mustache | 56 +- .../resources/qt5cpp/modelFactory.mustache | 39 +- .../src/main/resources/qt5cpp/object.mustache | 21 +- .../src/main/resources/retrofit/api.mustache | 32 +- .../main/resources/retrofit/model.mustache | 58 +- .../src/main/resources/retrofit/pom.mustache | 277 +- .../main/resources/retrofit/service.mustache | 20 +- .../src/main/resources/ruby/api.mustache | 104 +- .../main/resources/ruby/base_object.mustache | 148 +- .../src/main/resources/ruby/model.mustache | 58 +- .../src/main/resources/ruby/monkey.mustache | 158 +- .../src/main/resources/ruby/swagger.mustache | 146 +- .../ruby/swagger/configuration.mustache | 48 +- .../resources/ruby/swagger/request.mustache | 540 +- .../resources/ruby/swagger/response.mustache | 112 +- .../resources/ruby/swagger/version.mustache | 6 +- .../ruby/swagger_client.gemspec.mustache | 46 +- .../resources/ruby/swagger_client.mustache | 12 +- .../src/main/resources/scala/api.mustache | 140 +- .../main/resources/scala/apiInvoker.mustache | 334 +- .../src/main/resources/scala/model.mustache | 12 +- .../src/main/resources/scala/pom.mustache | 431 +- .../resources/scalatra/Bootstrap.mustache | 22 +- .../main/resources/scalatra/JettyMain.scala | 20 +- .../main/resources/scalatra/JsonUtil.scala | 2 - .../main/resources/scalatra/README.mustache | 2 +- .../resources/scalatra/ServletApp.mustache | 44 +- .../src/main/resources/scalatra/api.mustache | 108 +- .../src/main/resources/scalatra/build.sbt | 50 +- .../main/resources/scalatra/model.mustache | 14 +- .../src/main/resources/scalatra/web.xml | 28 +- .../assets/css/bootstrap-responsive.css | 2285 ++++---- .../swagger-static/assets/css/bootstrap.css | 5205 +++++++++-------- .../swagger-static/assets/css/style.css | 323 +- .../swagger-static/assets/js/bootstrap.js | 2855 ++++----- .../assets/js/jquery-1.8.3.min.js | 2803 ++++++++- .../swagger-static/assets/js/main.js | 101 +- .../resources/swagger-static/index.mustache | 90 +- .../resources/swagger-static/model.mustache | 20 +- .../swagger-static/operation.mustache | 68 +- .../resources/swagger-static/package.mustache | 20 +- .../src/main/resources/swagger-static/pom.xml | 196 +- .../main/resources/swift/APIHelper.mustache | 24 +- .../src/main/resources/swift/APIs.mustache | 71 +- .../swift/AlamofireImplementations.mustache | 129 +- .../main/resources/swift/Extensions.mustache | 39 +- .../src/main/resources/swift/Models.mustache | 206 +- .../src/main/resources/swift/api.mustache | 75 +- .../src/main/resources/swift/model.mustache | 32 +- .../main/resources/tizen/api-body.mustache | 226 +- .../main/resources/tizen/api-header.mustache | 53 +- .../resources/tizen/apiclient-body.mustache | 196 +- .../resources/tizen/apiclient-header.mustache | 100 +- .../main/resources/tizen/error-body.mustache | 30 +- .../resources/tizen/error-header.mustache | 23 +- .../resources/tizen/helpers-body.mustache | 488 +- .../resources/tizen/helpers-header.mustache | 89 +- .../main/resources/tizen/model-body.mustache | 259 +- .../resources/tizen/model-header.mustache | 56 +- .../resources/tizen/modelFactory.mustache | 42 +- .../src/main/resources/tizen/object.mustache | 43 +- .../main/resources/validator/index.mustache | 20 +- .../src/test/resources/2_0/postBodyTest.json | 2 +- .../src/test/resources/2_0/requiredTest.json | 4 +- .../resources/2_0/responseSelectionTest.json | 4 +- .../src/test/resources/2_0/v1beta3.json | 612 +- .../src/test/resources/2_0/wordnik.json | 2 +- .../src/test/scala/ClientAuthInputTest.scala | 34 +- .../src/test/scala/CodegenTest.scala | 74 +- .../src/test/scala/ExampleGeneratorTest.scala | 44 +- .../test/scala/Java/JavaInheritanceTest.scala | 17 +- .../test/scala/Java/JavaModelEnumTest.scala | 6 +- .../src/test/scala/Java/JavaModelTest.scala | 353 +- .../src/test/scala/Objc/ObjcModelTest.scala | 256 +- .../src/test/scala/SwaggerMigratorTest.scala | 9 +- .../src/test/scala/php/PhpModelTest.scala | 247 +- .../src/test/scala/python/PythonTest.scala | 6 +- .../src/test/scala/scala/ScalaModelTest.scala | 259 +- .../staticDocs/StaticOperationTest.scala | 54 +- modules/swagger-generator/pom.xml | 459 +- .../java/io/swagger/generator/Bootstrap.java | 66 +- .../generator/DynamicSwaggerConfig.java | 116 +- .../generator/exception/ApiException.java | 39 +- .../exception/BadRequestException.java | 37 +- .../exception/NotFoundException.java | 37 +- .../swagger/generator/model/ApiResponse.java | 133 +- .../io/swagger/generator/model/Generated.java | 56 +- .../generator/model/GeneratorInput.java | 75 +- .../swagger/generator/model/InputOption.java | 97 +- .../swagger/generator/model/ResponseCode.java | 42 +- .../swagger/generator/online/Generator.java | 303 +- .../generator/resource/ExceptionWriter.java | 72 +- .../generator/resource/SwaggerResource.java | 238 +- .../generator/util/ApiOriginFilter.java | 65 +- .../generator/util/ValidationException.java | 38 +- .../generator/util/ValidationMessage.java | 41 +- .../io/swagger/generator/util/ZipUtil.java | 112 +- .../src/main/resources/logback.xml | 20 +- .../src/main/webapp/WEB-INF/web.xml | 90 +- .../src/test/scala/GeneratorInputTest.scala | 8 +- pom.xml | 943 +-- samples/client/petstore/akka-scala/pom.xml | 11 +- .../src/main/resources/reference.conf | 28 +- .../swagger/client/api/EnumsSerializers.scala | 8 +- .../scala/io/swagger/client/api/PetApi.scala | 85 +- .../io/swagger/client/api/StoreApi.scala | 46 +- .../scala/io/swagger/client/api/UserApi.scala | 76 +- .../io/swagger/client/core/ApiInvoker.scala | 190 +- .../io/swagger/client/core/ApiRequest.scala | 36 +- .../io/swagger/client/core/ApiSettings.scala | 14 +- .../io/swagger/client/core/requests.scala | 17 +- .../io/swagger/client/model/Category.scala | 11 +- .../scala/io/swagger/client/model/Order.scala | 25 +- .../scala/io/swagger/client/model/Pet.scala | 25 +- .../scala/io/swagger/client/model/Tag.scala | 11 +- .../scala/io/swagger/client/model/User.scala | 25 +- .../client/petstore/android-java/build.gradle | 8 +- samples/client/petstore/android-java/pom.xml | 300 +- .../android-java/src/main/AndroidManifest.xml | 2 +- .../src/main/java/AndroidManifest.xml | 2 +- .../java/io/swagger/client/ApiException.java | 45 +- .../java/io/swagger/client/ApiInvoker.java | 652 +-- .../java/io/swagger/client/HttpPatch.java | 2 - .../main/java/io/swagger/client/JsonUtil.java | 150 +- .../java/io/swagger/client/api/PetApi.java | 938 ++- .../java/io/swagger/client/api/StoreApi.java | 434 +- .../java/io/swagger/client/api/UserApi.java | 846 ++- .../io/swagger/client/model/Category.java | 84 +- .../java/io/swagger/client/model/Order.java | 209 +- .../java/io/swagger/client/model/Pet.java | 210 +- .../java/io/swagger/client/model/Tag.java | 84 +- .../java/io/swagger/client/model/User.java | 260 +- .../io/swagger/petstore/test/PetApiTest.java | 258 +- .../swagger/petstore/test/StoreApiTest.java | 91 +- .../io/swagger/petstore/test/UserApiTest.java | 148 +- .../io/swagger/client/SwaggerClient.scala | 15 +- .../scala/io/swagger/client/api/PetApi.scala | 93 +- .../io/swagger/client/api/StoreApi.scala | 44 +- .../scala/io/swagger/client/api/UserApi.scala | 86 +- .../io/swagger/client/model/Category.scala | 10 +- .../scala/io/swagger/client/model/Order.scala | 18 +- .../scala/io/swagger/client/model/Pet.scala | 18 +- .../scala/io/swagger/client/model/Tag.scala | 10 +- .../scala/io/swagger/client/model/User.scala | 22 +- .../async-scala/src/test/scala/Test.scala | 17 +- .../petstore/flash/FlashPetstoreCodegen.scala | 26 +- .../petstore/flash/bin/AirExecutorApp-app.xml | 222 +- .../flex/com/wordnik/client/api/PetApi.as | 167 +- .../flex/com/wordnik/client/api/StoreApi.as | 69 +- .../flex/com/wordnik/client/api/UserApi.as | 154 +- .../flex/com/wordnik/client/model/Category.as | 18 +- .../com/wordnik/client/model/CategoryList.as | 15 +- .../flex/com/wordnik/client/model/Order.as | 32 +- .../com/wordnik/client/model/OrderList.as | 15 +- .../main/flex/com/wordnik/client/model/Pet.as | 51 +- .../flex/com/wordnik/client/model/PetList.as | 15 +- .../main/flex/com/wordnik/client/model/Tag.as | 18 +- .../flex/com/wordnik/client/model/TagList.as | 15 +- .../flex/com/wordnik/client/model/User.as | 44 +- .../flex/com/wordnik/client/model/UserList.as | 15 +- .../com/wordnik/swagger/common/ApiInvoker.as | 277 +- .../wordnik/swagger/common/ApiUrlHelper.as | 10 +- .../swagger/common/ApiUserCredentials.as | 66 +- .../com/wordnik/swagger/common/ListWrapper.as | 14 +- .../com/wordnik/swagger/common/SwaggerApi.as | 141 +- .../com/wordnik/swagger/common/XMLWriter.as | 28 - .../wordnik/swagger/event/ApiClientEvent.as | 13 +- .../com/wordnik/swagger/event/Response.as | 51 +- .../com/wordnik/swagger/exception/ApiError.as | 15 +- .../swagger/exception/ApiErrorCodes.as | 64 +- samples/client/petstore/java/pom.xml | 324 +- .../java/io/swagger/client/ApiClient.java | 897 ++- .../java/io/swagger/client/ApiException.java | 83 +- .../java/io/swagger/client/Configuration.java | 30 +- .../main/java/io/swagger/client/JsonUtil.java | 27 +- .../java/io/swagger/client/StringUtil.java | 72 +- .../java/io/swagger/client/api/PetApi.java | 1030 ++-- .../java/io/swagger/client/api/StoreApi.java | 472 +- .../java/io/swagger/client/api/UserApi.java | 912 ++- .../io/swagger/client/auth/ApiKeyAuth.java | 98 +- .../swagger/client/auth/Authentication.java | 6 +- .../io/swagger/client/auth/HttpBasicAuth.java | 49 +- .../java/io/swagger/client/auth/OAuth.java | 8 +- .../io/swagger/client/model/Category.java | 84 +- .../java/io/swagger/client/model/Order.java | 209 +- .../java/io/swagger/client/model/Pet.java | 210 +- .../java/io/swagger/client/model/Tag.java | 84 +- .../java/io/swagger/client/model/User.java | 260 +- .../java/io/swagger/client/ApiClientTest.java | 163 +- .../io/swagger/client/ConfigurationTest.java | 15 +- .../io/swagger/client/StringUtilTest.java | 45 +- .../swagger/client/auth/ApiKeyAuthTest.java | 63 +- .../client/auth/HttpBasicAuthTest.java | 79 +- .../io/swagger/petstore/test/PetApiTest.java | 306 +- .../swagger/petstore/test/StoreApiTest.java | 98 +- .../io/swagger/petstore/test/UserApiTest.java | 154 +- .../AppIcon.appiconset/Contents.json | 68 +- .../LaunchImage.launchimage/Contents.json | 70 +- .../petstore/objc/PetstoreClient/pom.xml | 44 +- samples/client/petstore/objc/pom.xml | 126 +- samples/client/petstore/perl/pom.xml | 88 +- .../php/SwaggerClient-php/composer.json | 4 +- .../petstore/php/SwaggerClient-php/pom.xml | 114 +- .../python/SwaggerPetstore-python/pom.xml | 88 +- .../python3/Python3PetstoreCodegen.scala | 26 +- samples/client/petstore/retrofit/pom.xml | 276 +- .../io/swagger/client/ServiceGenerator.java | 25 +- .../java/io/swagger/client/api/PetApi.java | 218 +- .../java/io/swagger/client/api/StoreApi.java | 102 +- .../java/io/swagger/client/api/UserApi.java | 204 +- .../io/swagger/client/model/Category.java | 21 +- .../java/io/swagger/client/model/Order.java | 55 +- .../java/io/swagger/client/model/Pet.java | 61 +- .../java/io/swagger/client/model/Tag.java | 21 +- .../java/io/swagger/client/model/User.java | 51 +- .../io/swagger/petstore/test/PetApiTest.java | 259 +- .../swagger/petstore/test/StoreApiTest.java | 92 +- .../io/swagger/petstore/test/UserApiTest.java | 146 +- samples/client/petstore/ruby/pom.xml | 116 +- samples/client/petstore/scala/pom.xml | 430 +- .../scala/io/swagger/client/ApiInvoker.scala | 63 +- .../scala/io/swagger/client/api/PetApi.scala | 233 +- .../io/swagger/client/api/StoreApi.scala | 118 +- .../scala/io/swagger/client/api/UserApi.scala | 218 +- .../io/swagger/client/model/Category.scala | 8 +- .../scala/io/swagger/client/model/Order.scala | 19 +- .../scala/io/swagger/client/model/Pet.scala | 20 +- .../scala/io/swagger/client/model/Tag.scala | 8 +- .../scala/io/swagger/client/model/User.scala | 22 +- .../scala/src/test/scala/PetApiTest.scala | 14 +- .../scala/src/test/scala/StoreApiTest.scala | 14 +- .../scala/src/test/scala/UserApiTest.scala | 36 +- .../PHPWordnikApiCodegen.scala | 26 +- .../scala/src/test/scala/AccountApiTest.scala | 15 +- .../scala/src/test/scala/WordApiTest.scala | 20 +- .../src/test/scala/WordListApiTest.scala | 31 +- .../scala/src/test/scala/WordsApiTest.scala | 9 - samples/client/wordnik/akka-scala/pom.xml | 11 +- .../src/main/resources/reference.conf | 28 +- .../io/swagger/client/api/AccountApi.scala | 75 +- .../swagger/client/api/EnumsSerializers.scala | 8 +- .../scala/io/swagger/client/api/WordApi.scala | 145 +- .../io/swagger/client/api/WordListApi.scala | 101 +- .../io/swagger/client/api/WordListsApi.scala | 20 +- .../io/swagger/client/api/WordsApi.scala | 67 +- .../io/swagger/client/core/ApiInvoker.scala | 190 +- .../io/swagger/client/core/ApiRequest.scala | 36 +- .../io/swagger/client/core/ApiSettings.scala | 14 +- .../io/swagger/client/core/requests.scala | 17 +- .../swagger/client/model/ApiTokenStatus.scala | 19 +- .../io/swagger/client/model/AudioFile.scala | 35 +- .../io/swagger/client/model/AudioType.scala | 11 +- .../client/model/AuthenticationToken.scala | 13 +- .../io/swagger/client/model/Bigram.scala | 17 +- .../io/swagger/client/model/Category.scala | 11 +- .../io/swagger/client/model/Citation.scala | 11 +- .../client/model/ContentProvider.scala | 11 +- .../io/swagger/client/model/Definition.scala | 39 +- .../model/DefinitionSearchResults.scala | 11 +- .../io/swagger/client/model/Example.scala | 31 +- .../client/model/ExampleSearchResults.scala | 11 +- .../swagger/client/model/ExampleUsage.scala | 9 +- .../scala/io/swagger/client/model/Facet.scala | 11 +- .../io/swagger/client/model/FacetValue.scala | 11 +- .../io/swagger/client/model/Frequency.scala | 11 +- .../client/model/FrequencySummary.scala | 17 +- .../scala/io/swagger/client/model/Label.scala | 11 +- .../scala/io/swagger/client/model/Note.scala | 15 +- .../swagger/client/model/PartOfSpeech.scala | 13 +- .../io/swagger/client/model/Related.scala | 21 +- .../scala/io/swagger/client/model/Root.scala | 13 +- .../io/swagger/client/model/ScoredWord.scala | 29 +- .../io/swagger/client/model/Sentence.scala | 19 +- .../client/model/SimpleDefinition.scala | 15 +- .../swagger/client/model/SimpleExample.scala | 15 +- .../io/swagger/client/model/StringValue.scala | 9 +- .../io/swagger/client/model/Syllable.scala | 13 +- .../io/swagger/client/model/TextPron.scala | 13 +- .../scala/io/swagger/client/model/User.scala | 23 +- .../io/swagger/client/model/WordList.scala | 29 +- .../swagger/client/model/WordListWord.scala | 21 +- .../io/swagger/client/model/WordObject.scala | 19 +- .../swagger/client/model/WordOfTheDay.scala | 31 +- .../client/model/WordSearchResult.scala | 13 +- .../client/model/WordSearchResults.scala | 11 +- samples/client/wordnik/android-java/pom.xml | 314 +- .../java/io/swagger/client/ApiException.java | 45 +- .../java/io/swagger/client/ApiInvoker.java | 460 +- .../java/io/swagger/client/HttpPatch.java | 2 - .../main/java/io/swagger/client/JsonUtil.java | 23 +- .../io/swagger/client/api/AccountApi.java | 406 +- .../java/io/swagger/client/api/WordApi.java | 950 ++- .../io/swagger/client/api/WordListApi.java | 491 +- .../io/swagger/client/api/WordListsApi.java | 116 +- .../java/io/swagger/client/api/WordsApi.java | 630 +- .../swagger/client/model/ApiTokenStatus.java | 201 +- .../io/swagger/client/model/AudioFile.java | 437 +- .../io/swagger/client/model/AudioType.java | 85 +- .../client/model/AuthenticationToken.java | 114 +- .../java/io/swagger/client/model/Bigram.java | 172 +- .../io/swagger/client/model/Category.java | 85 +- .../io/swagger/client/model/Citation.java | 85 +- .../swagger/client/model/ContentProvider.java | 85 +- .../io/swagger/client/model/Definition.java | 504 +- .../client/model/DefinitionSearchResults.java | 90 +- .../java/io/swagger/client/model/Example.java | 380 +- .../client/model/ExampleSearchResults.java | 90 +- .../io/swagger/client/model/ExampleUsage.java | 56 +- .../java/io/swagger/client/model/Facet.java | 90 +- .../io/swagger/client/model/FacetValue.java | 85 +- .../io/swagger/client/model/Frequency.java | 85 +- .../client/model/FrequencySummary.java | 177 +- .../java/io/swagger/client/model/Label.java | 85 +- .../java/io/swagger/client/model/Note.java | 148 +- .../io/swagger/client/model/PartOfSpeech.java | 119 +- .../java/io/swagger/client/model/Related.java | 235 +- .../java/io/swagger/client/model/Root.java | 119 +- .../io/swagger/client/model/ScoredWord.java | 346 +- .../io/swagger/client/model/Sentence.java | 206 +- .../client/model/SimpleDefinition.java | 143 +- .../swagger/client/model/SimpleExample.java | 143 +- .../io/swagger/client/model/StringValue.java | 56 +- .../io/swagger/client/model/Syllable.java | 114 +- .../io/swagger/client/model/TextPron.java | 114 +- .../java/io/swagger/client/model/User.java | 259 +- .../io/swagger/client/model/WordList.java | 350 +- .../io/swagger/client/model/WordListWord.java | 234 +- .../io/swagger/client/model/WordObject.java | 206 +- .../io/swagger/client/model/WordOfTheDay.java | 384 +- .../client/model/WordSearchResult.java | 114 +- .../client/model/WordSearchResults.java | 90 +- samples/client/wordnik/java/pom.xml | 326 +- .../java/io/swagger/client/ApiException.java | 45 +- .../java/io/swagger/client/ApiInvoker.java | 308 +- .../main/java/io/swagger/client/JsonUtil.java | 27 +- .../io/swagger/client/api/AccountApi.java | 532 +- .../java/io/swagger/client/api/WordApi.java | 1260 ++-- .../io/swagger/client/api/WordListApi.java | 649 +- .../io/swagger/client/api/WordListsApi.java | 135 +- .../java/io/swagger/client/api/WordsApi.java | 758 +-- .../swagger/client/model/ApiTokenStatus.java | 201 +- .../io/swagger/client/model/AudioFile.java | 437 +- .../io/swagger/client/model/AudioType.java | 85 +- .../client/model/AuthenticationToken.java | 114 +- .../java/io/swagger/client/model/Bigram.java | 172 +- .../io/swagger/client/model/Category.java | 85 +- .../io/swagger/client/model/Citation.java | 85 +- .../swagger/client/model/ContentProvider.java | 85 +- .../io/swagger/client/model/Definition.java | 504 +- .../client/model/DefinitionSearchResults.java | 90 +- .../java/io/swagger/client/model/Example.java | 380 +- .../client/model/ExampleSearchResults.java | 90 +- .../io/swagger/client/model/ExampleUsage.java | 56 +- .../java/io/swagger/client/model/Facet.java | 90 +- .../io/swagger/client/model/FacetValue.java | 85 +- .../io/swagger/client/model/Frequency.java | 85 +- .../client/model/FrequencySummary.java | 177 +- .../java/io/swagger/client/model/Label.java | 85 +- .../java/io/swagger/client/model/Note.java | 148 +- .../io/swagger/client/model/PartOfSpeech.java | 119 +- .../java/io/swagger/client/model/Related.java | 235 +- .../java/io/swagger/client/model/Root.java | 119 +- .../io/swagger/client/model/ScoredWord.java | 346 +- .../io/swagger/client/model/Sentence.java | 206 +- .../client/model/SimpleDefinition.java | 143 +- .../swagger/client/model/SimpleExample.java | 143 +- .../io/swagger/client/model/StringValue.java | 56 +- .../io/swagger/client/model/Syllable.java | 114 +- .../io/swagger/client/model/TextPron.java | 114 +- .../java/io/swagger/client/model/User.java | 259 +- .../io/swagger/client/model/WordList.java | 350 +- .../io/swagger/client/model/WordListWord.java | 234 +- .../io/swagger/client/model/WordObject.java | 206 +- .../io/swagger/client/model/WordOfTheDay.java | 384 +- .../client/model/WordSearchResult.java | 114 +- .../client/model/WordSearchResults.java | 90 +- samples/client/wordnik/scala/pom.xml | 430 +- .../java/io/swagger/client/ApiInvoker.scala | 55 +- .../io/swagger/client/api/AccountApi.scala | 138 +- .../java/io/swagger/client/api/WordApi.scala | 438 -- .../io/swagger/client/api/WordListApi.scala | 166 +- .../io/swagger/client/api/WordListsApi.scala | 37 +- .../java/io/swagger/client/api/WordsApi.scala | 232 +- .../swagger/client/model/ApiTokenStatus.scala | 16 +- .../io/swagger/client/model/AudioFile.scala | 33 +- .../io/swagger/client/model/AudioType.scala | 8 +- .../client/model/AuthenticationToken.scala | 10 +- .../java/io/swagger/client/model/Bigram.scala | 14 +- .../io/swagger/client/model/Category.scala | 8 +- .../io/swagger/client/model/Citation.scala | 8 +- .../client/model/ContentProvider.scala | 8 +- .../io/swagger/client/model/Definition.scala | 42 +- .../model/DefinitionSearchResults.scala | 9 +- .../io/swagger/client/model/Example.scala | 31 +- .../client/model/ExampleSearchResults.scala | 10 +- .../swagger/client/model/ExampleUsage.scala | 6 +- .../java/io/swagger/client/model/Facet.scala | 9 +- .../io/swagger/client/model/FacetValue.scala | 8 +- .../io/swagger/client/model/Frequency.scala | 8 +- .../client/model/FrequencySummary.scala | 15 +- .../java/io/swagger/client/model/Label.scala | 8 +- .../java/io/swagger/client/model/Note.scala | 12 +- .../swagger/client/model/PartOfSpeech.scala | 12 +- .../io/swagger/client/model/Related.scala | 18 +- .../java/io/swagger/client/model/Root.scala | 11 +- .../io/swagger/client/model/ScoredWord.scala | 26 +- .../io/swagger/client/model/Sentence.scala | 17 +- .../client/model/SimpleDefinition.scala | 12 +- .../swagger/client/model/SimpleExample.scala | 12 +- .../io/swagger/client/model/StringValue.scala | 6 +- .../io/swagger/client/model/Syllable.scala | 10 +- .../io/swagger/client/model/TextPron.scala | 10 +- .../java/io/swagger/client/model/User.scala | 20 +- .../io/swagger/client/model/WordList.scala | 27 +- .../swagger/client/model/WordListWord.scala | 19 +- .../io/swagger/client/model/WordObject.scala | 16 +- .../swagger/client/model/WordOfTheDay.scala | 32 +- .../client/model/WordSearchResult.scala | 10 +- .../client/model/WordSearchResults.scala | 9 +- .../scala/io/swagger/client/ApiInvoker.scala | 56 +- .../io/swagger/client/api/AccountApi.scala | 138 +- .../scala/io/swagger/client/api/WordApi.scala | 338 +- .../io/swagger/client/api/WordListApi.scala | 166 +- .../io/swagger/client/api/WordListsApi.scala | 37 +- .../io/swagger/client/api/WordsApi.scala | 232 +- .../swagger/client/model/ApiTokenStatus.scala | 16 +- .../io/swagger/client/model/AudioFile.scala | 33 +- .../io/swagger/client/model/AudioType.scala | 8 +- .../client/model/AuthenticationToken.scala | 10 +- .../io/swagger/client/model/Bigram.scala | 14 +- .../io/swagger/client/model/Category.scala | 8 +- .../io/swagger/client/model/Citation.scala | 8 +- .../client/model/ContentProvider.scala | 8 +- .../io/swagger/client/model/Definition.scala | 42 +- .../model/DefinitionSearchResults.scala | 9 +- .../io/swagger/client/model/Example.scala | 31 +- .../client/model/ExampleSearchResults.scala | 10 +- .../swagger/client/model/ExampleUsage.scala | 6 +- .../scala/io/swagger/client/model/Facet.scala | 9 +- .../io/swagger/client/model/FacetValue.scala | 8 +- .../io/swagger/client/model/Frequency.scala | 8 +- .../client/model/FrequencySummary.scala | 15 +- .../scala/io/swagger/client/model/Label.scala | 8 +- .../scala/io/swagger/client/model/Note.scala | 12 +- .../swagger/client/model/PartOfSpeech.scala | 12 +- .../io/swagger/client/model/Related.scala | 18 +- .../scala/io/swagger/client/model/Root.scala | 11 +- .../io/swagger/client/model/ScoredWord.scala | 26 +- .../io/swagger/client/model/Sentence.scala | 17 +- .../client/model/SimpleDefinition.scala | 12 +- .../swagger/client/model/SimpleExample.scala | 12 +- .../io/swagger/client/model/StringValue.scala | 6 +- .../io/swagger/client/model/Syllable.scala | 10 +- .../io/swagger/client/model/TextPron.scala | 10 +- .../scala/io/swagger/client/model/User.scala | 20 +- .../io/swagger/client/model/WordList.scala | 27 +- .../swagger/client/model/WordListWord.scala | 19 +- .../io/swagger/client/model/WordObject.scala | 16 +- .../swagger/client/model/WordOfTheDay.scala | 32 +- .../client/model/WordSearchResult.scala | 10 +- .../client/model/WordSearchResults.scala | 9 +- .../docs/assets/css/bootstrap-responsive.css | 2285 ++++---- .../docs/assets/css/bootstrap.css | 5205 +++++++++-------- .../dynamic-html/docs/assets/css/style.css | 323 +- .../dynamic-html/docs/assets/js/bootstrap.js | 2855 ++++----- .../docs/assets/js/jquery-1.8.3.min.js | 2803 ++++++++- samples/dynamic-html/docs/assets/js/main.js | 101 +- samples/dynamic-html/docs/index.html | 210 +- .../dynamic-html/docs/models/Category.html | 17 +- samples/dynamic-html/docs/models/Order.html | 49 +- samples/dynamic-html/docs/models/Pet.html | 49 +- samples/dynamic-html/docs/models/Tag.html | 17 +- samples/dynamic-html/docs/models/User.html | 65 +- .../dynamic-html/docs/operations/PetApi.html | 589 +- .../docs/operations/StoreApi.html | 223 +- .../dynamic-html/docs/operations/UserApi.html | 498 +- samples/html/index.html | 1346 +++-- .../php/PHPServerGenerator.scala | 28 +- .../server-generator/php/output/composer.json | 6 +- .../php/templates/composer.json | 6 +- .../php/templates/index.mustache | 20 +- samples/server/petstore/jaxrs/pom.xml | 315 +- .../gen/java/io/swagger/api/ApiException.java | 13 +- .../java/io/swagger/api/ApiOriginFilter.java | 34 +- .../io/swagger/api/ApiResponseMessage.java | 109 +- .../io/swagger/api/NotFoundException.java | 11 +- .../src/gen/java/io/swagger/api/PetApi.java | 193 +- .../java/io/swagger/api/PetApiService.java | 62 +- .../src/gen/java/io/swagger/api/StoreApi.java | 101 +- .../java/io/swagger/api/StoreApiService.java | 36 +- .../src/gen/java/io/swagger/api/UserApi.java | 170 +- .../java/io/swagger/api/UserApiService.java | 61 +- .../gen/java/io/swagger/model/Category.java | 84 +- .../src/gen/java/io/swagger/model/Order.java | 209 +- .../src/gen/java/io/swagger/model/Pet.java | 210 +- .../src/gen/java/io/swagger/model/Tag.java | 84 +- .../src/gen/java/io/swagger/model/User.java | 260 +- .../api/factories/PetApiServiceFactory.java | 9 +- .../api/factories/StoreApiServiceFactory.java | 9 +- .../api/factories/UserApiServiceFactory.java | 9 +- .../swagger/api/impl/PetApiServiceImpl.java | 126 +- .../swagger/api/impl/StoreApiServiceImpl.java | 72 +- .../swagger/api/impl/UserApiServiceImpl.java | 125 +- .../jaxrs/src/main/webapp/WEB-INF/web.xml | 98 +- .../server/petstore/nodejs/controllers/Pet.js | 174 +- .../petstore/nodejs/controllers/PetService.js | 176 +- .../petstore/nodejs/controllers/Store.js | 78 +- .../nodejs/controllers/StoreService.js | 102 +- .../petstore/nodejs/controllers/User.js | 166 +- .../nodejs/controllers/UserService.js | 98 +- samples/server/petstore/nodejs/index.js | 32 +- samples/server/petstore/scalatra/build.sbt | 50 +- .../scalatra/src/main/scala/JettyMain.scala | 20 +- .../src/main/scala/ScalatraBootstrap.scala | 16 +- .../scalatra/src/main/scala/ServletApp.scala | 28 +- .../scala/com/wordnik/client/api/PetApi.scala | 507 +- .../com/wordnik/client/api/StoreApi.scala | 189 +- .../com/wordnik/client/api/UserApi.scala | 464 +- .../com/wordnik/client/model/Category.scala | 9 +- .../com/wordnik/client/model/Order.scala | 16 +- .../scala/com/wordnik/client/model/Pet.scala | 19 +- .../scala/com/wordnik/client/model/Tag.scala | 9 +- .../scala/com/wordnik/client/model/User.scala | 21 +- .../scalatra/src/main/webapp/WEB-INF/web.xml | 28 +- samples/server/petstore/spring-mvc/pom.xml | 452 +- .../java/io/swagger/api/ApiException.java | 13 +- .../java/io/swagger/api/ApiOriginFilter.java | 34 +- .../io/swagger/api/ApiResponseMessage.java | 109 +- .../io/swagger/api/NotFoundException.java | 11 +- .../src/main/java/io/swagger/api/PetApi.java | 320 +- .../main/java/io/swagger/api/StoreApi.java | 153 +- .../src/main/java/io/swagger/api/UserApi.java | 296 +- .../swagger/configuration/SwaggerConfig.java | 18 +- .../configuration/SwaggerUiConfiguration.java | 59 +- .../swagger/configuration/WebApplication.java | 6 +- .../main/java/io/swagger/model/Category.java | 84 +- .../src/main/java/io/swagger/model/Order.java | 209 +- .../src/main/java/io/swagger/model/Pet.java | 210 +- .../src/main/java/io/swagger/model/Tag.java | 84 +- .../src/main/java/io/swagger/model/User.java | 260 +- 732 files changed, 62348 insertions(+), 56879 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as delete mode 100644 samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/XMLWriter.as delete mode 100644 samples/client/wordnik/scala/src/main/java/io/swagger/client/api/WordApi.scala 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 @@ private static CodegenConfig forName(String name) { 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 void run() { 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 void run() { } 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 @@ private void setSystemProperties() { /** * 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 @@ private void verbosed(boolean verbose) { 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 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 void run() { /** * 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 File convert(SupportingFile support) { /** * Creates mustache loader for template using classpath loader + * * @param generator - class with reader getter * @return loader for template */ @@ -135,6 +137,7 @@ public Reader getTemplate(String name) { /** * 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; - - public Config() { - this.options = new HashMap(); - } - - 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); - } + private Map options; + + public Config() { + this.options = new HashMap(); + } + + 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); + } } 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 @@ 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) { - - 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()); - } - else{ - System.out.println("omitting non-value node " + optionNode.getKey()); + public static Config read(String 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()); + } else { + System.out.println("omitting non-value node " + optionNode.getKey()); + } + } + } catch (Exception e) { + System.out.println(e.getMessage()); + return null; } - } - } - catch (Exception e) { - System.out.println(e.getMessage()); - return null; + + return config; } - - 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")); - - 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() : ""; + 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; } - catch(Exception e) { - e.printStackTrace(); + + 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); } - 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(); + + private String getCPResourcePath(String name) { + if (!"/".equals(File.separator)) { + return name.replaceAll(Pattern.quote(File.separator), "/"); + } + return name; } - 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; - } } \ 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 swagger(Swagger swagger) { - this.setSwagger(swagger); - return this; - } - public ClientOptInput opts(ClientOpts opts) { - this.setOpts(opts); - 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 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; } - } } - 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")); + + 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")); + } + } } - catch (Exception e) { - // continue - e.printStackTrace(); - } - } - return b.toString(); + this.auths = auths; } - else - return null; - } - public List getAuthorizationValues() { - return auths; - } - public CodegenConfig getConfig() { - return config; - } - public void setConfig(CodegenConfig config) { - this.config = config; - } + public List getAuthorizationValues() { + return auths; + } - public void setOpts(ClientOpts opts) { - this.opts = opts; - } + public CodegenConfig getConfig() { + return config; + } - public ClientOpts getOpts() { - return opts; - } + public void setConfig(CodegenConfig config) { + this.config = config; + } + + public ClientOpts getOpts() { + return opts; + } - public void setSwagger(Swagger swagger) { - this.swagger = swagger; - } + public void setOpts(ClientOpts opts) { + this.opts = opts; + } - @ApiModelProperty(dataType="Object") - public Swagger getSwagger() { - return swagger; - } + @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; - - public String getUri() { - return uri; - } - public void setUri(String uri) { - this.uri = uri; - } - - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - - 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(); - } + 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 getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + 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 @@ */ @Deprecated public class Codegen extends DefaultGenerator { - static Map configs = new HashMap(); - static String configString; - 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(); - } - } + 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"; - 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) { + 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"))); - } - catch (Exception e) { - usage(options); - return; + try { + clientOptInput + .opts(clientOpts) + .swagger(swagger); + new Codegen().opts(clientOptInput).generate(); + } catch (Exception e) { + e.printStackTrace(); + } } - try{ - clientOptInput - .opts(clientOpts) - .swagger(swagger); - new Codegen().opts(clientOptInput).generate(); + + 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; } - catch (Exception e) { - e.printStackTrace(); + + static void usage(Options options) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("Codegen", options); } - } - 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 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); + } + } } - return output; - } - static void usage(Options options) { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp( "Codegen", options ); - } + static { + List extensions = getExtensions(); + StringBuilder sb = new StringBuilder(); - 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); - } + 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); - - Set reservedWords(); - - List supportingFiles(); - - void setOutputDir(String dir); - String getOutputDir(); - - 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); + 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); + + 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 @@ 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 @@ 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.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; - - 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(); + CLIENT, SERVER, DOCUMENTATION, OTHER; + + private static Map names = new HashMap(); + + @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.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); - - 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")); - } - - 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"); + 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(); + + public List cliOptions() { + return cliOptions; + } + + public void processOpts() { + if (additionalProperties.containsKey("templateDir")) { + this.setTemplateDir((String) additionalProperties.get("templateDir")); + } + + 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()); + } } - } - 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; + } + + 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; + } - // 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 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); + + 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; } - 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; - } - - 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); - } - } - - private void addImport(CodegenModel m, String type) { - if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { - m.imports.add(type); - } - } - - 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; - } - } + 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); - } - - // 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; - } - - - 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; - } + 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; + } + + private void addImport(CodegenModel m, String type) { + if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { + m.imports.add(type); + } + } + + 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); + } + + /** + * 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; + } + + 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.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.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!"); - } - if (System.getProperty("debugSwagger") != null) { - Json.prettyPrint(swagger); + return this; } - 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()); - } - } - 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)); - } + + public List generate() { + if (swagger == null || config == null) { + throw new RuntimeException("missing swagger input or config!"); } - } - 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"); - } + 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()); + } + 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()); + } + } + 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; - } + for (String templateName : config.apiTemplateFiles().keySet()) { - 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"); + String filename = config.apiFilename(templateName, tag); + if (new File(filename).exists() && !config.shouldOverwrite(filename)) { + continue; } - }) - .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"); + 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"); + } } - }) - .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(); - } - 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"); - } - else { - mediaType.put("hasMore", null); + files.add(outputFile); + } + } + + config.processSwagger(swagger); + } catch (Exception e) { + e.printStackTrace(); } - c.add(mediaType); - } - operation.put(source, c); - String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); - operation.put(flagFieldName, true); - } - } - - 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 files; } - 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; + 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); } - 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); - } + } + + 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); } - if (!authMethods.isEmpty()) { - co.authMethods = config.fromSecurity(authMethods); + return ops; + } + + public SecuritySchemeDefinition fromSecurity(String name) { + Map map = swagger.getSecurityDefinitions(); + if (map == null) { + return null; } - } + return map.get(name); } - } - - 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)); - } + + + 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); + } + } + } } - 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); + + 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 ]", ""); } - objs.put("operation", ops); - operations.put("operations", objs); - operations.put("package", config.apiPackage()); + 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); - } - } + Set allImports = new LinkedHashSet(); + for (CodegenOperation op : ops) { + allImports.addAll(op.imports); + } - operations.put("imports", imports); - config.postProcessOperations(operations); - if (objs.size() > 0) { - List os = (List) objs.get("operation"); + 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); + } + } - if (os != null && os.size() > 0) { - CodegenOperation op = os.get(os.size() - 1); - op.hasMore = null; - } - } - 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); - } + 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; } - objs.put("imports", imports); - config.postProcessModels(objs); + 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; - } + 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 @@ */ @Deprecated public class MetaGenerator extends AbstractGenerator { - static Map configs = new HashMap(); - static String configString; - 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(); + static Map configs = new HashMap(); + static String configString; + + 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; - } + + 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; } - catch (Exception e) { - usage(options); - return; + + 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); } - 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)); + + 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 ); - } - - public static CodegenConfig getConfig(String name) { - if(configs.containsKey(name)) { - return configs.get(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(); + } } - 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.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 ""; - } + 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"; + } - public Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { - if(processedModels.contains(name)) { - return ""; + 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)); + 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(); - return values; - } + 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 ""; - } + 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 io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; +import io.swagger.models.Xml; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import org.codehaus.plexus.util.StringUtils; import java.text.SimpleDateFormat; -import java.util.*; - -import org.codehaus.plexus.util.StringUtils; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; public class XmlExampleGenerator { - public static String NEWLINE = "\n"; - public static String TAG_START = "<"; - public static String CLOSE_TAG = ">"; - public static String TAG_END = " examples; - protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - private static String EMPTY = ""; - - public XmlExampleGenerator(Map 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); + 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(); + } } - 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); + public String toXml(Property property) { + return toXml(null, property, 0, Collections.emptySet()); } - 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); + + 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; } - sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); - return sb.toString(); - } + 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); - protected String quote(String string) { - return "\"" + string + "\""; - } + return sb.toString(); + } - protected String toXml(String name, Property property, int indent, Collection path) { - if(property == null) { - return ""; + protected String quote(String string) { + return "\"" + string + "\""; } - 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; + + protected String toXml(String name, Property property, int indent, Collection path) { + if (property == null) { + return ""; } - final String asXml = toXml(name, inner, indent + 1, path); - if (StringUtils.isNotEmpty(asXml)) { - sb.append(prefix).append(asXml); + 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)); + } } - if(name != null) { - sb.append(NEWLINE); - sb.append(indent(indent)); - 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"; + } } - } - 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"; + return "not implemented " + property; } - 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 openTag(String name) { + return "<" + name + ">"; + } - protected String closeTag(String name) { - return ""; - } + protected String closeTag(String name) { + return ""; + } - protected String indent(int indent) { - StringBuffer sb = new StringBuffer(); - for(int i = 0; i < indent; i++) { - sb.append(" "); + 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 @@ 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.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; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "akka-scala"; - } - - public String getHelp() { - return "Generates a Scala client library base on Akka/Spray."; - } - - public AkkaScalaClientCodegen() { - super(); - outputFolder = "generated-code/scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "akka-scala"; - apiPackage = mainPackage + ".api"; - modelPackage = mainPackage + ".model"; - - 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") - ); - - 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); - - 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")); - - importMapping.remove("Seq"); - importMapping.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - importMapping.put("DateTime", "org.joda.time.DateTime"); - - 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"); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Int", - "Long", - "Float", - "Object", - "List", - "Seq", - "Map") - ); - instantiationTypes.put("array", "ListBuffer"); - instantiationTypes.put("map", "Map"); - } - - @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; + 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); + + 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"; + + 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") + ); + + 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); + + 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")); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + + 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"); + + 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 CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "akka-scala"; + } + + public String getHelp() { + return "Generates a Scala client library base on Akka/Spray."; + } + + @Override + public String escapeReservedWord(String name) { + return "`" + name + "`"; + } + + @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 { - 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); + } + } + 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(); } - } } - if (!unknownCodes.isEmpty()) { - additionalProperties.put("unknownStatusCodes", unknownCodes); + // Adapt 'hasMore' + it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + security.hasMore = it.hasNext(); + } + + if (codegenSecurities.isEmpty()) { + return null; } - } catch (Exception e) { - LOGGER.error("Unable to find operations List", e); - } + return codegenSecurities; } - 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) + "]"; + + @Override + public String toOperationId(String operationId) { + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); } - 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(); + + 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); } - // Adapt 'hasMore' - it = codegenSecurities.iterator(); - while (it.hasNext()) { - final CodegenSecurity security = it.next(); - security.hasMore = it.hasNext(); + + @Override + public String toParamName(String name) { + return formatIdentifier(name, false); } - if (codegenSecurities.isEmpty()) - return null; - return codegenSecurities; - } - - @Override - public String toOperationId(String operationId) { - return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); - } - - 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 toParamName(String name) { return formatIdentifier(name, false); } - - @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); - } - - @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 String toVarName(String name) { + return formatIdentifier(name, false); } - public abstract String formatFragment(String fragment); - } + @Override + public String toEnumName(CodegenProperty property) { + return formatIdentifier(property.baseName, true); + } - 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(); + 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); } - } - private static class CapitalizeLambda extends CustomLambda { @Override - public String formatFragment(String fragment) { - return StringUtils.capitalize(fragment); + 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 class CamelizeLambda extends CustomLambda { - private final boolean capitalizeFirst; + 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 CamelizeLambda(boolean capitalizeFirst) { - this.capitalizeFirst = capitalizeFirst; + public abstract String formatFragment(String fragment); } - @Override - public String formatFragment(String fragment) { - return camelize(fragment, !capitalizeFirst); + + 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); + 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; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "android"; - } - - public String getHelp() { - return "Generates an Android client library."; - } - - public AndroidClientCodegen() { - super(); - outputFolder = "generated-code/android"; - 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) + ">"; + 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 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.")); } - 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("-", "_"); - - // 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 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")); + + @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); } - else{ - //not set, use default to be passed to template - additionalProperties.put("invokerPackage", invokerPackage); + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); } - - if(additionalProperties.containsKey("groupId")) { - this.setGroupId((String)additionalProperties.get("groupId")); + + @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{ - //not set, use to be passed to template - additionalProperties.put("groupId", groupId); + + @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")); + } + + 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")); } - - if(additionalProperties.containsKey("artifactId")) { - this.setArtifactId((String)additionalProperties.get("artifactId")); + + public Boolean getUseAndroidMavenGradlePlugin() { + return useAndroidMavenGradlePlugin; } - else{ - //not set, use to be passed to template - additionalProperties.put("artifactId", artifactId); + + public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) { + this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin; } - - if(additionalProperties.containsKey("artifactVersion")) { - this.setArtifactVersion((String)additionalProperties.get("artifactVersion")); + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; } - else{ - //not set, use to be passed to template - additionalProperties.put("artifactVersion", artifactVersion); + + public void setGroupId(String groupId) { + this.groupId = groupId; } - - if(additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String)additionalProperties.get("sourceFolder")); + + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; } - if(additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { - this.setUseAndroidMavenGradlePlugin((Boolean)additionalProperties.get("useAndroidMavenGradlePlugin")); + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; } - else{ - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; } - - 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(); - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "async-scala"; - } - - public String getHelp() { - return "Generates an Asynchronous Scala client library."; - } - - public AsyncScalaClientCodegen() { - super(); - outputFolder = "generated-code/async-scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "asyncscala"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - 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") - ); - - 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); - - 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.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - 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) + "]"; + 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 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"; + + 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") + ); + + 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); + + 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.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + 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"); } - 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 toModelName(type); + + public String getName() { + return "async-scala"; + } + + public String getHelp() { + return "Generates an Asynchronous Scala client library."; } - 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 escapeReservedWord(String name) { + return "_" + name; } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } - 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 modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ListBuffer[" + inner + "]() "; + + @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); + } + + @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 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"; - } } \ 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "csharp"; - } - - public String getHelp() { - return "Generates a CSharp client library."; - } - - public CSharpClientCodegen() { - super(); - outputFolder = "generated-code/csharp"; - modelTemplateFiles.put("model.mustache", ".cs"); - apiTemplateFiles.put("api.mustache", ".cs"); - templateDir = "csharp"; - apiPackage = "IO.Swagger.Api"; - modelPackage = "IO.Swagger.Model"; - - 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") - ); - - additionalProperties.put("invokerPackage", invokerPackage); - - 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) + ">"; + 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 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"; + + 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") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + + 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"); + + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "csharp"; + } + + public String getHelp() { + return "Generates a CSharp client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @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); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); } - 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; + + + @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); } - 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "java"; - } - - public String getHelp() { - return "Generates a Java client library."; - } - - public JavaClientCodegen() { - super(); - outputFolder = "generated-code/java"; - 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); - } - - 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")); - } - - - - @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); + 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 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")); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "java"; + } + + public String getHelp() { + return "Generates a Java client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("invokerPackage")) { + this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + } else { + //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")); + } + + + @Override + public String escapeReservedWord(String name) { + return "_" + 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 toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } + @Override + public String toVarName(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, e.g. return - if(reservedWords.contains(name)) - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } + // camelize (lower first character) the variable name + // pet_id => petId + name = camelize(name, true); - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(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 name; } - 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)) + + @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"; - - public CodegenType getTag() { - return CodegenType.SERVER; - } - - public String getName() { - return "jaxrs"; - } - - public String getHelp() { - return "Generates a Java JAXRS Server application."; - } - - public JaxRSServerCodegen() { - super.processOpts(); - - sourceFolder = "src/gen/java"; - - outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" ); - 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); - - - 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) + ">"; + 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 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); + + + 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"; + } + + public String getHelp() { + return "Generates a Java JAXRS Server application."; } - List opList = operations.get(basePath); - if(opList == null) { - opList = new ArrayList(); - operations.put(basePath, opList); + + @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")); + } - 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"; - } + + @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) { + 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; + } - String result = super.apiFilename(templateName, tag); + 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; + } - if( templateName.endsWith( "Impl.mustache")){ - int ix = result.lastIndexOf( '/' ); - result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; + @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"; + } - String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); - if( output != null ){ - result = result.replace( apiFileFolder(), implFileFolder(output)); - } + return result; } - 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); - } + private String implFileFolder(String output) { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); + } - public boolean shouldOverwrite( String filename ){ + public boolean shouldOverwrite(String filename) { - return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java"); - } + return !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); + } } \ 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.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { - protected String apiVersion = "1.0.0"; - protected int serverPort = 8080; - protected String projectName = "swagger-server"; - - public String apiPackage() { - return "controllers"; - } - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.SERVER; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "nodejs"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a nodejs server library using the swagger-tools project. By default, " + - "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; - } - - public NodeJSServerCodegen() { - super(); - - // set the output folder here - outputFolder = "generated-code/nodejs"; + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + + public NodeJSServerCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/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(); + + /** + * 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 + } + } - /** - * 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(); + public String apiPackage() { + return "controllers"; + } /** - * 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 the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType */ - apiTemplateFiles.put( - "controller.mustache", // the template to use - ".js"); // the extension for each file to write + public CodegenType getTag() { + return CodegenType.SERVER; + } /** - * 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. + * 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 */ - templateDir = "nodejs"; + public String getName() { + return "nodejs"; + } /** - * Reserved words. Override this with reserved words specific to your language + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message */ - 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") - ); + 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); + } /** - * Additional Properties. These values can be passed to the templates and - * are available in models, apis, and supporting files + * 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 */ - additionalProperties.put("apiVersion", apiVersion); - additionalProperties.put("serverPort", serverPort); + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } /** - * 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 + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated */ - // 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 apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } - } - - @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(); - } + + @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; } - 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "objc"; - } - - public String getHelp() { - return "Generates an Objective-C client library."; - } - - public ObjcClientCodegen() { - super(); - outputFolder = "generated-code" + File.separator + "objc"; - 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 = ""; - - 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") - ); - - // 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" - )); - - 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"); - - importMapping = new HashMap (); - - 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")); + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected String classPrefix = "SWG"; + protected String projectName = "swaggerClient"; + + 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 = ""; + + 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") + ); + + // 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" + )); + + 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"); + + importMapping = new HashMap(); + + 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")); } - - if(additionalProperties.containsKey("classPrefix")) { - this.setClassPrefix((String)additionalProperties.get("classPrefix")); + + public CodegenType getTag() { + return CodegenType.CLIENT; } - - if(additionalProperties.containsKey("projectName")) { - this.setProjectName((String)additionalProperties.get("projectName")); + + public String getName() { + return "objc"; } - else{ - additionalProperties.put("projectName", projectName); + + public String getHelp() { + return "Generates an Objective-C client library."; } - - 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"); + + @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")); } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array"); + + @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 + "*"; + } } - 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)) + + @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); - - // 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 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 + "*"; - } - } - } - - @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); + + @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 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 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 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 + 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; - } - - @Override - public String toDefaultValue(Property p) { - return null; - } - - @Override - public String apiFileFolder() { - 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"; - } - - 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_]","_"); - - // 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); - - // 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); - } - - 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"); - - return camelize(operationId, true); - } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - - public void setClassPrefix(String classPrefix) { - this.classPrefix = classPrefix; - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } + 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 apiFileFolder() { + 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"; + } + + 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_]", "_"); + + // 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); + + // 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); + } + + 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"); + } + + return camelize(operationId, true); + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + + 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "perl"; - } - - public String getHelp() { - return "Generates a Perl client library."; - } - - public PerlClientCodegen() { - super(); - modelPackage = File.separatorChar + "Object"; - outputFolder = "generated-code" + File.separatorChar + "perl"; - modelTemplateFiles.put("object.mustache", ".pm"); - apiTemplateFiles.put("api.mustache", ".pm"); - templateDir = "perl"; - - typeMapping.clear(); - languageSpecificPrimitives.clear(); - - 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" - ) - ); - - 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) + "]"; - } - 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)) { + protected String invokerPackage = "SwaggerClient"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + 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"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + 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" + ) + ); + + 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")); + } + + 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; - } - - // 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); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // 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); - } + } + + 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); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "php"; - } - - public String getHelp() { - return "Generates a PHP client library."; - } - - public PhpClientCodegen() { - super(); - - invokerPackage = camelize("SwaggerClient"); - - String packagePath = invokerPackage + "-php"; - - modelPackage = packagePath + "/lib/models"; - apiPackage = packagePath + "/lib"; - outputFolder = "generated-code/php"; - modelTemplateFiles.put("model.mustache", ".php"); - apiTemplateFiles.put("api.mustache", ".php"); - templateDir = "php"; - - 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") - ); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - // 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) + "]"; + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public PhpClientCodegen() { + super(); + + invokerPackage = camelize("SwaggerClient"); + + String packagePath = invokerPackage + "-php"; + + modelPackage = packagePath + "/lib/models"; + apiPackage = packagePath + "/lib"; + outputFolder = "generated-code/php"; + modelTemplateFiles.put("model.mustache", ".php"); + apiTemplateFiles.put("api.mustache", ".php"); + templateDir = "php"; + + 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") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + // 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")); } - 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; + } + + public String getName() { + return "php"; + } + + public String getHelp() { + return "Generates a PHP 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); } - 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; - } + + @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); } - 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; + + @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); } - - // 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "python3"; - } - - public String getHelp() { - return "Generates a Python3 client library."; - } - - public Python3ClientCodegen() { - super(); - outputFolder = "generated-code/python3"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python3"; - - apiPackage = module; - modelPackage = module + ".models"; - - 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) + "]"; - } - 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)) { + String module = "client"; + + public Python3ClientCodegen() { + super(); + outputFolder = "generated-code/python3"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python3"; + + apiPackage = module; + modelPackage = module + ".models"; + + 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")); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "python3"; + } + + public String getHelp() { + return "Generates a Python3 client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @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"; - } - - @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(); - - // 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); - - 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) { - // 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); - } - - @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"; - } - - @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 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); - } + } + + 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("-", "_"); + + // 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); + + // 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) { + // 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); + } + + @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"; + } + + @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 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/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; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "python"; - } - - public String getHelp() { - return "Generates a Python client library."; - } - - public PythonClientCodegen() { - super(); - - eggPackage = module + "-python"; - - invokerPackage = eggPackage + File.separatorChar + module; - - outputFolder = "generated-code" + File.separatorChar + "python"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python"; - - apiPackage = invokerPackage + File.separatorChar + "apis"; - modelPackage = invokerPackage + File.separatorChar + "models"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - 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")); - - 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) + "]"; - } - 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)) { + protected String module = "SwaggerPetstore"; + protected String invokerPackage; + protected String eggPackage; + + public PythonClientCodegen() { + super(); + + eggPackage = module + "-python"; + + invokerPackage = eggPackage + File.separatorChar + module; + + outputFolder = "generated-code" + File.separatorChar + "python"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python"; + + apiPackage = invokerPackage + File.separatorChar + "apis"; + modelPackage = invokerPackage + File.separatorChar + "models"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + 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")); + + 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")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "python"; + } + + public String getHelp() { + return "Generates a Python client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @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"; - } - - @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(); - - // 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); - - 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 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) { - // 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)); - } - - @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"; - } - - @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 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); - } + } + + 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("-", "_"); + + // 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)); + + // 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) { + // 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)); + } + + @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"; + } + + @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 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/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(); - - // 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(); - - /** - * Configures the type of generator. - * - * @return the CodegenType for this generator - * @see io.swagger.codegen.CodegenType - */ - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - /** - * Configures a friendly name for the generator. This will be used by the generator - * to select the library with the -l flag. - * - * @return the friendly name for the generator - */ - public String getName() { - return "qt5cpp"; - } - - /** - * Returns human-friendly help for the generator. Provide the consumer with help - * tips, parameters here - * - * @return A string value for the help message - */ - public String getHelp() { - return "Generates a qt5 C++ client library."; - } - - public Qt5CPPGenerator() { - super(); - - // set the output folder here - outputFolder = "generated-code/qt5cpp"; + 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(); + + public Qt5CPPGenerator() { + super(); + + // set the output folder here + outputFolder = "generated-code/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"); + + modelTemplateFiles.put( + "model-body.mustache", + ".cpp"); + + /** + * 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 + + 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 + ">"; - } - 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) + ">*"; - } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "*"; + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); } - 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()"; + + @Override + public String toApiFilename(String name) { + return PREFIX + initialCaps(name) + "Api"; } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - if(!languageSpecificPrimitives.contains(inner)) { - inner += "*"; - } - return "new QList<" + inner + ">()"; + + /** + * 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 RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + + @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"; } - 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; - } - 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) || + 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 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "retrofit"; - } - - public String getHelp() { - return "Generates a Retrofit client library."; - } - - public RetrofitClientCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "retrofit"; - 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") - ); - - 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) + ">"; + 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 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"; + + 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"); } - 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)) - return toModelName(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); } - 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 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); + } + + @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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "ruby"; - } - - public String getHelp() { - return "Generates a Ruby client library."; - } - - /** - * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". - */ - public String generateModuleName() { - return camelize(gemName.replaceAll("[^\\w]+", "_")); - } - - public RubyClientCodegen() { - super(); - moduleName = generateModuleName(); - modelPackage = gemName + "/models"; - apiPackage = gemName + "/api"; - outputFolder = "generated-code" + File.separatorChar + "ruby"; - modelTemplateFiles.put("model.mustache", ".rb"); - apiTemplateFiles.put("api.mustache", ".rb"); - templateDir = "ruby"; - - typeMapping.clear(); - languageSpecificPrimitives.clear(); - - 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) + "]"; - } - 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)) { + protected String gemName = "swagger_client"; + protected String moduleName = null; + protected String libFolder = "lib"; + + 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"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + 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")); + } + + 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"; - } - - @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(); - - // 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); - - 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) { - // 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); - } - - @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"; - } - - @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); - } - - @Override - public String toModelImport(String name) { - return modelPackage() + "/" + toModelFilename(name); - } - - @Override - public String toApiImport(String name) { - return apiPackage() + "/" + toApiFilename(name); - } + } + + public String toDefaultValue(Property p) { + return "null"; + } + + @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(); + } + + // 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); + } + + 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) { + // 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); + } + + @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"; + } + + @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); + } + + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(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(); - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "scala"; - } - - public String getHelp() { - return "Generates a Scala client library."; - } - - public ScalaClientCodegen() { - super(); - outputFolder = "generated-code/scala"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scala"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - 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") - ); - - 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); - - 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.remove("List"); - importMapping.remove("Set"); - importMapping.remove("Map"); - - 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) + "]"; + 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 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"; + + 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") + ); + + 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); + + 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.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + 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"); } - 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 toModelName(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); } - 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 + "]"; + + 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); } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return instantiationTypes.get("array") + "[" + inner + "]"; + + @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 - 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 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 "new ListBuffer[" + 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"; - } - @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); + } } 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"; - - public CodegenType getTag() { - return CodegenType.SERVER; - } - - public String getName() { - return "scalatra"; - } - - public String getHelp() { - return "Generates a Scala server application with Scalatra."; - } - - public ScalatraServerCodegen() { - super(); - outputFolder = "generated-code/scalatra"; - modelTemplateFiles.put("model.mustache", ".scala"); - apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scalatra"; - apiPackage = "com.wordnik.client.api"; - modelPackage = "com.wordnik.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") - ); - - defaultIncludes = new HashSet( - Arrays.asList("double", - "Int", - "Long", - "Float", - "Double", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "List", - "Set", - "Map") - ); - - typeMapping.put("integer", "Int"); - typeMapping.put("long", "Long"); - - 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(); + 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 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"; + + 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") + ); + + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + + 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"); } - return objs; - } + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "scalatra"; + } + + public String getHelp() { + return "Generates a Scala server application with Scalatra."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } - @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 apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().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)) + + @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 SpringMVCServerCodegen() { 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 void processOpts() { @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 @@ else if (p instanceof MapProperty) { @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 void addOperationToGroup(String tag, String resourcePath, Operation opera } 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(); + } - languageSpecificPrimitives = new HashSet(); - importMapping = new HashMap (); - } + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } - @Override - public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + public String getName() { + return "html"; } - else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + public String getHelp() { + return "Generates a static HTML file."; } - 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(); + @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); } - 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); + @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; } - 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 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 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); + public SwaggerGenerator() { + super(); + templateDir = "swagger"; + outputFolder = "generated-code/swagger"; + + 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 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); + public SwaggerYamlGenerator() { + super(); + templateDir = "swagger"; + outputFolder = "generated-code/swagger"; + + 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 @@ 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"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "swift"; - } - - public String getHelp() { - return "Generates a swift client library."; - } - - public SwiftGenerator() { - super(); - outputFolder = "generated-code/swift"; - modelTemplateFiles.put("model.mustache", ".swift"); - apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; - - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected String sourceFolder = "Classes/Swaggers"; + + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; + + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); + + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); + } + + sourceFolder = appName + "/" + sourceFolder; + + 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")); + + 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(); + } + + private static String normalizePath(String path) { + StringBuilder builder = new StringBuilder(); + + int cursor = 0; + Matcher matcher = PATH_PARAM_PATTERN.matcher(path); + boolean found = matcher.find(); + while (found) { + String stringBeforeMatch = path.substring(cursor, matcher.start()); + builder.append(stringBeforeMatch); + + String group = matcher.group().substring(1, matcher.group().length() - 1); + group = camelize(group, true); + builder + .append("{") + .append(group) + .append("}"); + + cursor = matcher.end(); + found = matcher.find(); + } + + String stringAfterMatch = path.substring(cursor); + builder.append(stringAfterMatch); + + return builder.toString(); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "swift"; + } + + public String getHelp() { + return "Generates a swift client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); } - additionalProperties.put("projectName", appName); - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); } - sourceFolder = appName + "/" + sourceFolder; - - 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")); - - 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(); - } - - @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) + "]"; + @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); } - 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)) + + @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()); + + @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; } - 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(); + + @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; } - String stringAfterMatch = path.substring(cursor); - builder.append(stringAfterMatch); + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultAPI"; + } + return initialCaps(name) + "API"; + } - return builder.toString(); - } + @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(); - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "tizen"; - } - - public String getHelp() { - return "Generates a Samsung Tizen C++ client library."; - } - - public TizenClientCodegen() { - super(); - outputFolder = "generated-code/tizen"; - 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 = ""; - - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "int", - "long") - ); - languageSpecificPrimitives = new HashSet(); - - additionalProperties().put("prefix", PREFIX); - - 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" - )); - - super.typeMapping = 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"); - - 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"); + protected static String PREFIX = "Sami"; + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected Map namespaces = new HashMap(); + + 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 = ""; + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long") + ); + languageSpecificPrimitives = new HashSet(); + + additionalProperties().put("prefix", PREFIX); + + 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" + )); + + super.typeMapping = 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"); + + 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")); } - 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 + "*"; - } - - @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 getName() { + return "tizen"; + } + + public String getHelp() { + return "Generates a Samsung Tizen C++ client library."; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map"); + } else if (p instanceof ArrayProperty) { + 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 + "*"; + } + } + + @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) + ";"; + } + 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()"; + } 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"; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; } - else { - return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; } - } - @Override - public String toModelImport(String name) { - if(namespaces.containsKey(name)) { - return "using " + namespaces.get(name) + ";"; + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); } - 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 toApiName(String name) { + return PREFIX + initialCaps(name) + "Api"; } - else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ArrayList()"; + + public String toApiFilename(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; } - // else - if(p instanceof RefProperty) { - RefProperty rp = (RefProperty) p; - return "new " + toModelName(rp.getSimpleRef()) + "()"; + + 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); } - return "null"; - } - - @Override - public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder; - } - - @Override - public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder; - } - - @Override - public String toModelFilename(String name) { - return PREFIX + initialCaps(name); - } - - @Override - public String toApiName(String name) { - return PREFIX + initialCaps(name) + "Api"; - } - - public String toApiFilename(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 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); - } } 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 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 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 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}} + {{#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}} + {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) + queryParams.put("{{paramName}}", String.valueOf({{paramName}})) + {{/queryParams}} - {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}) - {{/headerParams}} + {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}) + {{/headerParams}} - invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, - "{{httpMethod}}", "{{returnContainer}}", - {{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}}) + invokeApi(onSuccess, onFailure, basePath, versionPath, resourcePath, queryParams, headerParams, + "{{httpMethod}}", "{{returnContainer}}", + {{#returnBaseType}}{{{returnBaseType}}}.class {{/returnBaseType}}{{^returnBaseType}}null {{/returnBaseType}}) - } - {{/operation}} -} + } + {{/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 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"); + +// Use UTC as the default time zone. +this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + +// Set default User-Agent. +setUserAgent("Java-Swagger"); + +// 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); +} - private Map authentications; +public String getBasePath() { +return basePath; +} - private DateFormat dateFormat; +public ApiClient setBasePath(String basePath) { +this.basePath = basePath; +return this; +} - 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"); +/** +* Get authentications (key: authentication name, value: authentication). +*/ +public Map + getAuthentications() { +return authentications; +} - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); +/** +* 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); +} - // Set default User-Agent. - setUserAgent("Java-Swagger"); +/** +* 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!"); +} - // 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); - } +/** +* 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; - } +/** +* 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; - } +/** +* 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()); - } +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; - } +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; - } +/** +* 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 ""; +/** +* 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(); - } +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}}; - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); - {{/queryParams}} - - {{#headerParams}}if ({{paramName}} != null) - headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); - {{/headerParams}} - - final String[] accepts = { - {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - 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) + + {{#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}}; + + // query params + Map + queryParams = new HashMap + (); + Map + headerParams = new HashMap + (); + Map + formParams = new HashMap + (); + + {{#queryParams}}if ({{paramName}} != null) + queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/queryParams}} + + {{#headerParams}}if ({{paramName}} != null) + headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/headerParams}} + + final String[] accepts = { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + 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 int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return 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 String getMessage() { + return message; + } + + /** + * Get the HTTP response headers. + */ + public Map + > getResponseHeaders() { + return responseHeaders; + } + + /** + * 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 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); - } - } +private final String location; +private final String paramName; + +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); +} +} } 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; - - 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); - } - } +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); +} +} } 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 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 String getType() { +return type; +} - public void setType(String type) { - this.type = type; - } +public void setType(String type) { +this.type = type; +} - public String getMessage() { - return message; - } +public String getMessage() { +return message; +} - public void setMessage(String message) { - this.message = 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}} { - - 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}} }) - - 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 class {{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}} }) + + 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}} - - @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}} -} + 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); + } + + {{/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 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 String getType() { +return type; +} - public void setType(String type) { - this.type = type; - } +public void setType(String type) { +this.type = type; +} - public String getMessage() { - return message; - } +public String getMessage() { +return message; +} - public void setMessage(String message) { - this.message = 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[] 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[] 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); - } - } +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[] 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"; +} +} + +@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[] getRootConfigClasses() { +return new Class[] { SwaggerConfig.class }; +} - @Override - protected Class[] getServletConfigClasses() { - return new Class[] { WebMvcConfiguration.class }; - } +@Override +protected Class[] getServletConfigClasses() { +return new Class[] { WebMvcConfiguration.class }; +} - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } +@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) - - 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: 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]) { - - 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 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) - } - - case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { - case JString(s) => - ISODateTimeFormat.dateTimeParser().parseDateTime(s) - }, { - case d: DateTime => - JString(ISODateTimeFormat.dateTimeParser().print(d)) - })) +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) + +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) +} +} + +/** +* 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(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] + + } + +/** +* 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)) +})) } class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { - import io.swagger.client.core.ApiInvoker._ - import io.swagger.client.core.ParametersMap._ - - implicit val ec = system.dispatcher - implicit val jsonFormats = formats - - def settings = ApiSettings(system) - - import spray.http.MessagePredicate._ - - val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && - Encoder.DefaultFilter && - minEntitySize(settings.compressionSizeThreshold) - - 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 addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => - - val rawHeaders = for { - (name, value) <- headers.asFormattedParams - header = RawHeader(name, String.valueOf(value)) - } yield header - - 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 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 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) - } - - 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 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) - } - - def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { - try { - implicit val timeout: Timeout = settings.connectionTimeout - - 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 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) - } - } - - 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, 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 _ => 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] - } +import io.swagger.client.core.ApiInvoker._ +import io.swagger.client.core.ParametersMap._ + +implicit val ec = system.dispatcher +implicit val jsonFormats = formats +def settings = ApiSettings(system) + +import spray.http.MessagePredicate._ + +val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && +Encoder.DefaultFilter && +minEntitySize(settings.compressionSizeThreshold) + +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 } -sealed trait CustomContentTypes { +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 + +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 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 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) +} + +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 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) +} + +def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { +try { +implicit val timeout: Timeout = settings.connectionTimeout + +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 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) +} +} + +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, 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 _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) +} +} - def normalizedContentType(original: String): ContentType = - MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) +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 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 CustomContentTypes { + +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}'") +} +} } sealed trait UntrustedSslContext { - this: ApiInvoker => - - 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 = {} - - 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 - } +this: ApiInvoker => + +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 = {} + +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 +} } 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) - - 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")) - } +def this(system: ExtendedActorSystem) = this(system.settings.config) + +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")) +} } 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]) { - - def asFormattedParamsList = m.toList.flatMap(formattedParams) - - def asFormattedParams = m.flatMap(formattedParams) - - 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(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)) - } - - } +/** +* 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 asFormattedParams = m.flatMap(formattedParams) + +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(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 HttpClient client = null; - - private boolean ignoreSSLCertificates = false; - - 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); - - /** - * 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"); - - 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. - } - } +private static ApiInvoker INSTANCE = new ApiInvoker(); +private Map + defaultHeaderMap = new HashMap +(); + +private HttpClient client = null; + +private boolean ignoreSSLCertificates = false; + +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); + +/** +* 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"); + +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. +} +} } 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)) - } - } + 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}} + {{/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"; - - /** - * 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}}"; - } - - /** - * 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(); - - // 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 - - /** - * 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}}"; - - /** - * 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"; - - /** - * Reserved words. Override this with reserved words specific to your language - */ - reservedWords = new HashSet ( - Arrays.asList( - "sample1", // replace with static values - "sample2") +// 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 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."; +} + +public {{generatorClass}}() { +super(); + +// 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 + +/** +* 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}}"; + +/** +* 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"; + +/** +* 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 - } - - /** - * 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); - } - - /** - * 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)) + ); + } + + /** + * 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); + } + + /** + * 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)) + return toModelName(type); + } + else + type = swaggerType; return toModelName(type); - } - else - type = swaggerType; - return toModelName(type); - } -} \ No newline at end of file + } + } \ 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 { - - /// - /// Initializes a new instance of the class. - /// - /// The base path. - public ApiClient(String basePath="{{basePath}}") { - this.basePath = basePath; - this.restClient = new RestClient(this.basePath); - } +/// + + /// 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); +} - /// +/// + /// 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; } - - 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; - } + /// + +/// +The RestClient. +public RestClient restClient { get; set; } + +private Dictionary + defaultHeaderMap = new Dictionary +(); - public async Task CallApiAsync(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, - Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { +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; +} - var request = new RestRequest(Path, Method); +public async Task + CallApiAsync(String Path, RestSharp.Method Method, Dictionary + QueryParams, String PostBody, + Dictionary + HeaderParams, Dictionary + FormParams, Dictionary + FileParams, String[] AuthSettings) { - UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); + var request = new RestRequest(Path, Method); - // add default header, if any - foreach(KeyValuePair defaultHeader in this.defaultHeaderMap) - request.AddHeader(defaultHeader.Key, defaultHeader.Value); + UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); - // 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 default header, if any + foreach(KeyValuePair + defaultHeader in this.defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); - // add form parameter, if any - foreach(KeyValuePair param in FormParams) - request.AddParameter(param.Key, param.Value); + // add header parameter, if any + foreach(KeyValuePair + param in HeaderParams) + request.AddHeader(param.Key, param.Value); - // add file parameter, if any - foreach(KeyValuePair param in FileParams) - request.AddFile(param.Key, param.Value); + // add query parameter, if any + foreach(KeyValuePair + param in QueryParams) + request.AddQueryParameter(param.Key, param.Value); - if (PostBody != null) { - request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter - } + // add form parameter, if any + foreach(KeyValuePair + param in FormParams) + request.AddParameter(param.Key, param.Value); - return (Object) await restClient.ExecuteTaskAsync(request); + // 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 } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// + return (Object) await restClient.ExecuteTaskAsync(request); + + } + + /// + + /// 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; - - try - { - return JsonConvert.DeserializeObject(content, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - } + /// + + /// 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; - /// - /// 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); - } - } + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException 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; - } - } + /// + + /// 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); + } + } - /// - /// 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: + /// + + /// 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: //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}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#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}}); {{/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) - /// + } + + /// + + /// 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; - } + if (apiClient == null) { // use the default one in Configuration + this.apiClient = Configuration.apiClient; + } else { + this.apiClient = apiClient; + } } - /// - /// Initializes a new instance of the class. - /// - /// + /// + + /// 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}}) { - - {{#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 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}} - - // 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); - - if (((int)response.StatusCode) >= 400) { + /// + + /// {{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}} + + 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; + + {{#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}} }; + + // make the HTTP request + IRestResponse response = (IRestResponse) apiClient.CallApi(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}}}) 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}}) { - - {{#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 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}} - - // 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) { + } + {{#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}}) { + + {{#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 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}} + + // 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 { + private static const API_ERROR_MSG:String = "Api error response: "; + + 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) { + errorCode = String(errorCodeArray[0]); + } + 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 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; - 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) - 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){ - errorCode = String(errorCodeArray[0]); - } - 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 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}} - - {{#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}}}; - - {{/vars}} + {{#model}} + [XmlRootNode(name="{{classname}}")] + public class {{classname}} { + {{#vars}} + + {{#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}}}; + + {{/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}}
- -

Parameters

-
- {{#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}} - - + + +

{{{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}}
+ +

Parameters

+ +
+ {{#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}} - -@interface {{classname}} () + #import "{{classname}}.h" + #import "SWGFile.h" + #import "SWGQueryParamCollection.h" + {{#imports}}#import "{{import}}.h" + {{/imports}} + {{newline}} + + @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}} - - 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}} - - {{#requiredParamCount}} - {{#requiredParams}} - if({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} - - {{#returnContainer}} - // response is in a container - {{>apiBodyResponseWithContainer}}{{/returnContainer}} - - {{#returnSimpleType}} - // non container response - - {{#returnTypeIsPrimitive}} - // primitive response - {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} - - {{#returnBaseType}} - // complex response - {{>apiNonPrimitiveResponse}}{{/returnBaseType}} - {{/returnSimpleType}} - - {{^returnSimpleType}}{{^returnContainer}} - // it's void - {{>voidResponse}} - {{/returnContainer}}{{/returnSimpleType}} -} + options: NSJSONReadingMutableContainers + error: &error]; + bodyDictionary = JSON; + } + {{/bodyParam}} + {{^bodyParam}} + + 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}} + + {{#requiredParamCount}} + {{#requiredParams}} + if({{paramName}} == nil) { + // error + } + {{/requiredParams}} + {{/requiredParamCount}} + + {{#returnContainer}} + // response is in a container + {{>apiBodyResponseWithContainer}}{{/returnContainer}} + + {{#returnSimpleType}} + // non container response + + {{#returnTypeIsPrimitive}} + // primitive response + {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} + + {{#returnBaseType}} + // complex response + {{>apiNonPrimitiveResponse}}{{/returnBaseType}} + {{/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 - -@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}} -/** - - {{{summary}}} - {{#notes}}{{{notes}}}{{/notes}} - - {{#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}} - -{{newline}} -{{/operation}} + @interface {{classname}}: NSObject + + @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}} + /** + + {{{summary}}} + {{#notes}}{{{notes}}}{{/notes}} + + {{#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}} + + {{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}}', - @_ - ); - - return bless \%args, $class; +my $class = shift; +my (%args) = ( +'ua' => LWP::UserAgent->new, +'base_url' => '{{basePath}}', +@_ +); + +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) = @_; - - # update parameters based on authentication settings - $self->update_params_for_auth($header_params, $query_params, $auth_settings); - - - my $_url = $self->{base_url} . $resource_path; - - # 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; - - # 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); - - } - elsif ($method eq 'PUT') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = PUT($_url, %$header_params, Content => $_body_data); - - } - 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; +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); + + +my $_url = $self->{base_url} . $resource_path; + +# 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; + +# 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); + +} +elsif ($method eq 'PUT') { +# multipart +$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? +'form-data' : $header_params->{'Content-Type'}; + +$_request = PUT($_url, %$header_params, Content => $_body_data); + +} +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; - - 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); - } - - return $_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 + +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; } @@ -232,15 +232,15 @@ sub deserialize # @return String Accept (e.g. application/json) sub select_header_accept { - 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); - } +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); +} } @@ -249,15 +249,15 @@ sub select_header_accept # @return String Content-Type (e.g. application/json) sub select_header_content_type { - 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); - } +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); +} } @@ -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) = @_; - - 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 - } - } +my ($self, $header_params, $query_params, $auth_settings) = @_; + +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 +} +} } 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); - } - } +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; +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) = @_; - - {{#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 - - 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) { + # + # {{{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}} + + # 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 = {}; + + # '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; - } - 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}} + {{/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}}; - -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"; - -# -#{{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 = { + {{#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; + + 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. + # + + 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}}, + '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, {{/hasMore}}{{/vars}} - }; + }; - return bless $self, $class; -} + return bless $self, $class; + } -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} + # get swagger type of the attribute + sub get_swagger_types { + return $swagger_types; + } -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} + # get attribute mappping + sub get_attribute_map { + return $attribute_map; + } -1; -{{/model}} + 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.'); + +$this->user_agent= $user_agent; +} - /** - * 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.'); +/** +* get the user agent of the api client +* +* @return string user agent +*/ +public function getUserAgent($user_agent) { +return $this->user_agent; +} - $this->user_agent= $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.'); + +$this->curl_timeout = $seconds; +} - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } +/** +* get the HTTP timeout value +* +* @return string HTTP timeout value +*/ +public function getTimeout() { +return $this->curl_timeout; +} - /** - * 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; - } +/** +* 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 the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } +/** +* 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) { + +$headers = array(); + +# determine authentication setting +$this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + +# construct the http header +$headerParams = array_merge((array)self::$default_header, (array)$headerParams); + +foreach ($headerParams as $key => $val) { +$headers[] = "$key: $val"; +} - /** - * 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; - } - } +// 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)); +} - /** - * 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) { - - $headers = array(); - - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - - # construct the http header - $headerParams = array_merge((array)self::$default_header, (array)$headerParams); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { - $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)); - } - - $url = $this->host . $resourcePath; - - $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); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - 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); - - // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - - // 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); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); - } else { - curl_setopt($curl, CURLOPT_VERBOSE, 0); - } - - // obtain the HTTP response headers - curl_setopt($curl, CURLOPT_HEADER, 1); - - // Make the request - $response = curl_exec($curl); - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // 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); - } - - // 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; - } +$url = $this->host . $resourcePath; - /** - * 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; - } - - return $sanitized; - } +$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); - /** - * 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)); - } +curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - /** - * 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); - } - } +if (! empty($queryParams)) { +$url = ($url . '?' . http_build_query($queryParams)); +} - /** - * 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); - } +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); - /** - * 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); - } +// Set user agent +curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - /** - * 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; - } - } +// 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); - /** - * 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 $deserialized; - } +curl_setopt($curl, CURLOPT_VERBOSE, 1); +curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); +} else { +curl_setopt($curl, CURLOPT_VERBOSE, 0); +} - /* - * 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); - } - } +// obtain the HTTP response headers +curl_setopt($curl, CURLOPT_HEADER, 1); - /* - * 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); - } - } +// 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); + +// 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); +} + +// 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; +} + +/** +* 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; +} + +return $sanitized; +} + +/** +* 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 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 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 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 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; +} +} + +/** +* 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 $deserialized; +} + +/* +* 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 - - :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'] - - @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 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) - - # 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)} - - # 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) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # 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) - - # 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 - - :param obj: object or string value - - :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. - - 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. - - :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] - - 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) - - 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)) - - return instance - - 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 - - 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 = {} - - 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]) - - return params - - 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)) - - 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' - - content_types = list(map(lambda x: x.lower(), content_types)) - - 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`') +""" +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' + +@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 + +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): + +# 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) + +# 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) + +# auth setting +self.update_params_for_auth(header_params, query_params, auth_settings) + +# body +if body: +body = self.sanitize_for_serialization(body) + +# 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) + +# 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 + +:param obj: object or string value + +: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. + +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. + +: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] + +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) + +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)) + +return instance + +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 + +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 = {} + +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]) + +return params + +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)) + +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' + +content_types = list(map(lambda x: x.lower(), content_types)) + +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`') 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 - ) - - # 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 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.") - - post_params = post_params or {} - headers = headers or {} - - 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) - - if r.status not in range(200, 206): - raise ApiException(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 - - return resp - - 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 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 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 __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() +) + +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'] + +if post_params and body: +raise ValueError("body parameter cannot be used with post_params parameter.") + +post_params = post_params or {} +headers = headers or {} + +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) + +if r.status not in range(200, 206): +raise ApiException(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 + +return resp + +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 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 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) class ApiException(Exception): - """ - 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() - - # 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 - - 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) +""" +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() + +# 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 + +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. - """ - - IMPL = RESTClientObject() - - @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 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 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 DELETE(cls, *n, **kw): - """ - Perform a DELETE request using `RESTClient.request()` - """ - return cls.IMPL.DELETE(*n, **kw) +""" +A class with all class methods to perform JSON requests. +""" + +IMPL = RESTClientObject() + +@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 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 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 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 - -REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] - -setup( + # 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"] + + 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""" - - 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): - - 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 - - if self.cookie: - headers['Cookie'] = self.cookie - - 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 method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - if data: - data = data.encode('utf-8') - - 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) - - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None - - 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 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'} - - 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) - - 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 '')) - - # 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 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""" - - # 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]: - return objClass(obj) - elif objClass == datetime: - return self._parseDatetime(obj) - - instance = objClass() - - 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)) - - return instance +"""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 callAPI(self, resourcePath, method, queryParams, postData, +headerParams=None): + +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 + +if self.cookie: +headers['Cookie'] = self.cookie + +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 method in ['GET']: + +#Options to add statements later on and for compatibility +pass + +elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: + +if postData: +headers['Content-type'] = 'application/json' +data = self.sanitizeForSerialization(postData) +data = json.dumps(data) + +else: +raise Exception('Method ' + method + ' is not recognized.') + +if data: +data = data.encode('utf-8') + +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) + +try: +data = json.loads(response) +except ValueError: # PUT requests don't return anything +data = None + +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 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'} + +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) + +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 '')) + +# 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 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""" + +# 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]: +return objClass(obj) +elif objClass == datetime: +return self._parseDatetime(obj) + +instance = objClass() + +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)) + +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 - -namespace Swagger { -{{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)); - } - } - 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)); +#include + + #include + + + namespace Swagger { + {{classname}}::{{classname}}() {} + + {{classname}}::~{{classname}}() {} + + {{classname}}::{{classname}}(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; } - } - } - - {{/collectionFormat}} - {{/queryParams}} - - HttpRequestWorker *worker = new HttpRequestWorker(); - HttpRequestInput input(fullPath, "{{httpMethod}}"); - - {{#formParams}}{{^isFile}} - if({{paramName}} != NULL) { - input.add_var("{{paramName}}", *{{paramName}}); - } - {{/isFile}}{{/formParams}} - - {{#bodyParams}} - {{#isContainer}} - QJsonArray* {{paramName}}Array = new QJsonArray(); - toJsonArray((QList*){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*")); - - QJsonDocument doc(*{{paramName}}Array); - QByteArray bytes = doc.toJson(); - - input.request_body.append(bytes); - {{/isContainer}} - {{^isContainer}} - QString output = {{paramName}}.asJson(); - input.request_body.append(output); - {{/isContainer}}{{/bodyParams}} - - {{#headerParams}} - // TODO: add header support - {{/headerParams}} - - connect(worker, - &HttpRequestWorker::on_execution_finished, - this, - &{{classname}}::{{nickname}}Callback); - - worker->execute(&input); -} - -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}} - - worker->deleteLater(); - - {{#returnType}}emit {{nickname}}Signal(output);{{/returnType}} - {{^returnType}}emit {{nickname}}Signal();{{/returnType}} -} -{{/operation}} -{{/operations}} -} /* namespace Swagger */ + + {{#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)); + } + } + 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}} + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "{{httpMethod}}"); + + {{#formParams}}{{^isFile}} + if({{paramName}} != NULL) { + input.add_var("{{paramName}}", *{{paramName}}); + } + {{/isFile}}{{/formParams}} + + {{#bodyParams}} + {{#isContainer}} + QJsonArray* {{paramName}}Array = new QJsonArray(); + toJsonArray((QList + *){{paramName}}, {{paramName}}Array, QString("body"), QString("SWGUser*")); + + QJsonDocument doc(*{{paramName}}Array); + QByteArray bytes = doc.toJson(); + + input.request_body.append(bytes); + {{/isContainer}} + {{^isContainer}} + QString output = {{paramName}}.asJson(); + input.request_body.append(output); + {{/isContainer}}{{/bodyParams}} + + {{#headerParams}} + // TODO: add header support + {{/headerParams}} + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &{{classname}}::{{nickname}}Callback); + + worker->execute(&input); + } + + 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}} + + worker->deleteLater(); + + {{#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); - } - } - } - QList **val = static_cast**>(value); - delete *val; - *val = output; - } -} + // 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; + } + } -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)); - } - } - } - } - 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)); - } -} + 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)); + } + } -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() { + void + {{classname}}::cleanup() { {{#vars}}{{#complexType}}if({{name}} != NULL) { - {{#isContainer}}QList<{{complexType}}*>* arr = {{name}}; + {{#isContainer}}QList<{{complexType}}*>* arr = {{name}}; foreach({{complexType}}* o, *arr) { - delete o; + delete o; } - {{/isContainer}}delete {{name}}; - }{{/complexType}} + {{/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; -} - -void -{{classname}}::fromJsonObject(QJsonObject &pJson) { + } + + {{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) { {{#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); -} - -QJsonObject* -{{classname}}::asJsonObject() { - QJsonObject* obj = new QJsonObject(); + } + + QString + {{classname}}::asJson () + { + QJsonObject* obj = this->asJsonObject(); + + 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}}"); - - obj->insert("{{name}}", {{name}}JsonArray); - {{/isContainer}} + {{^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}} {{/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}} - - # 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}} - - # 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 '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}} - - # 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}} + {{#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}} + + # 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 = {} + + # 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}} + + # 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}} + + 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 +# 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 +# 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 +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 +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 +# 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 +# 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 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}} - } - end +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 +# attribute type +def self.swagger_types +{ +{{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} +{{/vars}} +} +end - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? +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} +# 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}} +{{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} 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 - - # 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 - - # 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)) - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # 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 +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 + +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? + +# Configure logger. Default to use Rails +self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + +# remove :// from scheme +configuration.scheme.sub!(/:\/\//, '') + +# 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 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' - - 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] ||= {} - - # 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] || {}) - - # 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 +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 + +# 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 +} + +# 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 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 +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 +def code +raw.code +end - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - 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 +# 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 +# `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 +# 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 json? +format == 'json' +end - def xml? - format == 'xml' - 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_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 +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 - - 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}})) - - {{/pathParams}} - - 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] - - {{#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}} - - var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} - - 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 { + 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 + + {{#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}} + + 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] + + {{#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}} + + var postBody: AnyRef = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}} + + 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) { - - var defaultHeaders: HashMap[String, String] = httpHeaders - - 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 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 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 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 - - 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() - } +httpHeaders: HashMap[String, String] = HashMap(), +hostMap: HashMap[String, Client] = HashMap(), +asyncHttpClient: Boolean = false, +authScheme: String = "", +authPreemptive: Boolean = false) { + +var defaultHeaders: HashMap[String, String] = httpHeaders + +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 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 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 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 + +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,16 +1,6 @@ -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 "/" - } +object JettyMain { def main(args: Array[String]) = { val server: Server = new Server @@ -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() - } - } - else - List() - {{/collectionFormat}} - {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} - - {{/isQueryParam}} + {{#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}} + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} - {{#isFormParam}} - val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") - {{/isFormParam}} + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} - {{#isBodyParam}} - val {{paramName}} = parsedBody.extract[{{dataType}}] - {{/isBodyParam}} - {{/isFile}} - println("{{paramName}}: " + {{paramName}}) - {{/allParams}} - } + {{#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) + $parent = $(selector) - e && e.preventDefault() + e && e.preventDefault() - $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) + $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) - $parent.trigger(e = $.Event('close')) + $parent.trigger(e = $.Event('close')) - if (e.isDefaultPrevented()) return + if (e.isDefaultPrevented()) return - $parent.removeClass('in') + $parent.removeClass('in') - function removeElement() { - $parent - .trigger('closed') - .remove() - } + function removeElement() { + $parent + .trigger('closed') + .remove() + } - $.support.transition && $parent.hasClass('fade') ? - $parent.on($.support.transition.end, removeElement) : - removeElement() - } + $.support.transition && $parent.hasClass('fade') ? + $parent.on($.support.transition.end, removeElement) : + removeElement() + } - /* ALERT PLUGIN DEFINITION - * ======================= */ + /* ALERT PLUGIN DEFINITION + * ======================= */ - var old = $.fn.alert + 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 = 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.Constructor = Alert - /* ALERT NO CONFLICT - * ================= */ + /* ALERT NO CONFLICT + * ================= */ - $.fn.alert.noConflict = function () { - $.fn.alert = old - return this - } + $.fn.alert.noConflict = function () { + $.fn.alert = old + return this + } - /* ALERT DATA-API - * ============== */ + /* ALERT DATA-API + * ============== */ - $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) + $(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.defaults = { + loadingText: 'loading...' + } - $.fn.button.Constructor = Button + $.fn.button.Constructor = Button - /* BUTTON NO CONFLICT - * ================== */ + /* BUTTON NO CONFLICT + * ================== */ - $.fn.button.noConflict = function () { - $.fn.button = old - return this - } + $.fn.button.noConflict = function () { + $.fn.button = old + return this + } - /* BUTTON DATA-API - * =============== */ + /* 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') - }) + $(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 - - if (pos > (children.length - 1) || pos < 0) return - - if (this.sliding) { - return this.$element.one('slid', function () { - that.to(pos) - }) - } + Carousel.prototype = { - if (activePos == pos) { - return this.pause().cycle() - } - - return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) - } + 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 + } - , 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 - } + , to: function (pos) { + var $active = this.$element.find('.item.active') + , children = $active.parent().children() + , activePos = children.index($active) + , that = this - , next: function () { - if (this.sliding) return - return this.slide('next') - } + if (pos > (children.length - 1) || pos < 0) return - , prev: function () { - if (this.sliding) return - return this.slide('prev') - } + if (this.sliding) { + return this.$element.one('slid', function () { + that.to(pos) + }) + } - , 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 + if (activePos == pos) { + return this.pause().cycle() + } - this.sliding = true + return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) + } - isCycling && this.pause() + , 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 = $next.length ? $next : this.$element.find('.item')[fallback]() + , next: function () { + if (this.sliding) return + return this.slide('next') + } - e = $.Event('slide', { - relatedTarget: $next[0] - }) + , prev: function () { + if (this.sliding) return + return this.slide('prev') + } - if ($next.hasClass('active')) return + , 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') + } - 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() - isCycling && this.cycle() + return this + } - return this } - } - - /* CAROUSEL PLUGIN DEFINITION - * ========================== */ + /* CAROUSEL PLUGIN DEFINITION + * ========================== */ - var old = $.fn.carousel + 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() - }) - } + $.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() + }) + } - $.fn.carousel.defaults = { - interval: 5000 - , pause: 'hover' - } + $.fn.carousel.defaults = { + interval: 5000 + , pause: 'hover' + } - $.fn.carousel.Constructor = Carousel + $.fn.carousel.Constructor = Carousel - /* CAROUSEL NO CONFLICT - * ==================== */ + /* CAROUSEL NO CONFLICT + * ==================== */ - $.fn.carousel.noConflict = function () { - $.fn.carousel = old - return this - } + $.fn.carousel.noConflict = function () { + $.fn.carousel = old + return this + } - /* CAROUSEL DATA-API - * ================= */ + /* 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() - }) + $(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' + } - , dimension: function () { - var hasWidth = this.$element.hasClass('width') - return hasWidth ? 'width' : 'height' - } + , show: function () { + var dimension + , scroll + , actives + , hasData - , show: function () { - var dimension - , scroll - , actives - , hasData + if (this.transitioning) return - if (this.transitioning) return + dimension = this.dimension() + scroll = $.camelCase(['scroll', dimension].join('-')) + actives = this.$parent && this.$parent.find('> .accordion-group > .in') - 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) + } - 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]) + } - 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) + } - , 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() - , reset: function (size) { - var dimension = this.dimension() + this.$element + .removeClass('collapse') + [dimension](size || 'auto') + [0].offsetWidth - this.$element - .removeClass('collapse') - [dimension](size || 'auto') - [0].offsetWidth + this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') - this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') + return this + } - 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) + } - , 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) - this.$element.trigger(startEvent) + if (startEvent.isDefaultPrevented()) return - if (startEvent.isDefaultPrevented()) return + this.transitioning = 1 - this.transitioning = 1 + this.$element[method]('in') - this.$element[method]('in') + $.support.transition && this.$element.hasClass('collapse') ? + this.$element.one($.support.transition.end, complete) : + complete() + } - $.support.transition && this.$element.hasClass('collapse') ? - this.$element.one($.support.transition.end, complete) : - complete() - } + , toggle: function () { + this[this.$element.hasClass('in') ? 'hide' : 'show']() + } - , toggle: function () { - this[this.$element.hasClass('in') ? 'hide' : 'show']() } - } + /* COLLAPSE PLUGIN DEFINITION + * ========================== */ - /* COLLAPSE PLUGIN DEFINITION - * ========================== */ + var old = $.fn.collapse - 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]() - }) - } + $.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]() + }) + } - $.fn.collapse.defaults = { - toggle: true - } + $.fn.collapse.defaults = { + toggle: true + } - $.fn.collapse.Constructor = Collapse + $.fn.collapse.Constructor = Collapse - /* COLLAPSE NO CONFLICT - * ==================== */ + /* COLLAPSE NO CONFLICT + * ==================== */ - $.fn.collapse.noConflict = function () { - $.fn.collapse = old - return this - } + $.fn.collapse.noConflict = function () { + $.fn.collapse = old + return this + } - /* COLLAPSE DATA-API - * ================= */ + /* 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) - }) + $(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 = { + Dropdown.prototype = { - constructor: Dropdown + constructor: Dropdown - , toggle: function (e) { - var $this = $(this) - , $parent - , isActive + , toggle: function (e) { + var $this = $(this) + , $parent + , isActive - if ($this.is('.disabled, :disabled')) return + if ($this.is('.disabled, :disabled')) return - $parent = getParent($this) + $parent = getParent($this) - isActive = $parent.hasClass('open') + isActive = $parent.hasClass('open') - clearMenus() + clearMenus() - if (!isActive) { - $parent.toggleClass('open') - } + if (!isActive) { + $parent.toggleClass('open') + } - $this.focus() + $this.focus() - return false - } + return false + } - , keydown: function (e) { - var $this - , $items - , $active - , $parent - , isActive - , index + , keydown: function (e) { + var $this + , $items + , $active + , $parent + , isActive + , index - if (!/(38|40|27)/.test(e.keyCode)) return + if (!/(38|40|27)/.test(e.keyCode)) return - $this = $(this) + $this = $(this) - e.preventDefault() - e.stopPropagation() + e.preventDefault() + e.stopPropagation() - if ($this.is('.disabled, :disabled')) return + if ($this.is('.disabled, :disabled')) return - $parent = getParent($this) + $parent = getParent($this) - isActive = $parent.hasClass('open') + isActive = $parent.hasClass('open') - if (!isActive || (isActive && e.keyCode == 27)) return $this.click() + if (!isActive || (isActive && e.keyCode == 27)) return $this.click() - $items = $('[role=menu] li:not(.divider):visible a', $parent) + $items = $('[role=menu] li:not(.divider):visible a', $parent) - if (!$items.length) return + if (!$items.length) return - index = $items.index($items.filter(':focus')) + 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 + 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() - } + $items + .eq(index) + .focus() + } - } + } - function clearMenus() { - $(toggle).each(function () { - getParent($(this)).removeClass('open') - }) - } + function clearMenus() { + $(toggle).each(function () { + getParent($(this)).removeClass('open') + }) + } - function getParent($this) { - var selector = $this.attr('data-target') - , $parent + function getParent($this) { + var selector = $this.attr('data-target') + , $parent - if (!selector) { - selector = $this.attr('href') - selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 - } + if (!selector) { + selector = $this.attr('href') + selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + } - $parent = $(selector) - $parent.length || ($parent = $this.parent()) + $parent = $(selector) + $parent.length || ($parent = $this.parent()) - return $parent - } + return $parent + } - /* DROPDOWN PLUGIN DEFINITION - * ========================== */ + /* DROPDOWN PLUGIN DEFINITION + * ========================== */ - var old = $.fn.dropdown + 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 = 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.Constructor = Dropdown - /* DROPDOWN NO CONFLICT - * ==================== */ + /* DROPDOWN NO CONFLICT + * ==================== */ - $.fn.dropdown.noConflict = function () { - $.fn.dropdown = old - return this - } + $.fn.dropdown.noConflict = function () { + $.fn.dropdown = old + return this + } - /* APPLY TO STANDARD DROPDOWN ELEMENTS - * =================================== */ + /* 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) + $(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']() - } + , toggle: function () { + return this[!this.isShown ? 'show' : 'hide']() + } - , show: function () { - var that = this - , e = $.Event('show') + , show: function () { + var that = this + , e = $.Event('show') - this.$element.trigger(e) + this.$element.trigger(e) - if (this.isShown || e.isDefaultPrevented()) return + if (this.isShown || e.isDefaultPrevented()) return - this.isShown = true + this.isShown = true - this.escape() + this.escape() - this.backdrop(function () { - var transition = $.support.transition && that.$element.hasClass('fade') + 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 - } + if (!that.$element.parent().length) { + that.$element.appendTo(document.body) //don't move modals dom position + } - that.$element - .show() + that.$element + .show() - if (transition) { - that.$element[0].offsetWidth // force reflow - } + if (transition) { + that.$element[0].offsetWidth // force reflow + } - that.$element - .addClass('in') - .attr('aria-hidden', false) + that.$element + .addClass('in') + .attr('aria-hidden', false) - that.enforceFocus() + that.enforceFocus() - transition ? - that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : - that.$element.focus().trigger('shown') + transition ? + that.$element.one($.support.transition.end, function () { + that.$element.focus().trigger('shown') + }) : + that.$element.focus().trigger('shown') - }) - } + }) + } - , hide: function (e) { - e && e.preventDefault() + , hide: function (e) { + e && e.preventDefault() - var that = this + var that = this - e = $.Event('hide') + e = $.Event('hide') - this.$element.trigger(e) + this.$element.trigger(e) - if (!this.isShown || e.isDefaultPrevented()) return + if (!this.isShown || e.isDefaultPrevented()) return - this.isShown = false + this.isShown = false - this.escape() + this.escape() - $(document).off('focusin.modal') + $(document).off('focusin.modal') - this.$element - .removeClass('in') - .attr('aria-hidden', true) + this.$element + .removeClass('in') + .attr('aria-hidden', true) - $.support.transition && this.$element.hasClass('fade') ? - this.hideWithTransition() : - this.hideModal() - } + $.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') - } - } - - , hideWithTransition: function () { - var that = this - , timeout = setTimeout(function () { - that.$element.off($.support.transition.end) - that.hideModal() - }, 500) - - this.$element.one($.support.transition.end, function () { - clearTimeout(timeout) - that.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() + } + }) + } - , hideModal: function (that) { - this.$element - .hide() - .trigger('hidden') + , 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') + } + } - this.backdrop() - } + , hideWithTransition: function () { + var that = this + , timeout = setTimeout(function () { + that.$element.off($.support.transition.end) + that.hideModal() + }, 500) + + this.$element.one($.support.transition.end, function () { + clearTimeout(timeout) + that.hideModal() + }) + } + + , hideModal: function (that) { + this.$element + .hide() + .trigger('hidden') - , removeBackdrop: function () { - this.$backdrop.remove() - this.$backdrop = null - } + this.backdrop() + } + + , removeBackdrop: function () { + this.$backdrop.remove() + this.$backdrop = null + } - , backdrop: function (callback) { - var that = this - , animate = this.$element.hasClass('fade') ? 'fade' : '' + , backdrop: function (callback) { + var that = this + , animate = this.$element.hasClass('fade') ? 'fade' : '' - if (this.isShown && this.options.backdrop) { - var doAnimate = $.support.transition && animate + if (this.isShown && this.options.backdrop) { + var doAnimate = $.support.transition && animate - this.$backdrop = $('